LoginSignup
0
2

More than 3 years have passed since last update.

画像内のA4プリントを切り出す

Posted at

画像内のA4プリントを切り出す

写真に存在するプリントを真上視点から切り抜いた画像に変換する。
image.png
上の写真を下の写真に変換できる。
image.png

コードに関する注意

  • 縦長のA4ファイルに変換するので横長の場合はxとyを書き換えること。
  • xが短辺の長さになっているので適度に書き換えること。

コード

cutting_a4.py
#カラー画像を受け取って紙を切り取って返す
def cutting_paper(img):
    x = 2000 #切り取り後のx座標
    y = int(x*1.415)
    img_gray = gray(img)
    #2値化
    ret,img_th1  = cv2.threshold(img_gray,220,255,cv2.THRESH_TOZERO_INV)
    img_not = cv2.bitwise_not(img_th1)
    ret,img_th2  = cv2.threshold(img_not,0,255, cv2.THRESH_BINARY | cv2.THRESH_OTSU )
    #輪郭抽出
    contours, hierarchy = cv2.findContours(img_th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    #2番目にでかい四角が紙の輪郭なのでpaper_tapを取り出す
    pic_tap = None #画像の輪郭
    paper_tap = None #紙の輪郭
    for i, con in enumerate(contours):
        size = cv2.contourArea(con)
        if pic_tap is None:
            pic_tap = (con,size)
            continue
        if pic_tap[1] <= size:
            pic_tap = (con,size)
            continue
        elif paper_tap is None:
            paper_tap = (con,size)
        elif paper_tap[1] <= size:
            paper_tap = (con,size)

    #直線近似して描画
    epsilon = 0.1*cv2.arcLength(paper_tap[0],True)
    paper_corners= cv2.approxPolyDP(paper_tap[0],epsilon,True)#紙の頂点座標
    fix_con = np.array([[[0,0]],[[x,0]],[[x,y]],[[0,y]]], dtype="int32")#整形後のサイズ

    M = cv2.getPerspectiveTransform(np.float32(paper_corners),np.float32(fix_con))#変換行列の生成
    img_trans = cv2.warpPerspective(img,M,(x,y))#変換
    return img_trans

img = cv2.imread('input.png',-1)
cv2.imwrite("output.png", img)
plt.imshow(plt.imread("output.png"))
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2