title: How can I select the pixels that fall within a contour in an image represented by a numpy array?
body: <p>VI have a set of contour points drawn on an image which is stored as a 2D numpy array. The contours are represented by 2 numpy arrays of float values for x and y coordinates each. <a href="https://gist.github.com/sdoken/173fae1f9d8673ffff5b481b3872a69d" rel="nofollow noreferrer">These coordinates</a> are not integers and do not align perfectly with pixels but they do tell you the location of the contour points with respect to pixels.</p>
  <p>I would like to be able to select the pixels that fall within the contours. I wrote some code that is pretty much the same as answer given here: <a href="https://stackoverflow.com/questions/33234363/access-pixel-values-within-a-contour-boundary-using-opencv-in-python/33251950?noredirect=1#comment88697613_33251950">Access pixel values within a contour boundary using OpenCV in Python</a></p>
  <pre><code>temp_list = []
  for a, b in zip(x_pixel_nos, y_pixel_nos):
      temp_list.append([[a, b]]) # 2D array of shape 1x2
  temp_array = np.array(temp_list)
  contour_array_list = []
  contour_array_list.append(temp_array)
  
  
  
  lst_intensities = []
  
  # For each list of contour points...
  for i in range(len(contour_array_list)):
      # Create a mask image that contains the contour filled in
      cimg = np.zeros_like(pixel_array)
      cv2.drawContours(cimg, contour_array_list, i, color=255, thickness=-1)
  
  # Access the image pixels and create a 1D numpy array then add to list
  pts = np.where(cimg == 255)
  lst_intensities.append(pixel_array[pts[0], pts[1]])
  </code></pre>
  <p>When I run this, I get an error <code>error: OpenCV(3.4.1) /opt/conda/conda-bld/opencv-suite_1527005509093/work/modules/imgproc/src/drawing.cpp:2515: error: (-215) npoints &gt; 0 in function drawContours</code></p>
  <p>I am guessing that at this point openCV will not work for me because my contours are floats, not integers, which openCV does not handle with <code>drawContours</code>. If I convert the coordinates of the contours to integers, I lose a lot of precision.</p>
  <p>So how can I get at the pixels that fall within the contours?</p>
  <p><a href="https://i.stack.imgur.com/mxgwI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxgwI.png" alt="enter image description here" /></a></p>
  <p>This should be a trivial task but so far I was not able to find an easy way to do it.</p>