# -*- coding:utf-8 -*-
import cv2
img = cv2.imread('cropped.jpg')
img2 = cv2.imread('cropped.jpg')
# Grayscale に変換
img_gs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 2 値化
ret, thresh = cv2.threshold(img_gs, 250, 255, cv2.THRESH_BINARY)
# 輪郭を取得
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.imwrite('cropped_edge_rectangle.jpg', img)
# ギリギリで切り出し
crop_img = img2[y1_min:y2_max, x1_min:x2_max]
cv2.imwrite('cropped_edge.jpg', crop_img)
# 少し余白を付けて付けて切り出し
offset = 100
y1_min -= offset
y2_max += offset
x1_min -= offset
x2_max += offset
crop_img = img2[y1_min:y2_max, x1_min:x2_max]
cv2.imwrite('cropped_edge_offset.jpg', crop_img)
元画像
枠取りをした結果
ギリギリで切り出した結果
少し余白を付けて切り出した結果







