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

i have a code which identifies contours after applying filters on video frames. Now in my case i get 3 contours and i show them by drawing rectangles around them, what i want to do is drawing a rectangle around all these 3 contour rectangles. like it will be a larger rectangle, containing 3 detected rectangles.

Here's my simple code of detecting and drawing rectangles around contours.

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)

解决方案

Maybe try something like this:

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)

Essentially you want to keep track of what the smallest x and y coordinates are and what the largest x and y coordinates (including the width and height) are, and then just draw a rectangle with those coordinates.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值