针对我所使用的视频,对上一节的代码进行了修改,增加了更多参数。
Python Opencv实践 - 车辆统计(1)读取视频,移除背景,做预处理_亦枫Leonlew的博客-CSDN博客示例中的图像的腐蚀、膨胀和闭运算等需要根据具体视频进行实验得到最佳效果。https://blog.csdn.net/vivo01/article/details/133756184?spm=1001.2014.3001.5502 主要参数有,检测窗口过滤大小的变量min/max_w/h,检测线的位置和长度(detection_line_x/y/length),检测线上下偏移量阈值(detection_line_offset)。
由于没有使用深度学习来识别车辆,只是通过传统的计算机视觉方法处理图像后,通过搜索轮廓来实现车辆检测。因此所有参数都是针对我所使用的视频进行了优化,实际运行中,还是会存在无法检测出部分车辆的问题。所有对图像的处理方法和相关参数,需要大家根据自己的视频来进行优化。对于我所使用的视频,我没有直接用MOG2来做背景移除,而是先通过Canny提取边缘后再进行背景移除处理,这一点只是实验出来对我所使用的视频来说效果最好,并非网上所看教程的做法。
- import cv2 as cv
- import numpy as np
-
- #读取视频文件
- videoFile = "../../SampleVideos/TrafficHEB.mp4"
- video = cv.VideoCapture(videoFile)
- FPS = 15
- DELAY = int(1000 / FPS)
- kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3,3))
- min_w = 82
- min_h = 82
- max_w = 160
- max_h = 160
- detection_line_length = 1500
- detection_line_x = (1920 - detection_line_length) / 2
- detection_line_y = 900
- detection_line_offset = 1
- cars_detected = 0
-
- #训练MOG2背景移除对象
- def trainBgSubtractor(train_video, mog, frameNum):
- #train_video = cv.VideoCapture(videoFile)
- while True:
- ret, frame = train_video.read()
- if ret == False:
- break
- mog.apply(frame, None, 0.01)
- frameNum = frameNum - 1
- if 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_img
-
-
- def filterMask(img, a=None):
- kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))
-
- # Fill any small holes
- img = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
- #img = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
-
- # Remove noise
- img = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
-
- # Dilate to merge adjacent blobs
- img = cv.dilate(img, kernel, iterations=6)
- return img
-
- def 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) and
- x > (detection_line_x) and x < (detection_line_x + detection_line_length)):
- cars_detected = cars_detected + 1
- print(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();
