笔记和代码
import cv2
import numpy as np"""
车辆数量统计/人流量统计
"""
cap = cv2.VideoCapture(',/video.mp4')
mog = cv2.createBackgroundSubtractorMOG2()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
min_w = 100
min_h = 90
line_high = 600
cars = []
car = 0
offset = 6
def center(x, y, w, h):x1 = int(w / 2)y1 = int(h / 2)cx = int(x) + x1cy = int(y) + y1return cx, cy
while True:ret, frame = cap.read()if ret:gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)blur = cv2.GaussianBlur(gray, (3, 3), 5)frame_mask = mog.apply(blur)erode = cv2.erode(frame_mask, kernel)dilate = cv2.dilate(erode, kernel, iterations=2)close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel)contours, hierarchy = 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:continuecv2.rectangle(frame, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 2)x_point, y_point = center(x, y, w, h)cars.append((x_point, y_point))cv2.circle(frame, (x_point, y_point), 5, (0, 0, 255), -1)for (x, y) in cars:if (line_high - offset) < y < (line_high + offset):car += 1cars.remove((x, y))cv2.putText(frame, 'Vehicle Count:' + str(car), (500, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 5)cv2.imshow('video', close)key = cv2.waitKey(1)if key == 27:break
cap.release()
cv2.destroyAllWindows()