背景减法——OpenCV
背景减法是一种从图像中消除背景的方法。为了实现这一点,我们从静态背景中提取移动前景。
背景减法在日常生活中有几个用例,它被用于对象分割、安全增强、行人跟踪、计算访客数量、交通车辆数量等。它能够学习和识别前景蒙版。
在 OpenCV 中,我们有 3 种算法来执行此操作 -
BackgroundSubtractorMOG – It is a Gaussian Mixture-based Background/Foreground Segmentation Algorithm.
BackgroundSubtractorMOG2 – It is also a Gaussian Mixture-based Background/Foreground Segmentation Algorithm. It provides better adaptability to varying scenes due illumination changes etc.
BackgroundSubtractorGMG – This algorithm combines statistical background image estimation and per-pixel Bayesian segmentation.
如何应用 OpenCV 内置函数进行背景减法 -
步骤#1 –创建一个对象来表示我们用于背景减法的算法。
步骤 #2 –在图像上应用backgroundsubtractor.apply()
函数。
# importing libraries
import numpy as np
import cv2
# creating object
fgbg1 = cv2.bgsegm.createBackgroundSubtractorMOG();
fgbg2 = cv2.createBackgroundSubtractorMOG2();
fgbg3 = cv2.bgsegm.createBackgroundSubtractorGMG();
# capture frames from a camera
cap = cv2.VideoCapture(0);
while(1):
# read frames
ret, img = cap.read();
# apply mask for background subtraction
fgmask1 = fgbg1.apply(img);
fgmask2 = fgbg2.apply(img);
fgmask3 = fgbg3.apply(img);
cv2.imshow('Original', img);
cv2.imshow('MOG', fgmask1);
cv2.imshow('MOG2', fgmask2);
cv2.imshow('GMG', fgmask3);
k = cv2.waitKey(30) & 0xff;
if k == 27:
break;
cap.release();
cv2.destroyAllWindows();
输出:
我们可以看到BackgroundSubtractorGMG
的结果图像中有很多噪声,因此总是首选对结果使用形态变换来去除噪声。
# importing libraries
import numpy as np
import cv2
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3));
# creating object
fgbg = cv2.bgsegm.createBackgroundSubtractorGMG();
# capture frames from a camera
cap = cv2.VideoCapture(0);
while(1):
# read frames
ret, img = cap.read();
# apply mask for background subtraction
fgmask = fgbg.apply(img);
# with noise frame
cv2.imshow('GMG noise', fgmask);
# apply transformation to remove noise
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel);
# after removing noise
cv2.imshow('GMG', fgmask);
k = cv2.waitKey(30) & 0xff;
if k == 27:
break;
cap.release();
cv2.destroyAllWindows();
输出:
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。