【发布时间】:2022-06-29 02:36:25
【问题描述】:
我有检测颜色的 python 代码。一旦检测到颜色,我就会找到轮廓并绘制它们。以下是原图:
下面是带有轮廓和边界框的图像:
如您所见,检测到很多轮廓,因此存在多个边界框。有没有办法将这些边界框合并为一个。下面是代码
import cv2
import imutils
import numpy as np
image = cv2.imread("L00001.png")
image = imutils.resize(image, width=800)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_bound = np.array([45, 150, 20])
upper_bound = np.array([75, 305, 255])
origMask = cv2.inRange(hsv, lower_bound, upper_bound)
contours, h = cv2.findContours(origMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
new = np.vstack(contours)
area = cv2.contourArea(c)
if area > 10:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 2)
cv2.imshow("FRAME", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
【问题讨论】:
-
我建议您查看您的 origMask 并查看是否可以调整颜色范围。如果做不到这一点,也许在得到你的轮廓之前使用一些形态来关闭和间隙。
-
我喜欢@fmw42 的建议。蛮力的方法是通过轮廓边界框搜索 min(x)、min(y) 和 max(x)、max(y),这将为您提供角点。
-
我已经能够通过使用连通分量分析来做到这一点。将尽快回答并发布代码
标签: python bounding-box opencv-contour color-detection