Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Try this:

import cv2

backsub = cv2.createBackgroundSubtractorMOG2()  
capture = cv2.VideoCapture('../../video/traffic.mp4') 
i = 0
minArea = 5
font = cv2.FONT_HERSHEY_SIMPLEX

while True:
    ret, frame = capture.read()
    fgmask = backsub.apply(frame, None, 0.01)
    erode = cv2.erode(fgmask, None, iterations=2)      
    moments = cv2.moments(erode, True)               
    area = moments['m00']

    if moments['m00'] >= minArea:


       x = (moments['m10'] // moments['m00'])
        y = (moments['m01'] // moments['m00'])
        cv2.line(frame, (220, 470),(560, 470), (0, 0, 255),2)
        if x >= 190 and x <= 560 and y >= 470 and y <= 500:        
            i += 1
            print(i)

    cv2.putText(frame,'COUNT: %r' %i, (10,30), font, 1, (255, 0, 0), 2)
    cv2.imshow("Track", frame)
    cv2.imshow("background sub", fgmask)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

In line 19 and 20. Change cv2.line coordinates to suit your needed. Change x, y coordinates.

cv2.line(frame, (220, 470),(560, 470), (0, 0, 255),2)
if x >= 190 and x <= 560 and y >= 470 and y <= 500:

You will have to play around.

Try this:

import cv2

backsub = cv2.createBackgroundSubtractorMOG2()  
capture = cv2.VideoCapture('../../video/traffic.mp4') 
i = 0
minArea = 5
font = cv2.FONT_HERSHEY_SIMPLEX

while True:
    ret, frame = capture.read()
    fgmask = backsub.apply(frame, None, 0.01)
    erode = cv2.erode(fgmask, None, iterations=2)      
    moments = cv2.moments(erode, True)               
    area = moments['m00']

    if moments['m00'] >= minArea:


       x = (moments['m10'] // moments['m00'])
        y = (moments['m01'] // moments['m00'])
        cv2.line(frame, (220, 470),(560, 470), (0, 0, 255),2)
        if x >= 190 and x <= 560 and y >= 470 and y <= 500:        
            i += 1
            print(i)

    cv2.putText(frame,'COUNT: %r' %i, (10,30), font, 1, (255, 0, 0), 2)
    cv2.imshow("Track", frame)
    cv2.imshow("background sub", fgmask)
    key = cv2.waitKey(1)
    if key == is ord('q'):
        break

In line 19 and 20. Change cv2.line coordinates to suit your needed. Change x, y coordinates.

cv2.line(frame, (220, 470),(560, 470), (0, 0, 255),2)
if x >= 190 and x <= 560 and y >= 470 and y <= 500:

You will have to play around.