opencv 中 createBackgroundSubtractorMOG2 函数的行为

Behaviour of createBackgroundSubtractorMOG2 function in opencv

我正在尝试通过使用 cv2.createBackgroundSubtractorMOG2() 函数创建运动检测警报来检查移动物体并发出警报。 这是我的代码:

import cv2
import numpy as np
import winsound


kernel=np.ones((5,5),np.uint8)
cap=cv2.VideoCapture(0)
fgbg=cv2.createBackgroundSubtractorMOG2()
while True:
    ret,frame=cap.read()
    fgmask=fgbg.apply(frame)  #creates binary image of moving objects
    fgmask=cv2.erode(fgmask,kernel,iterations=1)  #erosion to remove noise
    counter=np.sum(fgmask==255)  # counts the number of white pixels in the mask
    cv2.imshow('img',fgmask)
    cv2.imshow('frame',frame)
    print(counter)
    if counter>50:  #sounds an alarm if the number of white pixels is greater than a certain limit
        winsound.Beep(1000,2000)
        print("beep")

    if (cv2.waitKey(1) & 0xFF)==ord('q'):
        break
cap.release()

问题是因为调用winsound.Beep函数时程序暂停了2秒,恢复后程序出现故障并反复开始发出哔哔声。

如果我删除 winsound.Beep 函数,程序将按预期运行。 为什么会这样?

您遇到此类问题的原因是 winsound.Beep(1000,2000) 是一个阻塞操作,应该在单独的线程上运行

为了让您完成您想要做的事情,这里是工作代码:

import cv2
import numpy as np
import winsound
import threading 

kernel=np.ones((5,5),np.uint8)
cap=cv2.VideoCapture(0)
fgbg=cv2.createBackgroundSubtractorMOG2()

def playSound():
    winsound.Beep(1000,2000)

while True:

    ret,frame=cap.read()
    fgmask=fgbg.apply(frame)  
    fgmask=cv2.erode(fgmask,kernel,iterations=1)  
    counter=np.sum(fgmask==255)  

    cv2.imshow('img',fgmask)
    cv2.imshow('frame',frame)

    if counter>50:  
        # Run the playSound function on a separate thread 
        t = threading.Thread(target=playSound)
        t.start()            

    if (cv2.waitKey(1) & 0xFF)==ord('q'):
        break

cap.release()

希望对您有所帮助