首页 > 解决方案 > 背景减法器在 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 的输出:

fgmask

img 的输出与原始帧相同。

这有什么问题,该怎么办?

标签: pythonopencvimage-processing

解决方案


您必须将 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()

推荐阅读