这可以通过 OpenCV 来完成,方法是检测绿色区域,然后挑选出最大的区域。有几种方法可以检测绿色区域,包括cv2.inRange 和cv2.threshold。
1。识别绿色区域
cv2.inRange
使用inRange,您可以识别一定范围内的颜色。例如:
lower_bound = (0,100,0)
upper_bound = (10,255,10)
因此可以识别颜色介于lower_bound 和upper_bound 之间的像素以创建带有
的蒙版
mask = cv2.inRange(im, lower_bound, upper_bound)
这是绿色区域的mask:
cv2.threshold
同样,阈值化将创建绿色区域的蒙版。首先,将图像转为灰度。
imgray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
但是,如果您对该图像进行阈值处理,它将识别出白色区域,因此我们希望得到 cv2.THRESH_BINARY_INV 找到的阈值的倒数
ok, thresh = cv2.threshold(imgray, 200, 255, cv2.THRESH_BINARY_INV)
这是阈值图像:
可以看出,thresh 和 mask 标识绿色区域。
2。轮廓
一旦我们有了掩码或阈值图像,我们就可以通过寻找轮廓来识别白色区域。我将使用mask 图像(thresh 也可以使用)。
(im2, contours, hierarchy) = cv2.findContours(mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
我们特别想要contours,它提供了一组可用于勾勒绿色区域的点。我们想要创建最大轮廓区域的轮廓,我们可以通过首先将它们从大到小排列,然后取第一个来找到它。
ordered_cnts = sorted(contours, key=cv2.contourArea, reverse=True)
largest_cnt = ordered_cnts[0]
largest_cnt 是以下一组点:
[[[ 0 701]]
[[ 0 999]]
[[298 999]]
[[298 701]]
[[289 701]]
[[288 702]]
[[287 701]]]
这些点可用于勾勒图像左下角的绿色框。我们只需要一个矩形,因此我们可以通过找到包围所有这些点的最小矩形来勾勒整个轮廓。
rect = cv2.minAreaRect(largest_cnt)
box = cv2.boxPoints(rect)
box 给出了rect 四个角的点列表。我们可以使用numpy 转换为整数点,并获取框的限制来裁剪图像。
box = np.array(box, dtype=int)
x0, y0 = np.min(box,axis=0)
x1, y1 = np.max(box,axis=0)
crop = im[y0:y1, x0:x1]
crop 图片:
组合代码
lower_bound = (0,100,0)
upper_bound = (10,255,10)
mask = cv2.inRange(im, lower_bound, upper_bound)
(im2, cnts, hierarchy) = cv2.findContours(mask, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
ordered_cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
largest_cnt = ordered_cnts[0]
rect = cv2.minAreaRect(largest_cnt)
box = cv2.boxPoints(rect)
box = np.array(box, dtype=int)
x0, y0 = np.min(box,axis=0)
x1, y1 = np.max(box,axis=0)
crop = im[y0:y1, x0:x1]