本文共 3356 字,大约阅读时间需要 11 分钟。
本文将详细介绍一个基于 Python OpenCV 的车辆检测与统计系统,主要用于高速公路道路上汽车的自动侦测、识别及数量统计。该系统能够实时监测道路上的车辆,分类统计车辆类型,并提供车辆数量的动态变化数据。
该系统的核心功能包括:
系统运行环境要求:
import cv2import numpy as npimport time# 初始化视频捕获cap = cv2.VideoCapture("video.mp4")# 背景模型与阴影检测fgbg = cv2.createBackgroundSubtractors( detectShadows=False, history=200, varThreshold=90)# 预定义车辆检测参数cars = []max_p_age = 5pid = 1cnt_up = 0cnt_down = 0# 车道线与检测范围设置line_up = 400line_down = 250up_limit = int(4.5 * (500 / 5))# 车辆分类参数font = cv2.FONT_HERSHEY_SIMPLEXup_limit = int(4.5 * (500 / 5))while cap.isOpened(): # 读取视频帧 ret, frame = cap.read() # 调整视频比例 frame = cv2.resize(frame, (900, 500)) # 更新车辆位置信息 for i in cars: i.age_one() # 前景背景模型检测 fgmask = fgbg.apply(frame) # 边缘检测与轮廓提取 contours0, hierarchy = cv2.findContours( fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE ) # 车辆检测与分类 for cnt in contours0: area = cv2.contourArea(cnt) if area > 300: m = cv2.moments(cnt) cx = int(m['m10'] / m['m00']) cy = int(m['m01'] / m['m00']) x, y, w, h = cv2.boundingRect(cnt) # 车辆分类与统计 new = True if cy in range(up_limit, down_limit): for i in cars: if (abs(x - i.getX()) <= w and abs(y - i.getY()) <= h): new = False i.updateCoords(cx, cy) if i.going_UP(line_down, line_up): cnt_up += 1 elif i.going_DOWN(line_down, line_up): cnt_down += 1 break if new: p = vehicles.Car(pid, cx, cy, max_p_age) cars.append(p) pid += 1 # 绘制检测框 cv2.circle(frame, (cx, cy), 2, (0, 0, 255), -1) # 车辆信息可视化 for i in cars: cv2.putText(frame, str(i.getId()), (i.getX(), i.getY()), font, 0.3, (255, 255, 0), 1, cv2.LINE_AA) # 车辆类型判断 if line_down + 20 <= i.getY() <= line_up - 20: a = (h + 0.74 * w - 100) if a >= 0: cv2.putText(frame, "Truck", (i.getX(), i.getY()), font, 1, (0, 0, 255), 2, cv2.LINE_AA) else: cv2.putText(frame, "car", (i.getX(), i.getY()), font, 1, (0, 0, 255), 2, cv2.LINE_AA) # 动态显示界面 cv2.line(frame, (0, line_up), (900, line_up), (0, 0, 255), 3, 8) cv2.line(frame, (0, up_limit), (900, up_limit), (0, 0, 0), 1, 8) cv2.line(frame, (0, down_limit), (900, down_limit), (255, 255, 0), 1, 8) cv2.line(frame, (0, line_down), (900, line_down), (255, 0, 0), 3, 8) cv2.imshow('Frame', frame) if cv2.waitKey(1) & 0xff == ord('q'): breakelse: cap.release()cv2.destroyAllWindows() 本文介绍了一个基于 Python OpenCV 的车辆检测与统计系统,详细解释了系统的功能、实现细节及优势。该系统能够有效地在高速公路道路上监测车辆,提供重要的交通流量数据,为智能交通管理提供支持。
转载地址:http://zxkr.baihongyu.com/