python - 背景减法器在 OpenCV Python 中不起作用,该怎么办?
问题描述
我正在参考这篇文章使用 python 学习 openCV,我尝试了与他们给出的相同的代码,但即使是背景删除的第一阶段也不起作用。
cap = cv2.VideoCapture(1)
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1) # Horizontal Flip
cv2.imshow('original', frame)
# Background Removal
bgSubtractor = cv2.createBackgroundSubtractorMOG2(
history=10, varThreshold=30, detectShadows=False)
fgmask = bgSubtractor.apply(frame)
kernel = np.ones((5, 5), np.uint8)
# The effect is to remove the noise in the background
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel, iterations=2)
# To close the holes in the objects
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel, iterations=2)
img = cv2.bitwise_and(frame, frame, mask=fgmask)
cv2.imshow('image after bitwise_fgmask', img)
cv2.imshow('fgmask', fgmask)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
fgmask 的输出:
img 的输出与原始帧相同。
这有什么问题,该怎么办?
解决方案
您必须将 bgSubtractor 移出 while 循环。否则,您将在每一帧都重新创建它:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# Background Removal
bgSubtractor = cv2.createBackgroundSubtractorMOG2(
history=10, varThreshold=30, detectShadows=False)
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1) # Horizontal Flip
cv2.imshow('original', frame)
fgmask = bgSubtractor.apply(frame)
kernel = np.ones((5, 5), np.uint8)
# The effect is to remove the noise in the background
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel, iterations=2)
# To close the holes in the objects
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel, iterations=2)
img = cv2.bitwise_and(frame, frame, mask=fgmask)
cv2.imshow('image after bitwise_fgmask', img)
cv2.imshow('fgmask', fgmask)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
推荐阅读
- flutter - #Mark:相当于飞镖/颤振?
- reactjs - useEffect 无限调用函数
- r - 使用 rnaturalearth 将河流添加到地图中
- android - 关闭应用程序时如何保持计时器运行?(科特林)
- google-cloud-platform - 尝试获取 c2-standard-60 时收到超出报价的消息
- docker - Docker 容器上的 Gitlab API 不工作 - curl: (28) 无法连接
- python - 使用 pycountry 从名称中获取国家/地区 ID
- typescript - RxJS 比赛在没有完成任一流的情况下停止
- c# - 在 Word 中替换选定文本时如何保留文本格式?
- flutter - 如何更改 Flutter intl 中的主要本地化文件