Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a rectangle around all contours in 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)
like image 808
Moeed Kundi Avatar asked Oct 23 '16 14:10

Moeed Kundi


People also ask

How do you draw a bounding box around contours?

The basic idea is to find the Xmin, Xmax, Ymin, Ymax of each identified coordinates of the contour and then create a rectangle using it. Lets understand this with an example: Import the necessary libraries, read the input file, convert it to grayscale and plot it.


1 Answers

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.

like image 87
pzp Avatar answered Sep 30 '22 16:09

pzp