1 OpenCV车辆统计
1.1 OpenCV车辆统计步骤
- 用GMM获取前景掩码
- 形态学操作除去噪声
- 获取图像上的轮廓,根据轮廓特征筛选出车辆。
- 在图片上设置线计数线,对在线临界区域的车辆
参考项目地址:https://gitcode.com/gh_mirrors/opencv31/opencv
1.2 代码
# 去背景
# 加载视频
import cv2
import numpy as np
cap = cv2.VideoCapture('tracker.mp4')
bgsubmog = cv2.bgsegm.createBackgroundSubtractorMOG()
# 形态学kernel,用于过滤噪声
kernel= cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
## 轮廓最小外界矩形的宽高筛选是否是车辆
min_w = 90
min_h = 90
## 存储图片上的车辆
cars = []
# 检测线的高度, 超参数
line_high = 620
## 线的偏移量,即在line_high(+-)区域内的车辆被计数
offset = 7
## 存储车辆数
carno = 0
def center(x, y, w, h):
'''
根据车辆外接矩形的左上角坐标(x, y)和宽高(w, h)得出举行的对角线交点(cx, cy),根据(cx, cy)与line_high的关系计数。
'''
x1 = int(w/2)
y1 = int(h/2)
cx = int(x) + x1
cy = int(y) + y1
return cx, cy
while True:
ret, frame = cap.read()
if ret == True:
## 彩色图转灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
## 高斯滤波去噪
blur = cv2.GaussianBlur(gray, (3, 3), 5)
# 1. 获取前景掩码
mask = bgsubmog.apply(blur)
# 2.通过腐蚀操作去掉轮廓小的噪声
erode = cv2.erode(mask, kernel)
## 通过膨胀操作再把保留轮廓还原回来
dilate = cv2.dilate(erode, kernel, iterations=2)
## 闭操作, 去掉轮廓内部的噪声
close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel, iterations=2)
## 3.查找轮廓,筛选车辆
result, 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 (i, c) in enumerate(contours):
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 2)
## 通过外接矩形的宽高大小来过滤掉小轮廓.保留的轮廓都是车
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)
# 4.判断汽车是否过线.
for (x, y) in cars:
if y > (line_high - offset) and y < (line_high + offset):
# 计数加1
carno += 1
cars.remove((x, y))
print(carno)
## 打印计数信息
cv2.putText(frame, 'Vehicle Count:' + str(carno), (500, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 5)
cv2.imshow('frame', frame)
key = cv2.waitKey(10)
if key == 'q':
break
cap.release()
cv2.destroyAllWindows()
2 YOLOV8车流量统计
2.1 YOLOV8车流量统计步骤
- 读入视频
- 计数
(2.1) 导入YOLOv8模型
(2.2) 设置掩码
(2.3) 根据掩码获取图像部分区域,送入YOLOV8检测
(2.4)感兴趣区域送入YOLOV8检测
(2.5)获取检测框坐标
(2.6)遍历每个检测框,判断检测框中心是否经过指定区域
2.2 代码
import cv2 # cv2==4.10.0
import numpy as np # np==1.26.4
from ultralytics import YOLO
import matplotlib.path as mplPath
import matplotlib.pyplot as plt
def get_bboxes(preds: object):
''' object为模型输出,获取检测框
preds[0].boxes.xyxy
'''
Boxes = preds[0].boxes
B = np.array(Boxes.xyxy).astype(int)
return B
def get_center(bbox):
'''获取检测框的中心点'''
center = ((bbox[0] + bbox[2]) // 2, (bbox[1] + bbox[3]) // 2)
return center
def is_valid_detection(xc, yc):
'''判断框的中心点是都在POLYGON区域内'''
return mplPath.Path(POLYGON).contains_point((xc, yc))
## 多边形区域,如果车辆的所在的检测框在POLYGON中,则统计车辆数加一。
POLYGON = np.array([
[45, 460],
[830, 460],
[830, 462],
[45, 462]
])
def count_cars(cap: object):
# 2.1 导入YOLOv8模型
MODEL_NAMES = 'yolov8s.pt'
model = YOLO(MODEL_NAMES)
## car_num存储检测出车辆的数量
car_num = 0
## 2.2 设置掩码,只对图像的mask区域检测车辆、汽车、卡车
mask = np.zeros([720, 1280], np.uint8) # frame.shape(720, 1280, 3)
mask[400:620, 45:825] = 255 # 感兴趣区域设为255,只对感兴趣区域检测
while cap.isOpened():
status, frame = cap.read()
# 2.3 根据掩码获取图像部分区域
frame_mask = cv2.bitwise_and(frame, frame, mask = mask)
if not status:
break
# 2.4 感兴趣区域送入YOLOV8检测
preds = model.predict(frame_mask, classes=[2, 5, 7], conf=0.5) # 'bus':5,'car':2,'truck':7
# 2.5 获取检测框坐标
bboxes = get_bboxes(preds)
## 2.6 遍历每个检测框,判断检测框中心是否经过指定区域
for box in bboxes:
# 检测框中心
xc, yc = get_center(box)
# 如果检测框中心在指定区域,car_num累加
if is_valid_detection(xc, yc):
car_num += 1
# 画出每个检测框的中心
cv2.circle(img=frame, center=(xc, yc), radius=5, color=(0, 255, 0), thickness=-1)
# 画出检测框
cv2.rectangle(img=frame, pt1=(box[0], box[1]), pt2=(box[2], box[3]), color=(255, 0, 0), thickness=1)
# 再图像左上角显示数量数
cv2.putText(img=frame, text=f"Cars_num: {car_num}", org=(100, 100), fontFace=cv2.FONT_HERSHEY_PLAIN,
fontScale=3,
color=(0, 0, 255), thickness=3)
# 画出指定区域,此区域用于车辆计数
cv2.polylines(img=frame, pts=[POLYGON], isClosed=True, color=(0, 0, 255), thickness=4)
# 展示画面
cv2.imshow("frame", frame)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
# 1. 读入视频
VIDEO_PATH = "trafic.mp4"
cap = cv2.VideoCapture(VIDEO_PATH)
# 2. 计数
count_cars(cap)
车辆计数
问题:同一车辆会被多次计数,有些检测到的车辆没有被统计,此方法还需改进。