FindContours returing only one contour for two objects

asked 2016-10-28 06:52:08 -0600

marcosbontempo gravatar image

Hello,

I'm trying to count people with a motion detection code. It works fine if only one person is walking but, when they walk side by side, it counts two as one. I think the problem is in findContours, because it's returning only one contour.

Here is my code:

import cv2
import numpy as np

c = cv2.VideoCapture(0)
_,f = c.read()

avg2 = np.float32(f)

while(1):
    _,f = c.read()

    cv2.accumulateWeighted(f,avg2,0.1)
    res2 = cv2.convertScaleAbs(avg2)
    gray_res = cv2.cvtColor(res2, cv2.COLOR_BGR2GRAY)

    # Get difference between frames 
    gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)

    # compute the absolute difference between the current frame and background
    frameDelta = cv2.absdiff(gray_res, gray)
    thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]

    # dilate the thresholded image to fill in holes, then find contours
    # on thresholded image
    thresh = cv2.dilate(thresh, None, iterations=2)
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # loop over the contours
    for cnt in cnts:
    # compute the bounding box for the contour, draw it on the frame,
    # and update the text
        (x, y, w, h) = cv2.boundingRect(cnt)
        cv2.rectangle(f, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.imshow('img',f)
    cv2.imshow('avg2',res2)
    cv2.imshow('delta',frameDelta)

cv2.destroyAllWindows()
c.release()

And here is a image of what's happening:

image description

I already tried to use the size of the contour to check if there are two persons but sometimes the size of one person is equal of the size of two.

Does anybody have an idea of how to count two people if they are walking together? I was thinking about counting the heads, but I cannot find any way of doing that. Sometimes they walk so close that there is no space between their bodies, only between their heads. Do I have to check inside of the contour?

Any tip will be very helpful,

Thanks

edit retag flag offensive close merge delete