在 OpenCV Python 中围绕所有轮廓绘制一个矩形

新手上路,请多包涵

我有一个代码可以在对视频帧应用过滤器后识别轮廓。现在在我的例子中,我得到了 3 个轮廓,我通过在它们周围绘制矩形来显示它们,我想要做的是在所有这 3 个轮廓矩形周围绘制一个矩形。就像它将是一个更大的矩形,包含 3 个检测到的矩形。这是我检测和绘制轮廓周围矩形的简单代码。

 im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy = []

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    if w > 80 and h > 80:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('Motion Detector',frame)

原文由 Moeed Kundi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
2 个回答

也许尝试这样的事情:

 im2, contours, hierarchy = cv2.findContours(canny_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy = []

height, width, _ = canny_img.shape
min_x, min_y = width, height
max_x = max_y = 0

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    min_x, max_x = min(x, min_x), max(x+w, max_x)
    min_y, max_y = min(y, min_y), max(y+h, max_y)
    if w > 80 and h > 80:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)

if max_x - min_x > 0 and max_y - min_y > 0:
    cv2.rectangle(frame, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)

本质上,您想要跟踪最小的 x 和 y 坐标是什么以及最大的 x 和 y 坐标(包括宽度和高度)是什么,然后只需使用这些坐标绘制一个矩形。

原文由 pzp 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用麻木:

 boxes = []
for c in cnts:
    (x, y, w, h) = cv2.boundingRect(c)
    boxes.append([x,y, x+w,y+h])

boxes = np.asarray(boxes)
left, top = np.min(boxes, axis=0)[:2]
right, bottom = np.max(boxes, axis=0)[2:]

cv2.rectangle(frame, (left,top), (right,bottom), (255, 0, 0), 2)

原文由 lorenzo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题