python+yolov3视频车辆检测代码
IDE工具:pycharm 2023
后端语言:python 3.11
import cv2
import numpy as np
def contour_check_car():
url_temp = "rtsp://xxxx:xxxxxx@192.168.2.176:554/h264/ch1/sub/av_stream"
# 打开视频文件
cap = cv2.VideoCapture(url_temp)
# 定义感兴趣区域(ROI)的坐标和大小
roi_x, roi_y, roi_width, roi_height = 150, 150, 50, 20
# 初始化前一帧
ret, prev_frame = cap.read()
# 初始化计数器
count = 0
object_in_roi = False
while True:
ret, frame = cap.read()
if not ret:
break
# 将当前帧和前一帧相减
frame_diff = cv2.absdiff(prev_frame, frame)
# 将差异图像转换为灰度图像
gray_diff = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY)
# 应用阈值来检测运动物体
_, thresh = cv2.threshold(gray_diff, 30, 255, cv2.THRESH_BINARY)
# 查找差异图像中的轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制矩形框以标记运动物体,并进行计数
for contour in contours:
if cv2.contourArea(contour) > 10: # 根据需要调整面积阈值
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 检查物体是否进入ROI
if x >= roi_x and y >= roi_y and x + w <= roi_x + roi_width and y + h <= roi_y + roi_height:
if not object_in_roi:
count += 1
object_in_roi = True
else:
object_in_roi = False
# 显示计数结果
cv2.putText(frame, f"Count: {count}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# 更新前一帧
prev_frame = frame.copy()
# 在帧上绘制ROI区域
cv2.rectangle(frame, (roi_x, roi_y), (roi_x + roi_width, roi_y + roi_height), (0, 255, 0), 2)
# 显示帧
cv2.imshow("Motion Detection and Counting", frame)
# 退出循环
if cv2.waitKey(30) & 0xFF == 27:
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
car_detector()