title: Python ASYNC IO Image Processing
body: <p>I'm currently taking images from a webcam that should be processed as soon as they are captured. The code uses the cv2.videocapture() function. </p>
  
  <p>Idea: As soon as an Image is captured I want to use the time the system needs to capture a new image for computation on the previous image. </p>
  
  <p>To achieve this task I use the asyncio library. </p>
  
  <p>First of all I define a producer function that produces n images which should be stored in a queue: </p>
  
  <pre><code>async def produce(queue, n):
      for x in range(n):
          # produce an item
          print('producing {}/{}'.format(x, n))
          # simulate i/o operation using sleep
          await asyncio.sleep(random.random())
          item = obtainImage()
          z.append(x)
          # put the item in the queue
          await queue.put(item)
  </code></pre>
  
  <p>After that I implemented a consumer function which waits for an entry in the queue and computes some image features (here a simple threshold):</p>
  
  <pre><code> async def consume(queue):
          while True:
              # wait for an item from the producer
              # Load the image stored in the queue 
              item = await queue.get()
              # process the item and store value
              ret,thresh1 = cv2.threshold(item,127,255,cv2.THRESH_BINARY)
  
              # simulate i/o operation using sleep
              await asyncio.sleep(random.random())
  
              # Notify the queue that the item has been processed
              queue.task_done() 
  
              #Return the Processesed image
              return thresh1
  </code></pre>
  
  <p>To start the functions I created a run function and added it into an event loop (The run method contains a parameter of how many images i want to process):</p>
  
  <pre><code>async def run(n):
      queue = asyncio.Queue()
      # schedule the consumer
      consumer = asyncio.ensure_future(consume(queue))
      # run the producer and wait for completion
      await produce(queue, n)
      # wait until the consumer has processed all items
      await queue.join()
      # the consumer is still awaiting for an item, cancel it
      consumer.cancel()
  
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(10))
    print(loop)
    loop.close()
  </code></pre>
  
  <p>As long as I use print statements I get an async output like this:</p>
  
  <p>producing 0/10</p>
  
  <p>producing 1/10</p>
  
  <p>consuming 0...</p>
  
  <p>producing 2/10</p>
  
  <p>consuming 1...</p>
  
  <p>producing 3/10</p>
  
  <p>consuming 2...</p>
  
  <p>producing 4/10</p>
  
  <p>consuming 3...</p>
  
  <p>Which is exactly what I desire in terms of order. However, I can`t get back any thresholded image. What am I missing? </p>
  
  <p>Thank you in advance</p>