import cv2
import numpy as np
min_w = 60
min_h = 60
# 设置检测线的高度 和其 偏移量
line_high = 200
line_offset = 6
# 存放有效车辆
cars = []
# 统计车数
carnum = 0
# 计算中心位置
def car_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('../VideoFile/Cars1.mp4')
bgsubmog = cv2.bgsegm.createBackgroundSubtractorMOG() # 去背景方法
# 形态学kernel
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
while True: # 逐帧读取
ret, frame = cap.read()
if ret:
# 灰度化
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# (高斯)去噪
blur = cv2.GaussianBlur(gray, (5, 5), 5)
# 去背景
mask = bgsubmog.apply(blur)
# 腐蚀
erode = cv2.erode(mask, kernel)
# 膨胀
dilate = cv2.dilate(erode, kernel, iterations=4)
# 闭运算
close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel)
# close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, kernel)
# 查找轮廓 返回轮廓cnt和层级关系ceng
cnts, ceng = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 画一条检测线
cv2.line(frame, (0, line_high), (640, line_high), (255, 255, 0), 2)
for (i, cnt) in enumerate(cnts):
(x, y, w, h) = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
# 对车辆的宽高进行判断
# 以验证是否是有效的车辆
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 = car_center(x, y, w, h)
cars.append(cpoint)
cv2.circle(frame, cpoint, 5, (0, 0, 255), -1)
for (x, y) in cars:
if line_high + line_offset > y > line_high - line_offset:
carnum += 1
cars.remove((x, y))
# print(carnum)
cv2.putText(frame, 'Up Vehicle Count:' + str(carnum), (50, 50), cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (255, 0, 0))
cv2.imshow('video', frame)
# cv2.imshow('close', close)
key = cv2.waitKey(2)
if key == 27: # 键盘中的ESC
break
cap.release()
cv2.destroyAllWindows()
CV-车辆统计
于 2024-03-08 19:05:14 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)