@@ -273,3 +273,54 @@ statistics::
273273 >>> import numpy as np
274274 >>> np.average(data, weights=mask) # doctest: +FLOAT_CMP
275275 9364.012674888021
276+
277+
278+ .. _interactive-masks :
279+
280+ Interactive Mask Control
281+ ------------------------
282+
283+ In the last example we will show how to use a
284+ :ref: `Matplotlib selector<regions-as_mpl_selector> ` widget with a custom
285+ ``callback `` function for creating a mask and updating it interactively through
286+ the selector.
287+ We first create an :class: `~regions.EllipsePixelRegion ` and add an ``as_mpl_selector ``
288+ property linked to the Matplotlib axes. This can be moved around to
289+ position it on different sources, and resized just like its Rectangle
290+ counterpart, using the handles of the bounding box.
291+
292+ The user-defined callback function here generates a mask from this region and overlays
293+ it on the image as an alpha filter (keeping the areas outside shaded).
294+ We will use this mask as an aperture as well to calculate integrated
295+ and averaged flux, which is updated live in the text field of the plot as well.
296+
297+ .. plot ::
298+ :context:
299+ :include-source:
300+ :align: center
301+
302+ from astropy import units as u
303+ from regions import PixCoord, EllipsePixelRegion
304+
305+ hdulist = fits.open(filename)
306+ hdu = hdulist[0]
307+
308+ plt.clf()
309+ ax = plt.subplot(1, 1, 1)
310+ im = ax.imshow(hdu.data, cmap=plt.cm.viridis, interpolation='nearest', origin='lower')
311+ text = ax.text(122, 1002, '', size='small', color='yellow')
312+ ax.set_xlim(120, 180)
313+ ax.set_ylim(1000, 1059)
314+
315+ def update_sel(region):
316+ mask = region.to_mask(mode='subpixels', subpixels=10)
317+ im.set_alpha((mask.to_image(hdu.data.shape) + 1) / 2)
318+ total = mask.multiply(hdu.data).sum()
319+ mean = np.average(hdu.data, weights=mask.to_image(hdu.data.shape))
320+ text.set_text(f'Total: {total:g}\n Mean: {mean:g}')
321+
322+ ellipse = EllipsePixelRegion(center=PixCoord(x=126, y=1031), width=8, height=4,
323+ angle=-0*u.deg, visual={'color': 'yellow'})
324+ selector = ellipse.as_mpl_selector(ax, callback=update_sel, use_data_coordinates=True)
325+
326+ hdulist.close()
0 commit comments