0

The scenario is the following. I'm capturing frames from a local webcam using OpenCV. I would like to POST every single frame in a while loop with the following logic:

url = "http://www.to.service"
while True:
    cap = cv2.VideoCapture(0)
    try:
      _, frame = cap.read()
      frame_data = do_something(frame)
      async_post(url, frame_data)
    except KeyboardInterrupt:
      break

I tried with asyncio and aiohttp with the following, but without success

async def post_data(session, url, data):
    async with session.post(url) as response:
        return await response.text()


async def main():
    async with aiohttp.ClientSession() as session:
        cap = cv2.VideoCapture(0)
        while True:
            try:
                _, frame = cap.read()
                frame_data = do_something(frame)  # get a dict
                await post_data(session, url, frame_data)  # post the dict
            except KeyboardInterrupt:
                break
        cap.release()
        cv2.destroyAllWindows()


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

As far as I understood the logic hereby presented might not be adequate for the asynchronous requests, as I cannot, in principle, fill a list of tasks to be gathered. I hope this is clear enough. Sorry in advance if it's not. Any help is much appreciated. Cheers

Fabrizio Miano
  • 493
  • 3
  • 11
  • Can you elaborate what _without success_ means? Did you get an exception? If so, please post the traceback. Otherwise, let us know how the program failed. – user4815162342 Sep 05 '19 at 17:04
  • No error produced. The post is simply performed synchronously – Fabrizio Miano Sep 05 '19 at 19:44
  • Note that you have an `await`, which tells asyncio to, well, wait for it to complete. If you want POST-ing to proceed in the background, you should use `asyncio.create_task(post_data(...))` instead. – user4815162342 Sep 05 '19 at 22:00
  • You'll probably also need to change `_, frame = cap.read()` to `_, frame = await loop.run_in_executor(None, cap.read)` to allow the event loop to run while waiting for the next image. – user4815162342 Sep 05 '19 at 22:01

0 Answers0