1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import cv2 import numpy as np
min_w = 90 min_h = 90
line_high = 550
offset = 7
carno =0
cars = []
def center(x, y, w, h): x1 = int(w/2) y1 = int(h/2) cx = x + x1 cy = y + y1
return cx, cy
cap = cv2.VideoCapture('video.mp4')
bgsubmog = cv2.bgsegm.createBackgroundSubtractorMOG()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
while True: ret, frame = cap.read() if(ret == True):
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(frame, (3,3), 5) mask = bgsubmog.apply(blur)
erode = cv2.erode(mask, kernel)
dilate = cv2.dilate(erode, kernel, iterations = 3)
close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel) close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, kernel)
cnts, h = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.line(frame, (10, line_high), (1200, line_high), (255, 255, 0), 3)
for (i, c) in enumerate(cnts): (x,y,w,h) = cv2.boundingRect(c)
isValid = ( w >= min_w ) and ( h >= min_h) if( not isValid): continue
cv2.rectangle(frame, (x, y), (x+w, y+h), (0,0,255), 2) cpoint = center(x, y, w, h) cars.append(cpoint) cv2.circle(frame, (cpoint), 5, (0,0,255), -1)
for (x, y) in cars: if( (y > line_high - offset) and (y < line_high + offset ) ): carno +=1 cars.remove((x , y )) print(carno) cv2.putText(frame, "Cars Count:" + str(carno), (500, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,0,0), 5) cv2.imshow('video', frame) key = cv2.waitKey(1) if(key == 27): break
cap.release() cv2.destroyAllWindows()
|