如何使用OpenCV和Python线程避免音频延迟?

2024-05-20 05:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用OpenCV和Python实现报警系统

我有以下资料:

import cv2
import winsound
import threading

# Tracker and camera configuration
# ...


def beep():
    winsound.Beep(frequency=2500, duration=1000)


try:
    while True:
        # Grab frame from webcam
        # ...

        success, bbox = tracker.update(colorFrame)

        # Draw bounding box
        if success:
            # Tracking success
            (x, y, w, h) = [int(p) for p in bbox]
            cv2.rectangle(colorFrame, (x, y), (x + w, y + h), (0, 255, 0), 2, 1)
         
            if alarm_condition(x, y, w, h):   # if bbox coordinates are touching restricted area
                text = "Alarm"
                threading.Thread(beep())

        # Show images
        cv2.imshow('Color Frame', colorFrame)

        # Record if the user presses a key
        key = cv2.waitKey(1) & 0xFF

        # if the `q` key is pressed, break from the lop
        if key == ord("q"):
            break

finally:

    # cleanup the camera and close any open windows
    vid.release()
    cv2.destroyAllWindows()

警报检测工作正常。但是,除了报警文本之外,我还尝试播放一声蜂鸣报警音。然而,当人接触到受限矩形区域时,音频播放会有很大的延迟,因为如果人一直接触该区域,音频会在每次迭代中播放

我已经读到线程可以帮助,但我无法使它工作


Tags: andthekeyfromimport报警ifbeep
1条回答
网友
1楼 · 发布于 2024-05-20 05:28:28

你的问题是它是连续播放的,这就是它落后的原因。你可以做一件事,你可以使用datetime检查声音是否最近播放,如果在一分钟后播放

范例

import datetime
import threading
import winsound

def beep():
    winsound.Beep(frequency=2500, duration=1000)

recently = []
if(condition):
    c_time = datetime.datetime.now().strftime('%M')
    if not recently:
        recently.append(c_time)
        threading.Thread(beep())
    elif recently[-1] == c_time:
        continue
    else:
        recently.append(c_time)
        threading.Thread(beep())

如果有任何错误,请道歉

相关问题 更多 >