主要函数
cv2.createBackgroundSubtractorMOG2(detectShadows=True)
createBackgroundSubtractorMOG2()
Ptr<BackgroundSubtractorMOG2> cv::createBackgroundSubtractorMOG2 ( int history = 500,
double varThreshold = 16,
bool detectShadows = true
)
retval = cv.createBackgroundSubtractorMOG2( [, history[, varThreshold[, detectShadows]]] )
参数 | 解释 |
---|
history | Length of the history |
varThreshold | 阈值在像素和模型之间的平方 Mahalanobis 距离上,以确定背景模型是否很好地描述了一个像素。此参数不会影响后台更新。 |
detectShadows | 如果为 true,该算法将检测阴影并对其进行标记。它会稍微降低速度,因此,如果您不需要此功能,请将参数设置为false。 |
添加链接描述
代码
import cv2
import numpy as np
mog = cv2.createBackgroundSubtractorMOG2(detectShadows=True)
camera = cv2.VideoCapture(r'C:\Users\~\Desktop\background_subtraction\05.mp4')
cv2.namedWindow('detection', 0)
cv2.resizeWindow('detection', 600, 500)
ret, frame = camera.read()
while ret:
for i in range(20):
ret, frame = camera.read()
fgmask = mog.apply(frame)
th = cv2.threshold(np.copy(fgmask), 244, 255, cv2.THRESH_BINARY)[1]
th = cv2.erode(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2)
dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 3)), iterations=2)
contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) > 1000:
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 0), 2)
cv2.imshow("mog", fgmask)
cv2.imshow("thresh", th)
cv2.imshow("diff", frame & cv2.cvtColor(fgmask, cv2.COLOR_GRAY2BGR))
cv2.imshow("detection", frame)
ret, frame = camera.read()
if cv2.waitKey(100) & 0xff == ord("q"):
break
camera.release()
cv2.destroyAllWindows()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 背景建模之后得到二值图像,使用3×3大小的腐蚀卷积核迭代腐蚀两次,然后使用8×3大小的膨胀卷积核膨胀迭代两次,对得到的结果进行轮廓检测,对于检测得到的每个轮廓,使用格林函数计算轮廓中的面积,如果轮廓中的面积像素个数多余1000则认为是有车辆通过