2 Python Opencv实践 - 车辆统计检测线绘制,车辆数量计数和显示

针对我所使用的视频,对上一节的代码进行了修改,增加了更多参数 。
实践 - 车辆统计(1)读取视频,移除背景,做预处理_亦枫的博客-CSDN博客示例中的图像的腐蚀、膨胀和闭运算等需要根据具体视频进行实验得到最佳效果 。
主要参数有,检测窗口过滤大小的变量min/max_w/h,检测线的位置和长度(/y/),检测线上下偏移量阈值(t) 。

2  Python Opencv实践 - 车辆统计检测线绘制,车辆数量计数和显示

文章插图
由于没有使用深度学习来识别车辆,只是通过传统的计算机视觉方法处理图像后,通过搜索轮廓来实现车辆检测 。因此所有参数都是针对我所使用的视频进行了优化,实际运行中,还是会存在无法检测出部分车辆的问题 。所有对图像的处理方法和相关参数,需要大家根据自己的视频来进行优化 。对于我所使用的视频,我没有直接用MOG2来做背景移除,而是先通过Canny提取边缘后再进行背景移除处理,这一点只是实验出来对我所使用的视频来说效果最好,并非网上所看教程的做法 。
【2Python Opencv实践 - 车辆统计检测线绘制,车辆数量计数和显示】import cv2 as cvimport numpy as np#读取视频文件videoFile = "../../SampleVideos/TrafficHEB.mp4"video = cv.VideoCapture(videoFile)FPS = 15DELAY = int(1000 / FPS)kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3,3))min_w = 82min_h = 82max_w = 160max_h = 160detection_line_length = 1500detection_line_x = (1920 - detection_line_length) / 2detection_line_y = 900detection_line_offset = 1cars_detected = 0#训练MOG2背景移除对象def trainBgSubtractor(train_video, mog, frameNum):#train_video = cv.VideoCapture(videoFile)while True:ret, frame = train_video.read()if ret == False:breakmog.apply(frame, None, 0.01)frameNum = frameNum - 1if frameNum <= 0:break#train_video.release()#增加对比度def imageAdjust(img, clipLimit = 1.5, gridSize = (3,3)):clahe = cv.createCLAHE(clipLimit, gridSize)adjusted_img = clahe.apply(img)return adjusted_imgdef filterMask(img, a=None):kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))# Fill any small holesimg = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)#img = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)# Remove noiseimg = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)# Dilate to merge adjacent blobsimg = cv.dilate(img, kernel, iterations=6)return imgdef rectCenter(x, y, w, h):return x + w / 2, y + h / 2#移除背景#参考资料:https://blog.csdn.net/u014737138/article/details/80389977#mog = cv.bgsegm.createBackgroundSubtractorMOG()mog = cv.createBackgroundSubtractorMOG2(history=100, detectShadows=True)#trainBgSubtractor(video, mog, 100)while True:cars_positions = []ret,frame = video.read()if ret == False:break;#变为灰度图做高斯滤波frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)frame_gray = cv.Canny(frame_gray, 65, 160)frame_gray = cv.GaussianBlur(frame_gray, (3,3), 3)#frame_gray = cv.medianBlur(frame_gray, 3)frame_gray = imageAdjust(frame_gray, 15, (3,3))foreground_mask = mog.apply(frame_gray, None, -1)foreground_mask[foreground_mask < 240] = 0#foreground_mask = cv.dilate(foreground_mask, kernel, iterations=2)forground_mask = cv.GaussianBlur(foreground_mask, (3,3), 3)foreground_mask = filterMask(foreground_mask)#画出检测线cv.line(frame,(int(detection_line_x), int(detection_line_y)),(int(detection_line_x + detection_line_length),int(detection_line_y)),(0,50,200))#查找轮廓contours,hierarchy = cv.findContours(foreground_mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_TC89_L1)#contours,hierarchy = cv.findContours(foreground_mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)#绘制轮廓for contour in contours:(x,y,w,h) = cv.boundingRect(contour)#过滤掉小的轮廓框if w >= min_w and h >= min_h and w <= max_w and h <= max_h:cv.rectangle(frame, (int(x),int(y)), (int(x + w), int(y + h)), (0,255,0), 2)#画出车辆中心点centerX,centerY = rectCenter(x, y, w , h)cv.circle(frame, (int(centerX), int(centerY)), 4, (0,0,255), -1)#将车辆加入检测到的车辆列表中cars_positions.append((centerX, centerY))#检测车辆中心点是否通过检测线for (x,y) in cars_positions:if (y > (detection_line_y - detection_line_offset) and y < (detection_line_y + detection_line_offset) andx > (detection_line_x) and x < (detection_line_x + detection_line_length)):cars_detected = cars_detected + 1print(cars_detected)#输出文字cv.putText(frame, 'Vehicle Detected:' + str(cars_detected), (900, 50), cv.FONT_HERSHEY_SIMPLEX, 2, (0,255,0), 5)cv.imshow("Traffic Original", frame)cv.imshow("Traffic Processing", foreground_mask)if cv.waitKey(DELAY) == 27:break;video.release()cv.destroyAllWindows();