dccsillag
dccsillag

Reputation: 957

OpenCV Python: cv2.findContours Returns to many contours

I'm working with a little program which will use OpenCV + python's background subtraction to count cars. I'm fine with background subtraction, I already have a background image. But when I use cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE), I get way too many contours. While I can do some basic filtering by checking contour area (cv2.contourArea(contour)), as shown in http://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/, not all cars are detected.

I also looked at cv2.groupRectangles(rectList, minNum[, eps]), but I can't seem to create a vector of rectangles (By the way, that's in http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html, last function).

My code to find contours/draw rectangles:

contours, im2 = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if MAXAREA >= cv2.contourArea(cnt) >= MINAREA:
        rect = cv2.minAreaRect(cnt)
        points = cv2.cv.BoxPoints(rect)
        cv2.rectangle(img, (int(points[1][0]), int(points[1][1])), (int(points[3][0]), int(points[3][1])), (0, 255, 0), 2)

(MINAREA and MAXAREA are the maximum and minimum areas for the contour to be drawn)

My Question: How can I either group rectangles or use some criteria to draw the correct rectangles (and keep cars from not being recognized)?

Any help is highly appreciated.

Upvotes: 0

Views: 14549

Answers (1)

Jijeesh
Jijeesh

Reputation: 29

As i have understood the question.You need to identify the rectangular shape(the car in the actual image) from the image.irrespective of the size.The minAreaRect function will fit a minimum area rectangle over all the contours given to it.This way u cannot identify the rectangle shape.But u can take this minimum rectangle as a template for each contours and match it with that particular contour.based on the matching score you can decide whether it is rectangular shape or not.One more approach you can try is How to detect simple geometric shapes using OpenCV.

Upvotes: 2

Related Questions