opencv 异步进程未切换布尔触发器

blpfk2vs  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(123)

我需要遵循以下步骤:
1 -我需要在OpenCV上启动摄像头示例
2 -我需要每隔2秒将摄像头的数据发送到一些外部源,但视频馈送显然不能在此期间停止
所以我创建了两个主要的异步函数:“flip_trigger”每2秒切换一个布尔变量,“camera_feed”也使用由“flip_trigger”切换的相同的“send_image”触发器。这两个必须同时运行。

send_image = False


async def flip_trigger():
    global send_image
    while True:
        await asyncio.sleep(2)
        send_image = not send_image
        print("Awaiting image")

async def camera_feed():
    global send_image
    face_names = []
    face_usernames = []
    video_capture = cv2.VideoCapture(0)
    while True:
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if(send_image):
            ret, frame = video_capture.read()
            #(...) some other code
        else:
            ret, frame = video_capture.read()
            cv2.imshow('Video', frame)
            continue
        #(...) some other code
        ret, frame = video_capture.read()
        cv2.imshow('Video', frame)
        video_capture.release()
        cv2.destroyAllWindows()
        break

async def start_camera():
    task1 = asyncio.create_task(flip_trigger())
    task2 = asyncio.create_task(camera_feed())
    await asyncio.wait({task1, task2}, return_when=asyncio.FIRST_COMPLETED) 

asyncio.run(start_camera())

问题是:当在VSCode上调试代码时,它似乎永远不会越过“await asyncio.sleep(2)”行,如果我删除“await”参数,代码似乎会卡在“flip_trigger”函数中。
如何让这些函数同时工作,并让“camera_feed”真实的捕获“send_image”布尔开关?

nzk0hqpo

nzk0hqpo1#

当你调用await时,asyncio试图继续循环中的其他任务。
想象一下,当调用await(尤其是与asyncio.sleep结合使用时)时,它会暂停执行,并跳转到另一个可以继续执行的await段区域。
这里,正常的python代码将按顺序执行,直到到达下一个await
你的camera_feed没有await,这意味着它将永远循环/直到休息。它不会回到flip_trigger
您可以使用asyncio.sleep(0)来启用两个函数之间的ping pong。

相关问题