2015年3月18日水曜日

[Python][OpenCV]OpenCVで余白削除

# -*- coding:utf-8 -*-
import cv2

img = cv2.imread('test.png')
img2 = cv2.imread('test.png')

# Grayscale に変換
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 結果を表示
#cv2.imshow('img', img)
#cv2.imshow('img2', img2)

# 2 値化
ret, thresh = cv2.threshold(img2, 250, 255, cv2.THRESH_BINARY)
#cv2.imshow('thresh', thresh)

# 輪郭を取得
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# i = 1 は画像全体の外枠になるのでカウントに入れない
x1 = []
y1 = []
x2 = []
y2 = []
for i in range(1, len(contours)):
    # ret の中身は (x, y, w, h)
    ret = cv2.boundingRect(contours[i])
    x1.append(ret[0])
    y1.append(ret[1])
    x2.append(ret[0] + ret[2])
    y2.append(ret[1] + ret[3])

x1_min = min(x1)
y1_min = min(y1)
x2_max = max(x2)
y2_max = max(y2)
cv2.rectangle(img, (x1_min, y1_min), (x2_max, y2_max), (0, 255, 0), 2)
cv2.imshow('img', img)
cv2.imwrite('test_cropRectangle.png', img)

crop_img = img2[y1_min:y2_max, x1_min:x2_max]
cv2.imshow('crop_img', crop_img)
cv2.imwrite('test_cropped.png', crop_img)

cv2.waitKey(0)
cv2.destroyAllWindows()
元画像

全画像の外枠検出結果

余白削除結果

0 件のコメント:

コメントを投稿