1

我正在尝试通过使用 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 函数,程序将按预期工作。为什么会这样?

4

1 回答 1

2

您遇到此类问题的原因是因为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()

希望这可以帮助

于 2018-12-03T12:31:51.147 回答