Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

Background Subtractor not working in OpenCV Python , what to do?

I was just learning openCV with python with reference to here and i tried the same code as they have given but even the first phase of bg removal is not working

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()

output for fgmask :

fgmask

output for img is same as the original frame

what's wrong in this and what to do ?

question from:https://stackoverflow.com/questions/65923575/background-subtractor-not-working-in-opencv-python-what-to-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...