一、实验目的

用OpenCV编写一个车辆计数程序,强化对课堂讲授内容如图像腐蚀、轮廓提取、边缘检测、视频读写等知识的深入理解和灵活应用。

二、实验要求

1、用OpenCV编写一个车辆计数程序,对一段视频里道路上的来往车辆进行计数统计,要求避免同一车辆重复统计,并尽量避免漏检、错检;
2、认真撰写实验报告,要求说明实验原理,对实验过程叙述清楚,关键代码给出注释,对实验结果给出合理解释,实验分析部分则需要指出实验结果优劣的原因以及如何进一步提高实验性能的方法或手段。
3、利用python版的OpenCV编写代码。

三、实验过程

import cv2
import numpy as np

min_w = 90
min_h = 90

#检测线的高度
line_high = 550

#线的偏移
offset = 7

#统计车的数量
carno =0

#存放有效车辆的数组
cars = []

def 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('video.mp4')

bgsubmog =cv2.createBackgroundSubtractorMOG2() #去背景
#形态学kernel
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))

while True:
    ret, frame = cap.read()
    if(ret == True):     

        #灰度
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #去噪(高斯)
        blur = cv2.GaussianBlur(frame, (3,3), 5)
        #去背影
        mask = bgsubmog.apply(blur)

        #腐蚀, 去掉图中小斑块
        erode = cv2.erode(mask, kernel) 

        #膨胀, 还原放大
        dilate = cv2.dilate(erode, kernel, iterations = 3)

        #闭操作,去掉物体内部的小块
        close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel)
        close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, kernel)

        cnts, 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(cnts):
            (x,y,w,h) = cv2.boundingRect(c)

            #对车辆的宽高进行判断
            #以验证是否是有效的车辆
            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 = center(x, y, w, h)
            cars.append(cpoint) 
            cv2.circle(frame, (cpoint), 5, (0,0,255), -1)

            for (x, y) in cars:
                if( (y > line_high - offset) and (y < line_high + offset ) ):
                    carno +=1
                    cars.remove((x , y ))
                    print(carno)
        
        cv2.putText(frame, "Cars Count:" + str(carno), (500, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,0,0), 5)
        cv2.imshow('video', frame)
        #cv2.imshow('erode', close)
    
    key = cv2.waitKey(1)
    if(key == 27):
        break

cap.release()
cv2.destroyAllWindows()

四、实验结果

实验结果如图所示,按Esc键退出。
在这里插入图片描述

五、实验分析

1.本实验很好的结合并运用了之前博客讲述的openCV基础知识。从而实现道路车流量计数,如图像的灰度图,图像的去噪,图像处理kernel的构建,图像腐蚀,图像膨胀,图像闭操作、图像背景消除等。
2.具体实现是根据估计定义汽车选框的大小,先去除视频中的背景去除,然后逐帧读取视频,转化为灰度图,并找出连续几帧中通过检测线的物体,并将其框起来,再通过根据物体的尺寸大小判断是否是汽车,如果是计数加一,否则不加以计数。
3.但根据实际代码跑的情况来看,效果并不是太好,代码还不够完善,算法还有很大优化空间,比如对于摩托车算法有时也会计算出来,多个汽车在一起会导致计数错误。具体改进可以加入深度学习技术加入对汽车形体的识别,以及对汽车阴影的去除,从而提高技术的精确度。后续可能会更新加入深度学习技术的代码,尽情期待。

图像的灰度图在之前博客openCV基础知识(三)具体说明,链接为:https://blog.csdn.net/qq_26274961/article/details/121617487
图像的去噪在之前博客openCV基础知识(五)具体说明,链接为:
https://blog.csdn.net/qq_26274961/article/details/121621414
图像处理kernel的构建,图像腐蚀,图像膨胀,图像闭操作等图像的数学形态学在之前博客openCV基础知识(六)具体说明,链接为:https://blog.csdn.net/qq_26274961/article/details/121641637
图像背景消除在之前博客openCV基础知识(八)具体说明,链接为:https://blog.csdn.net/qq_26274961/article/details/121731186

六、代码文件

小程序员将代码文件和相关素材整理到了百度网盘里,因为文件大小基本不大,大家也不用担心限速问题。后期小程序员有能力的话,将在gitee或者github上上传相关素材。
链接:https://pan.baidu.com/s/1Ce14ZQYEYWJxhpNEP1ERhg?pwd=7mvf
提取码:7mvf

GitHub 加速计划 / opencv31 / opencv
142
15
下载
OpenCV: 开源计算机视觉库
最近提交(Master分支:3 个月前 )
d9a139f9 Animated WebP Support #25608 related issues #24855 #22569 ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [ ] The feature is well documented and sample code can be built with the project CMake 1 天前
09030615 V4l default image size #25500 Added ability to set default image width and height for V4L capture. This is required for cameras that does not support 640x480 resolution because otherwise V4L capture cannot be opened and failed with "Pixel format of incoming image is unsupported by OpenCV" and then with "can't open camera by index" message. Because of the videoio architecture it is not possible to insert actions between CvCaptureCAM_V4L::CvCaptureCAM_V4L and CvCaptureCAM_V4L::open so the only way I found is to use environment variables to preselect the resolution. Related bug report is [#25499](https://github.com/opencv/opencv/issues/25499) Maybe (but not confirmed) this is also related to [#24551](https://github.com/opencv/opencv/issues/24551) This fix was made and verified in my local environment: capture board AVMATRIX VC42, Ubuntu 20, NVidia Jetson Orin. ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [X] I agree to contribute to the project under Apache 2 License. - [X] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [X] The PR is proposed to the proper branch - [X] There is a reference to the original bug report and related work - [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [ ] The feature is well documented and sample code can be built with the project CMake 1 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐