You have to move bgSubtractor out of the while loop. Otherwise you will be recreating it every frame:
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…