Ask Your Question
1

Grab second largest contour from max()

asked 2017-02-14 19:34:57 -0600

Daltz3 gravatar image

updated 2017-02-14 19:36:08 -0600

I'm completely new to OpenCV and Python (Java Developer) so It'd be much appreciated if detailed instructions were included. Thanks.

Okay, My goal is to grab two contours (same color) that are the largest contour and the second largest contour AND OR the same size contour. How would I go about this?

EDIT: Also as a note, my current code grabs the biggest contour and the smallest contour.

    # import the necessary packages
import numpy as np
import imutils
import cv2

#define HSV ranges

# green
greenLower = (35,21,62)
greenUpper = (90,255,255)

camera = cv2.VideoCapture(0)

while True:
    (grabbed, frame) = camera.read()

    #convert to HSV color space
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    #construct a mask for the color, then perform
    #a series of dilations and erosions to remove any small
    #blobs left in the mask

    green_mask = cv2.inRange(hsv, greenLower, greenUpper)
    green_mask = cv2.erode(green_mask, None, iterations=2)
    green_mask = cv2.dilate(green_mask, None, iterations=2)

    grncnts = cv2.findContours(green_mask.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)[-2]

    if len(grncnts)>0:
        green=max(grncnts, key=cv2.contourArea)
        (xg,yg,wg,hg) = cv2.boundingRect(green)
        cv2.rectangle(frame, (xg,yg), (xg+wg, yg+hg), (0,255,0), 2)
    if len(grncnts)>0:
        green=min(grncnts, key=cv2.contourArea)
        (xg,yg,wg,hg) = cv2.boundingRect(green)
        cv2.rectangle(frame, (xg,yg), (xg+wg, yg+hg), (0,255,0), 2)

    cv2.imshow("Frame", frame)
    #cv2.imshow("Mask", mask)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

# cleanup the camera and close open windows
camera.release()
cv2.destroyAllWindows()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2017-02-15 01:59:06 -0600

berak gravatar image

updated 2017-02-15 02:00:10 -0600

you've been using min() and max() there, in a similar way, you can just sort your list of rectangles by size:

>>> rects = [[1,2,3,4],[5,6,7,8],[4,3,2,1]]
>>> r2 = sorted(rects, key=lambda r: r[2]*r[3])
>>> r2
[[4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]
edit flag offensive delete link more

Comments

Could I see a working example of this? Like how do I change my code to match this?

Daltz3 gravatar imageDaltz3 ( 2017-02-15 16:35:07 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-02-14 19:34:57 -0600

Seen: 3,218 times

Last updated: Feb 15 '17