python+yolov3视频车辆检测代码

本文介绍了如何使用Python3.11和YOLOv3在PyCharmIDE中实现视频车辆检测,包括ROI区域的设定、运动物体计数和实时帧处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值