我需要遵循以下步驟:
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”布爾開關?
uj5u.com熱心網友回復:
當您呼叫awaitasyncio 時,會嘗試繼續回圈中的其他任務。
想象一下,當await特別是與asyncio.sleep被呼叫時,它會暫停執行并跳到另一個await可以繼續的部磁區域。
正常的 python 代碼按順序執行,直到到達下一個 await。
你camera_feed沒有await,這意味著它將永遠回圈/直到中斷。它不會回到flip_trigger.
您可以使用asyncio.sleep(0)來啟用兩個功能之間的乒乓。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/517752.html
