title: Mask Image region for Otsu Threshold with OpenCV
body: <p>I have images were certain regions are set to 255 to not interfere with the region of interest. When doing an Otsu threshold, these regions offset the threshold value. </p>
  
  <p><a href="https://i.stack.imgur.com/JzjM7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JzjM7.jpg" alt="Image with whited-out areas that throw off the Otsu threshold"></a></p>
  
  <p>I found a good <a href="https://stackoverflow.com/questions/12953993/otsu-thresholding-for-depth-image">answer</a> how to do this but my python implementation is slow. Given that I rountinly run my script on 10'000 images, more speed would save me days. </p>
  
  <p>Here an example of what I'm doing</p>
  
  <pre><code>        from __future__ import absolute_import, division, print_function
          #import matplotlib.pyplot as plt
          import numpy as np
          import cv2
  
          #Using the image provided in the question
          img = cv2.imread('imgSubbed-15.jpg', 0)
  
          yImg,xImg = img.shape
          how_many_255 = len(np.where(img==255)[0])
          tempThresImg = np.zeros((1,yImg * xImg - how_many_255), np.uint8)
  
          count=0
          for ii in range(xImg):
              for jj in range(yImg):
                  if img[jj, ii] != 255:
                     tempThresImg[0, count] =  img[jj, ii]
                     count +=1
  
          threshold, temp = cv2.threshold(tempThresImg,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #using otsu threshold
          ret,thresh = cv2.threshold(img,threshold,255,cv2.THRESH_BINARY)
  
          threshold1, thresh1 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #using otsu threshold
  
          cv2.imshow('Standard Way', thresh1)
          cv2.imshow('Removed 255s', thresh)
          print('\n\nThreshold with Removal= %d \t Standard Threshold = %d \n\n' %(threshold, threshold1))
  </code></pre>
  
  <p>The thresholds are 226 versus 250. </p>
  
  <p>Could anyone recommend a way to speed this up?</p>