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