title: Multi-threaded image processing with openCV in python
body: <p>I am quite new to python and have problems to parallize a part of my algorithm.
  Consider an input image thats need to be threshold in a certain way on pixel level. Since the algorithm only considers a specific area to calculate the threshold values, I'd like to run each chunk of the image in a seperate thread/process. And this is where I am stuck. I could not find a way that these threads work on the same image or how I can merge the results into a new image.
  Since I am usually from the java world I usually fighting the problem that I not want to interfere in other Thread. Therefore I just tried to pass each process the image.</p>
  
  <pre><code>def thresholding(img):
      stepSize = int(img.shape[0] / 10)
      futures = []
      with ProcessPoolExecutor(max_workers=4) as e:
          for y in range(0, img.shape[0], stepSize):
              for x in range(0, img.shape[1], stepSize):
                  futures.append(e.submit(thresholdThread, y, x, img))
      concurrent.futures.wait(futures)
      return img
  
  
  def thresholdThread(y, x, img):
      window_size = int(img.shape[0] / 10)
      window_shape = (window_size, window_size)
      window = img[y:y + window_shape[1], x:x + window_shape[0]]
      upper_bound, lower_bound, avg = getThresholdBounds(window, 0.6)
  
      for y_2 in range(0, window.shape[0]):
          for x_2 in range(0, window.shape[1]):
              tmp = img[y + y_2, x + x_2]
              img[y + y_2, x + x_2] = tmp if (tmp &gt;= upper_bound or tmp &lt;= lower_bound) else avg
      return str(avg)
  </code></pre>
  
  <p>As far as I understand python this does not work, because each process gets its own copy of <code>img</code>. But since img is of type ndarray of floats from numpy I have no idea if and how I could use shared object as descibed <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer">here</a>.</p>
  
  <p>FYI: I am using python 3.6.9. I do know that 3.7 is released, but installing everthing again so I can use spyder and openCV is not so easy.</p>