opencv python 背景减法

Background Subtraction

BackgroundSubtractorMOG

MOG算法,即高斯混合模型分离算法,它使用一种通过K高斯分布的混合来对每个背景像素进行建模的方法(K = 3-5)

import numpy as np
import cv2
import matplotlib.pyplot as plt

cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()

while(1):
    ret, frame = cap.read()

    fgmask = fgbg.apply(frame)

    cv2.imshow('frame',fgmask)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

opencv python 背景减法

BackgroundSubtractorMOG2

MOG2算法,也是高斯混合模型分离算法,是MOG的改进算法,该算法的一个重要特征是 它为每个像素选择适当数量的高斯分布,它可以更好地适应不同场景的照明变化等.

import numpy as np
import cv2
import matplotlib.pyplot as plt

cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()

while(1):
    ret, frame = cap.read()

    fgmask = fgbg.apply(frame)

    cv2.imshow('frame',fgmask)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

opencv python 背景减法

BackgroundSubtractorGMG

该算法结合统计背景图像估计和每像素贝叶斯分割,该算法使用前几个(默认为120)帧进行后台建模。它采用概率前景分割算法,使用贝叶斯推理识别可能的前景对象.在前几帧图像中会得到一个黑色窗口.

import numpy as np
import cv2
import matplotlib.pyplot as plt

cap = cv2.VideoCapture('test.mp4')
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()

while(1):
    ret, frame = cap.read()

    fgmask = fgbg.apply(frame)
    fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)

    cv2.imshow('frame',fgmask)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

opencv python 背景减法

相关推荐