Mask an image (np.ndarray) section which lies between two curves
<p>Borrowing this example from astropy:</p>

<pre><code>import numpy as np
from matplotlib import pyplot as plt
from astropy.io import fits
from astropy.wcs import WCS
from astropy.utils.data import download_file

fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits'
image_file = download_file(fits_file, cache=True)
hdu = fits.open(image_file)[0]
wcs = WCS(hdu.header)

fig = plt.figure()
ax = fig.add_subplot(111)
plt.imshow(hdu.data, origin='lower', cmap='cubehelix')
plt.xlabel('X')
plt.ylabel('Y')

x_array = np.arange(0, 1000)
line_1 = 1 * x_array + 20 * np.sin(0.05*x_array)
line_2 = x_array - 100 + 20 * np.sin(0.05*x_array)

plt.plot(x_array, line_1, color='red')
plt.plot(x_array, line_2, color='red')

ax.set_xlim(0, hdu.shape[1])
ax.set_ylim(0, hdu.shape[0])

plt.show()
</code></pre>

<p>I would like to calculate the median pixel value (in y direction for example) which lies between the two curves:</p>

<p><a href="http://i.stack.imgur.com/5QvFz.png" rel="nofollow"><img src="http://i.stack.imgur.com/5QvFz.png" alt="enter image description here"></a></p>

<p>I believe the clever thing would be to create a mask for the region of interest.</p>

<p>Is there a way to generate this mask without looping across the image pixels?</p>

<p>Edit 1: Modified question improve understanding</p>

<p>Edit 2: I changed the example to better represent the question title (curves instead of straight lines)</p>

<p>A fairly straight forward way of generating such a mask would be to use the <code>numpy.mgrid</code> thingy that essentially gives you x and y-coordinate arrays (in that 2D case) that can then be used to compute the mask with the equation of the lines . </p>

<p><strong>Edit :</strong> Provided you can express your mask using an equation (like <code>f(x,y)&lt;0</code> where f is any function you want) or a combination of those equations, you can do anything you want. Here is an example with your new mask along with some extra art pieces:  </p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

y,x=np.mgrid[0:1000,0:1000]

#a wiggly ramp
plt.subplot(221)
mask0=(y &lt; x + 20 * np.sin(0.05*x)) &amp; (y &gt; x - 100 + 20 * np.sin(0.05*x))
plt.imshow(mask0,origin='lower',cmap='gray')

#a ramp
plt.subplot(222)
mask1=(y &lt; x) &amp; (x &lt; y+100)
plt.imshow(mask1,origin='lower',cmap='gray')

#a disk
plt.subplot(223)
mask2=(200**2&gt;(x-500)**2+(y-500)**2)
plt.imshow(mask2,origin='lower',cmap='gray')

#a ying-yang attempt
plt.subplot(224)
mask3= (mask2 &amp; (0 &lt; np.sin(3.14*x/250)*100 + 500 - y) &amp; (30**2 &lt; (x-620)**2+(y-500)**2) )| (30**2 &gt; (x-380)**2+(y-500)**2)
plt.imshow(mask3,origin='lower',cmap='gray')

plt.show()
</code></pre>

<p>Output :</p>

<p><a href="http://i.stack.imgur.com/VPK6w.png" rel="nofollow"><img src="http://i.stack.imgur.com/VPK6w.png" alt="Output"></a></p>

python numpy indexing mask scikit-image