python 背景建模 opencv createBackgroundSubtractorMOG2

主要函数

cv2.createBackgroundSubtractorMOG2(detectShadows=True)# url: https://docs.opencv.org/3.4.2/de/de1/group__video__motion.html#ga2beb2dee7a073809ccec60f145b6b29c
  • c++
createBackgroundSubtractorMOG2()
Ptr<BackgroundSubtractorMOG2> cv::createBackgroundSubtractorMOG2	(	int 	history = 500,
double 	varThreshold = 16,
bool 	detectShadows = true 
)		
  • Python:
retval	=	cv.createBackgroundSubtractorMOG2(	[, history[, varThreshold[, detectShadows]]]	)
  • Parameters
参数解释
historyLength of the history
varThreshold阈值在像素和模型之间的平方 Mahalanobis 距离上,以确定背景模型是否很好地描述了一个像素。此参数不会影响后台更新。
detectShadows如果为 true,该算法将检测阴影并对其进行标记。它会稍微降低速度,因此,如果您不需要此功能,请将参数设置为false。

添加链接描述

代码

import cv2
import numpy as np

# MOG背景分割器
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] # 阈值处理 https://www.cnblogs.com/yinliang-liang/p/9293310.html

    th = cv2.erode(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2) # 图像形态学操作-腐蚀操作 cv2.erode
    dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 3)), iterations=2) # cv2.dilate () 膨胀:将前景物体变大,理解成将图像断开裂缝变小(在图片上画上黑色印记,印记越来越小)

    contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 轮廓检测 https://blog.csdn.net/weixin_44690935/article/details/109008946
    for c in contours:
        if cv2.contourArea(c) > 1000:# 此函数利用格林公式计算轮廓的面积。http://edu.pointborn.com/article/2021/11/19/1706.html
            (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()
  • 背景建模之后得到二值图像,使用3×3大小的腐蚀卷积核迭代腐蚀两次,然后使用8×3大小的膨胀卷积核膨胀迭代两次,对得到的结果进行轮廓检测,对于检测得到的每个轮廓,使用格林函数计算轮廓中的面积,如果轮廓中的面积像素个数多余1000则认为是有车辆通过
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值