外接矩形で画像をクロップする方法のメモ。
import sys import cv2 def main(): in_file = sys.argv[1] out_file = sys.argv[2] img = cv2.imread(in_file) # グレースケール img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) res, img_bw = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # 輪郭 cs, h = cv2.findContours(img_bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # x, y の最小, 最大でトリミング min_x, min_y, w, h = cv2.boundingRect(cs[0]) max_x = min_x + w max_y = min_y + h for i in range(1, len(cs)): x1, y1, w, h = cv2.boundingRect(c) x2 = x1 + w y2 = y1 + h if x1 < min_x: min_x = x1 if y1 < min_y: min_y = y1 if x2 > max_x: max_x = x2 if y2 > max_y: max_y = y2 # トリミング tgt_img = img[min_y:max_y, min_x:max_x] cv2.imwrite(out_file, tgt_img) return 0 if __name__ == '__main__': res = main() exit(res)