Drawing a rectangle around all contours in OpenCV Python

前端 未结 3 638
无人及你
无人及你 2021-02-06 15:54

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

相关标签:
3条回答
  • 2021-02-06 16:08

    Using numpy:

    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)
    
    0 讨论(0)
  • 2021-02-06 16:21

    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)
  • 2021-02-06 16:28

    If you want to box everything in a binary image, you can generate points from all non zero values and apply the algorithms on that. This is done as seen below:

        points = cv2.findNonZero(thresholdImage)
        rect = cv2.minAreaRect(points)
    
    0 讨论(0)
提交回复
热议问题