1.视频加载
import cv2
import numpy as np
cap = cv2.VideoCapture('./video.mp4')
2.背景减除对象
mog = cv2.bgsegm.createBackgroundSubtractorMOG()
3.形态学卷积核
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
4.外接矩形中心点
min_w = 90
min_h = 90
line_high = 600
offset = 7
cars = []
carno = 0
def center(x, y, w, h):
x1 = int(w / 2)
y1 = int(h / 2)
cx = int(x) + x1
cy = int(y) + y1
return cx, cy
5.视频帧循环读取
while True:
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 5)
mask = mog.apply(blur)
erode = cv2.erode(mask, kernel)
dialte = cv2.dilate(erode, kernel, iterations=2)
close = cv2.morphologyEx(dialte, cv2.MORPH_CLOSE, kernel)
contours, 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 contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
is_valid = (w >= min_w) and (h >= min_h)
if not is_valid:
continue
cv2.rectangle(frame, (int(x), int(y)), (int(x + w), int(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, 'Vehicle Count:' + str(carno), (500, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 5)
cv2.imshow('frame', frame)
key = cv2.waitKey(1)
if key == 27:
break
6.释放资源
cap.release()
7.摧毁窗口
cv2.destroyAllWindows()
1
2
3
4
5
6
