I have the following steps I need to follow:
1 - I need to start a camera instance on OpenCV
2 - I need to send the camera's data to some outside source every 2 seconds, but the video feed obviously cannot stop in the meantime
So I made two main async functions: "flip_trigger", which switches a boolean variable every 2 seconds, and "camera_feed", which also consumes the same "send_image" trigger that s switched by "flip_trigger". The two must run at the same time.
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())
The problem is: while debugging the code on VSCode, it seemingly never gets past the "await asyncio.sleep(2)" line, and if I remove the "await" parameter, the code seems to get stuck inside the "flip_trigger" function.
How do I make these functions work at the same time, and make "camera_feed" capture the "send_image" boolean switches in real time?
CodePudding user response:
When you call await
asyncio tries to continue other tasks in the loop.
Imagine when await
especially in combination with asyncio.sleep
is called it pauses the execution and it hops to another await
section region where it can continue.
There normal python code is executed sequentially until the next await is reached.
Your camera_feed
has no await
, that means it will continuously loop forever/until the break.
It won't go back to flip_trigger
.
You can use asyncio.sleep(0)
to enable a ping pong between both functions.