python,opencvで任意の大きさの面積だけを抽出する
検索してもあんまり出てこなかったりして、右往左往してなんとか書きました。
でももっと効率の良い書き方があると思いますので知っていたら教えてください、、、
環境
ubuntu16.04
opencv3.4
python3.5
プログラム
import cv2 import numpy as np frame = cv2.imread("img.png") height = frame.shape[0] width = frame.shape[1] img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #2値化 thresh = 40 max_pixel = 255 ret, img_dst = cv2.threshold(img_gray, thresh, max_pixel, cv2.THRESH_BINARY) #指定領域面積のみ抽出 dst = np.zeros((height, width, 1), np.uint8) connectivity = 4 min_area=100 max_area=10000 output = cv2.connectedComponentsWithStats(img_dst, connectivity, cv2.CV_32S) for i in range(output[0]): if output[2][i][4] >= min_area and output[2][i][4] <= max_area: cv2.rectangle(dst, (output[2][i][0], output[2][i][1]), ( output[2][i][0] + output[2][i][2], output[2][i][1] + output[2][i][3]), (255, 255, 255), -1) res = cv2.bitwise_and(dst,img_dst) cv2.imshow("gray", img_dst) cv2.imshow("frame", frame) cv2.imshow("result", res) k = cv2.waitKey(0) cv2.destroyAllWindows()