import matplotlib.pyplot as plt
import numpy as np
from astropy import units as u
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
from regions import EllipsePixelRegion, PixCoord

filename = get_pkg_data_filename('photometry/M6707HH.fits')
hdulist = fits.open(filename)
hdu = hdulist[0]

fig, ax = plt.subplots()
im = ax.imshow(hdu.data, origin='lower')
text = ax.text(122, 1002, '', size='small', color='yellow')
ax.set_xlim(120, 180)
ax.set_ylim(1000, 1059)

def update_sel(region):
    mask = region.to_mask(mode='subpixels', subpixels=10)
    im.set_alpha((mask.to_image(hdu.data.shape) + 1) / 2)
    total = mask.multiply(hdu.data).sum()
    mean = np.average(hdu.data, weights=mask.to_image(hdu.data.shape))
    text.set_text(f'Total: {total:g}\nMean: {mean:g}')

ellipse = EllipsePixelRegion(center=PixCoord(x=126, y=1031),
                             width=8, height=4,
                             angle=-0 * u.deg,
                             visual={'color': 'yellow'})
selector = ellipse.as_mpl_selector(ax, callback=update_sel)

hdulist.close()