def test_noclip(self): norm = ImageNormalize(vmin=2., vmax=10., stretch=SqrtStretch(), clip=False) norm2 = ImageNormalize(DATA, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=False) output = norm(DATA) expected = [np.nan, 0.35355339, 0.70710678, 0.93541435, 1.11803399, 1.27475488] assert_allclose(output, expected) assert_allclose(output.mask, [0, 0, 0, 0, 0, 0]) assert_allclose(norm.inverse(norm(DATA))[1:], DATA[1:]) assert_allclose(output, norm2(DATA))
def test_masked_noclip(self): mdata = ma.array(DATA, mask=[0, 0, 1, 0, 0, 0]) norm = ImageNormalize(vmin=2., vmax=10., stretch=SqrtStretch(), clip=False) norm2 = ImageNormalize(mdata, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=False) output = norm(mdata) expected = [np.nan, 0.35355339, -10, 0.93541435, 1.11803399, 1.27475488] assert_allclose(output.filled(-10), expected) assert_allclose(output.mask, [0, 0, 1, 0, 0, 0]) assert_allclose(norm.inverse(norm(DATA))[1:], DATA[1:]) assert_allclose(output, norm2(mdata))
def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) # Fill in some missing info self.meta['detector'] = "EIT" self.meta['waveunit'] = "Angstrom" self._fix_dsun() self._nickname = self.detector self.plot_settings['cmap'] = plt.get_cmap(self._get_cmap_name()) self.plot_settings['norm'] = ImageNormalize(stretch=source_stretch(self.meta, PowerStretch(0.5)))
def test_noclip(self): norm = ImageNormalize(vmin=2., vmax=10., stretch=SqrtStretch(), clip=False, invalid=None) norm2 = ImageNormalize(DATA, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=False, invalid=None) output = norm(DATA) expected = [ np.nan, 0.35355339, 0.70710678, 0.93541435, 1.11803399, 1.27475488 ] assert_allclose(output, expected) assert_allclose(output.mask, [0, 0, 0, 0, 0, 0]) assert_allclose(norm.inverse(norm(DATA))[1:], DATA[1:]) assert_allclose(output, norm2(DATA))
def test_masked_noclip(self): mdata = ma.array(DATA, mask=[0, 0, 1, 0, 0, 0]) norm = ImageNormalize(vmin=2., vmax=10., stretch=SqrtStretch(), clip=False) norm2 = ImageNormalize(mdata, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=False) output = norm(mdata) expected = [ np.nan, 0.35355339, -10, 0.93541435, 1.11803399, 1.27475488 ] assert_allclose(output.filled(-10), expected) assert_allclose(output.mask, [0, 0, 1, 0, 0, 0]) assert_allclose(norm.inverse(norm(DATA))[1:], DATA[1:]) assert_allclose(output, norm2(mdata))
def stretch_data(data, method="HistEqStretch"): """ methods = LogStretch, SqrtStretch, AsinhStretch, HistEqStretch """ if method == "LogStretch": norm = ImageNormalize(stretch=LogStretch(data)) elif method == "SqrtStretch": norm = ImageNormalize(stretch=SqrtStretch(data)) elif method == "AsinhStretch": norm = ImageNormalize(stretch=AsinhStretch(data)) elif method == "HistEqStretch": norm = ImageNormalize(stretch=HistEqStretch(data)) else: norm = data return norm
def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) # Fill in some missing info self.meta['detector'] = "AIA" self._nickname = self.detector self.plot_settings['cmap'] = cm.get_cmap(self._get_cmap_name()) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, AsinhStretch(0.01)))
def make_jpg(self): ''' Converts HIRES FITS file to JPG image Output filename = KOAID_CCD#_HDU##.jpg # = 1, 2, 3... ## = 01, 02, 03... ''' # TODO: Can we merge this with instrument.make_jpg()? # file to convert is lev0Dir/KOAID koaid = self.get_keyword('KOAID') filePath = '' for root, dirs, files in os.walk(self.dirs['lev0']): if koaid in files: filePath = ''.join((root, '/', koaid)) if not filePath: self.log.error('make_jpg: Could not find KOAID: ' + koaid) return False self.log.info( 'make_jpg: converting {} to jpeg format'.format(filePath)) koaid = filePath.replace('.fits', '') if os.path.isfile(filePath): for ext in range(1, len(self.fitsHdu)): try: ext2 = str(ext) pngFile = koaid + '_CCD' + ext2 + '_HDU' + ext2.zfill( 2) + '.png' jpgFile = pngFile.replace('.png', '.jpg') # image data to convert image = self.fitsHdu[ext].data interval = ZScaleInterval() vmin, vmax = interval.get_limits(image) norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=AsinhStretch()) plt.imshow(image, cmap='gray', origin='lower', norm=norm) plt.axis('off') # save as png, then convert to jpg plt.savefig(pngFile) Image.open(pngFile).convert('RGB').rotate(-90).save( jpgFile) os.remove(pngFile) plt.close() except: self.log.error('make_jpg: Could not create JPG: ' + jpgFile) else: self.log.error('make_jpg: file does not exist {}'.format(filePath)) return False return True
def background_reduction(List): Raw_Image_Data = [] Reduced_Image_Data = [] Bkg = [] Bkg_Sigma = [] Median = [] Std = [] Norm = ImageNormalize(stretch=SqrtStretch()) for i in range(len(List)): Image_File = get_pkg_data_filename(f'RAW_DATA/{List[i]}') crmask, Raw_Image_Data_1 = astroscrappy.detect_cosmics( fits.getdata(Image_File, ext=0)) Raw_Image_Data.append(Raw_Image_Data_1) Mask = (Raw_Image_Data_1 == 0) Sigma_Clip = SigmaClip(sigma=3.0) Bkg_Estimator = MedianBackground() Bkg_ta = Background2D(Raw_Image_Data_1, (25, 25), filter_size=(3, 3), sigma_clip=Sigma_Clip, bkg_estimator=Bkg_Estimator, mask=Mask) Bkg.append(Bkg_ta) Bkg_Sigma_ta = mad_std(Raw_Image_Data_1) Bkg_Sigma.append(Bkg_Sigma_ta) Mean, Median_ta, Std_ta = sigma_clipped_stats(Raw_Image_Data_1, sigma=3.0) Median.append(Median_ta) Std.append(Std_ta) Reduced_Image_Data_to_append = Raw_Image_Data_1 - Bkg_ta.background Reduced_Image_Data.append(Reduced_Image_Data_to_append) #plt.figure() #plt.imshow(Raw_Image_Data_1, cmap = 'gray', origin = 'lower', interpolation = 'bicubic', norm = Norm, vmin = 100, vmax = 1000) #plt.colorbar() #plt.figure() #plt.imshow(Bkg_ta.background, origin='lower', cmap='gray', interpolation = 'bicubic') #plt.colorbar() #plt.figure() #plt.imshow(Reduced_Image_Data_to_append, norm = Norm, origin = 'lower', cmap = 'gray', interpolation = 'bicubic', vmin = 1, vmax = 1000) #plt.colorbar() #plt.show() return Raw_Image_Data, Reduced_Image_Data, Bkg, Bkg_Sigma, Median, Std
def test_invalid_keyword(self, stretch): norm1 = ImageNormalize(stretch=stretch, vmin=-1, vmax=1, clip=False, invalid=None) norm2 = ImageNormalize(stretch=stretch, vmin=-1, vmax=1, clip=False) norm3 = ImageNormalize(DATA3, stretch=stretch, vmin=-1, vmax=1, clip=False, invalid=-1.) result1 = norm1(DATA3) result2 = norm2(DATA3) result3 = norm3(DATA3) assert_equal(result1[0:2], (np.nan, np.nan)) assert_equal(result2[0:2], (-1., -1.)) assert_equal(result1[2:], result2[2:]) assert_equal(result2, result3)
def find_sources(file_, fwhm): """ Uses DAOStarFinder to extract source positions from fits file :param file_ (str): name of target .fits file :param fwhm (float): The full width half maximum of the gaussian kernel in pixels For more config see https://photutils.readthedocs.io/en/stable/api/photutils.detection.DAOStarFinder.html """ # Read in fits file as numpy array data = read_fits(file_, return_array=True) # Calculate background level mean, median, std = stats.sigma_clipped_stats(data) print(('mean', 'median', 'std')) print((mean, median, std)) # Set up DAO Finder and run on bg subtracted image, printing results # sharplo=.2, sharphi=1., roundlo=-.3, roundhi=.3, daofind = DAOStarFinder(exclude_border=True, fwhm=fwhm, threshold=std) sources = daofind.find_stars(data - median) # daofind(data-median) # print('Sources:') print(sources) # Save positions of detected sources to csv file positions = (sources['xcentroid'], sources['ycentroid']) print_positions = zip(*[ sources[x] for x in [ 'id', 'xcentroid', 'ycentroid', 'sharpness', 'roundness1', 'roundness2', 'npix', 'sky', 'peak', 'flux', 'mag' ] ]) header = 'id,xcentroid,ycentroid,sharpness,roundness1,roundness2,npix,sky,peak,flux,mag' np.savetxt(file_[:-5] + '_positions.csv', print_positions, fmt='%.5e', header=header) # Show image with detected sources circled in blue apertures = CircularAperture(positions, r=4.) norm = ImageNormalize(stretch=SqrtStretch()) plt.imshow(data, cmap='Greys', origin='lower', norm=norm) apertures.plot(color='blue', lw=1.5, alpha=0.5) plt.draw() # Scatter plot sharpness vs magnitude plt.figure(2) sharp, round_, mags = (sources['sharpness'], sources['roundness1'], sources['mag']) plt.scatter(mags, sharp) plt.title('Sharpness vs Magnitude') plt.xlabel('Mag') plt.ylabel('Sharp') # Scatter plot roundness vs magnitude plt.figure(3) plt.scatter(mags, round_) plt.title('Roundness vs Magnitude') plt.xlabel('Mag') plt.ylabel('Roundness1') plt.show()
def find_sources(data, threshold=30, fwhm=3.0, show_sources=True, save_sources=False, plot_name='sources.png'): """Use photutils' DAOFind to locate sources in the input image. Parameters ---------- data : numpy.ndarray 2D image threshold : float Number of sigma above the background used to determine the presence of a source show_sources : bool If True, create an image with overlain marks showing sources save_sources : bool If True, save the image of the source locations at ```plot_name``` plot_name : str Name of file to save the image with marked sources Returns ------- sources : astropy.table.Table Table of source positions """ mean, median, std = sigma_clipped_stats(data, sigma=3.0) daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold * std) sources = daofind(data - median) if sources is not None: print('{} sources found.'.format(len(sources))) if show_sources or save_sources: positions = np.transpose( (sources['xcentroid'], sources['ycentroid'])) apertures = CircularAperture(positions, r=4.) norm = ImageNormalize(stretch=SqrtStretch()) plt.imshow(data, cmap='Greys', origin='lower', norm=norm) apertures.plot(color='blue', lw=1.5, alpha=0.5) if show_sources: plt.show() if save_sources: plt.savefig(plot_name) print('Plot saved to {}'.format(plot_name)) plt.close() else: print('No sources found.') return sources
def image_norm(image_data, stretch=viz.AsinhStretch): """ Create the ImageNormalize object based on the desired stretch and pixel value range. See http://docs.astropy.org/en/stable/visualization/normalization.html """ interval = viz.MinMaxInterval() vmin, vmax = interval.get_limits(image_data.flatten()) norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=stretch()) return norm
def __init__(self, data, header, **kwargs): super().__init__(data, header, **kwargs) self._nickname = self.detector self.plot_settings['cmap'] = self._get_cmap_name() self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.25)), clip=False) # Negative value pixels can appear that lead to ugly looking images. # This can be fixed by setting the lower limit of the normalization. self.plot_settings['norm'].vmin = 0.0
def __init__(self, data, header, **kwargs): super().__init__(data, header, **kwargs) # Fill in some missing info self.meta["detector"] = "SUVI" self.meta["telescop"] = "GOES-R" self._nickname = self.detector self.plot_settings["cmap"] = plt.get_cmap(self._get_cmap_name()) self.plot_settings["norm"] = ImageNormalize( stretch=source_stretch(self.meta, AsinhStretch(0.01)))
def __init__(self, data, header, **kwargs): # Assume pixel units are arcesc if not given header['cunit1'] = header.get('cunit1', 'arcsec') header['cunit2'] = header.get('cunit2', 'arcsec') super().__init__(data, header, **kwargs) self._nickname = self.detector self.plot_settings['cmap'] = plt.get_cmap(self._get_cmap_name()) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.5)))
def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{0}-{1}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = cm.get_cmap('stereohi{det!s}'.format(det=self.detector[-1])) self.plot_settings['norm'] = ImageNormalize(stretch=source_stretch(self.meta, PowerStretch(0.25))) # Try to identify when the FITS meta data does not have the correct # date FITS keyword if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs']
def find_sources_via_segmentation(data, sigma=3, fwhm=2.0, min_pix=5, make_plot=False): """ """ yd, xd = data.shape # Let's define the background using boxes of ~50x50 pixels nboxx = int(xd / 150) nboxy = int(yd / 150) bkg_estimator = MedianBackground() bkg = Background2D(data, (nboxy, nboxx), filter_size=(3, 3), bkg_estimator=bkg_estimator) data -= bkg.background # subtract the background threshold = sigma * bkg.background_rms #threshold = detect_threshold(data, nsigma=sigma) gaussian_sigma = fwhm * gaussian_fwhm_to_sigma kernel = Gaussian2DKernel(gaussian_sigma, x_size=3, y_size=3) kernel.normalize(mode='integral') segm = detect_sources(data, threshold, npixels=min_pix, filter_kernel=kernel) segm_deblend = deblend_sources(data, segm, npixels=min_pix, filter_kernel=kernel, nlevels=32, contrast=0.001) if make_plot: norm = ImageNormalize(stretch=SqrtStretch()) fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12.5)) ax1.imshow(data, origin='lower', cmap='Greys_r', norm=norm) ax1.set_title('Data') cmap = segm.make_cmap(seed=123) ax2.imshow(segm, origin='lower', cmap=cmap, interpolation='nearest') ax2.set_title('Segmentation Image') ax3.imshow(segm_deblend, origin='lower', cmap=cmap, interpolation='nearest') ax3.set_title('Deblended Segmentation Image') plt.show() #plt.save('testing.jpg') return data, segm_deblend, bkg
def plot_peaks(box, x_peaks, y_peaks, radius=None, title=None, vmin=None, vmax=None): """ This function plots the data with peaks marked ... :param box: :param x_peaks: :param y_peaks: :return: """ # Determine the maximum value in the box and the minium value for plotting if vmin is None: vmin = max(np.nanmin(box), 0.) if vmax is None: vmax = 0.5 * (np.nanmax(box) + vmin) # Set the normalization norm = ImageNormalize(stretch=SqrtStretch()) # Make the plot plt.figure(figsize=(8, 2.5)) plt.imshow(box, origin='lower', norm=norm, interpolation='nearest', vmin=vmin, vmax=vmax, cmap="viridis") if radius is None: plt.plot(x_peaks, y_peaks, ls='none', color='white', marker='+', ms=40, lw=10, mew=4) else: positions = (x_peaks, y_peaks) apertures = CircularAperture(positions, r=radius) apertures.plot(color='green', lw=1.5, alpha=0.5) plt.xlim(0, box.shape[1] - 1) plt.ylim(0, box.shape[0] - 1) if title is not None: plt.title(title) plt.show()
def plot_removal(cutout, mask, background, removed, title=None, vmin=None, vmax=None): """ This function ... :param cutout: :param mask: :param background: :param removed: :param title: :return: """ # Get raw data of mask as a numpy array if hasattr(mask, "data"): maskdata = mask.data else: maskdata = mask norm = ImageNormalize(stretch=SqrtStretch()) # Determine the maximum value in the box and the minimum value for plotting if vmin is None: vmin = max(np.nanmin(cutout), 0.) if vmax is None: vmax = 0.5 * (np.nanmax(cutout) + vmin) # Plot the data with the best-fit model plt.figure(figsize=(20,3)) plt.subplot(1,4,1) plt.imshow(cutout, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(-0.5, cutout.xsize-0.5) plt.ylim(-0.5, cutout.ysize-0.5) plt.title("Cutout") plt.subplot(1,4,2) plt.imshow(np.ma.masked_array(cutout, mask=maskdata), origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(-0.5, cutout.xsize-0.5) plt.ylim(-0.5, cutout.ysize-0.5) plt.title("Background mask") plt.subplot(1,4,3) plt.imshow(background, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(-0.5, background.xsize-0.5) plt.ylim(-0.5, background.ysize-0.5) plt.title("Estimated background") plt.subplot(1,4,4) plt.imshow(removed, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(-0.5, background.xsize-0.5) plt.ylim(-0.5, background.ysize-0.5) plt.title("Cutout with star removed") # Set the main title if title is not None: plt.suptitle(title, size=16) # Show the plot plt.show()
def make_jpg(self): ''' Converts a FITS file to JPG image ''' # file to convert is lev0Dir/KOAID path = self.dirs['lev0'] koaid = self.fitsHeader.get('KOAID') filePath = '' for root, dirs, files in os.walk(path): if koaid in files: filePath = ''.join((root, '/', koaid)) if not filePath: self.log.error('make_jpg: Could not find KOAID: ' + koaid) return False self.log.info('make_jpg: converting {} to jpeg format'.format(filePath)) #check if already exists? (JPG conversion is time consuming) #todo: Only allow skip if not fullRun? (ie Will we ever want to regenerate the jpg?) jpgFile = filePath.replace('.fits', '.jpg') if os.path.isfile(jpgFile): self.log.warning('make_jpg: file already exists. SKIPPING') return True # verify file exists try: if os.path.isfile(filePath): # image data to convert image = self.fitsHdu[0].data interval = ZScaleInterval() vmin, vmax = interval.get_limits(image) norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=AsinhStretch()) plt.imshow(image, cmap='gray', origin='lower', norm=norm) plt.axis('off') # save as png, then convert to jpg pngFile = filePath.replace('.fits', '.png') jpgFile = pngFile.replace('.png', '.jpg') plt.savefig(pngFile) Image.open(pngFile).convert('RGB').save(jpgFile) os.remove(pngFile) plt.close() else: #TODO: if this errors, should we remove .fits file added previously? self.log.error('make_jpg: file does not exist {}'.format(filePath)) return False except: self.log.error('make_jpg: Could not create JPG: ' + jpgFile) return False return True
def ref2image(data,positions,aper,fig_name): apertures = CircularAperture(positions, r=aper[0]) annulus_apertures = CircularAnnulus(positions, r_in=aper[1], r_out=aper[2]) fig = plt.figure(figsize=(20,20));fig.add_subplot(111) apertures.plot(color='blue',lw=2,alpha=1) annulus_apertures.plot(color='red',lw=2,alpha=0.5) norm = ImageNormalize(stretch=HistEqStretch(data)) plt.imshow(data, cmap='Greys', origin='lower', norm=norm) for i in range(len(positions)): plt.text(positions[i][0]+10,positions[i][1]+10,str(i+1),fontdict={'size':'50','color':'blue'}) plt.savefig(fig_name,dpi=150) plt.show()
def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{0}-{1}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = cm.get_cmap('sohoeit{wl:d}'.format(wl=int(self.wavelength.value))) self.plot_settings['norm'] = ImageNormalize(stretch=source_stretch(self.meta, PowerStretch(0.25))) self.meta['waveunit'] = 'Angstrom' # Try to identify when the FITS meta data does not have the correct # date FITS keyword if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs']
def starbright(fnstar, fnflat, istar, axs, fg): # %% load data data = meanstack(fnstar, 100)[0] # %% flat field flatnorm = readflat(fnflat, fnstar) data = (data / flatnorm).round().astype(data.dtype) # %% background mean, median, std = sigma_clipped_stats(data, sigma=3.0) rfact = data.shape[0] // 40 cfact = data.shape[1] // 40 bg = Background(data, (rfact, cfact), interp_order=1, sigclip_sigma=3) # http://docs.astropy.org/en/stable/units/#module-astropy.units # dataphot = (data - bg.background)*u.ph/(1e-4*u.m**2 * u.s * u.sr) # data = (data-0.97*data.min()/bg.background.min()*bg.background) * u.ph/(u.cm**2 * u.s * u.sr) data = data * u.ph / (u.cm**2 * u.s * u.sr) # %% source extraction sources = daofind(data, fwhm=3.0, threshold=5 * std) # %% star identification and quantification XY = column_stack((sources["xcentroid"], sources["ycentroid"])) apertures = CircularAperture(XY, r=4.0) norm = ImageNormalize(stretch=SqrtStretch()) flux = apertures.do_photometry(data, effective_gain=camgain)[0] # %% plots fg.suptitle("{}".format(fnflat.parent), fontsize="x-large") hi = axs[-3].imshow(flatnorm, interpolation="none", origin="lower") fg.colorbar(hi, ax=axs[-3]) axs[-3].set_title("flatfield {}".format(fnflat.name)) hi = axs[-2].imshow(bg.background, interpolation="none", origin="lower") fg.colorbar(hi, ax=axs[-2]) axs[-2].set_title("background {}".format(fnstar.name)) hi = axs[-1].imshow(data.value, cmap="Greys", origin="lower", norm=norm, interpolation="none") fg.colorbar(hi, ax=axs[-1]) for i, xy in enumerate(XY): axs[-1].text(xy[0], xy[1], str(i), ha="center", va="center", fontsize=16, color="w") apertures.plot(ax=axs[-1], color="blue", lw=1.5, alpha=0.5) axs[-1].set_title("star {}".format(fnstar.name)) return flux[istar]
def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) # It needs to be verified that these must actually be set and are not # already in the header. self.meta['detector'] = "TRACE" self.meta['obsrvtry'] = "TRACE" self._nickname = self.detector # Colour maps self.plot_settings['cmap'] = cm.get_cmap('trace' + str(self.meta['WAVE_LEN'])) self.plot_settings['norm'] = ImageNormalize(stretch=source_stretch(self.meta, LogStretch()))
def test_call_clip(self): """Test that the clip keyword is used when calling the object.""" data = np.arange(5) norm = ImageNormalize(vmin=1., vmax=3., clip=False) output = norm(data, clip=True) assert_equal(output.data, [0, 0, 0.5, 1.0, 1.0]) assert np.all(~output.mask) output = norm(data, clip=False) assert_equal(output.data, [-0.5, 0, 0.5, 1.0, 1.5]) assert np.all(~output.mask)
def plot_background_subtraction(background, background_clipped, est_background, star, est_background_star): """ This function ... :param background: :param background_clipped: :param est_background: :param star: :param est_background_star: :param peaks: :return: """ norm = ImageNormalize(stretch=SqrtStretch()) # Determine the maximum value in the box and the minimum value for plotting vmax = np.nanmax(background) vmin = np.nanmin(background) if vmax <= 0 else 0.0 # Plot the data with the best-fit model plt.figure(figsize=(20,3)) plt.subplot(1,5,1) plt.imshow(background, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(0, background.shape[1]-1) plt.ylim(0, background.shape[0]-1) plt.title("Background") plt.subplot(1,5,2) plt.imshow(background_clipped, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(0, background_clipped.shape[1]-1) plt.ylim(0, background_clipped.shape[0]-1) plt.title("Sigma-clipped background") plt.subplot(1,5,3) plt.imshow(est_background, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(0, est_background.shape[1]-1) plt.ylim(0, est_background.shape[0]-1) plt.title("Estimated background") plt.subplot(1,5,4) plt.imshow(star, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(0, star.shape[1]-1) plt.ylim(0, star.shape[0]-1) plt.title("Star") plt.subplot(1,5,5) plt.imshow(star.data - est_background_star, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis") plt.xlim(0, star.shape[1]-1) plt.ylim(0, star.shape[0]-1) plt.title("Star without background") plt.show()
def plot_norm(self, stretch='linear', power=1.0, asinh_a=0.1, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None, clip=True): """Create a matplotlib norm object for plotting. This is a copy of this function that will be available in Astropy 1.3: `astropy.visualization.mpl_normalize.simple_norm` See the parameter description there! Examples -------- >>> image = SkyImage() >>> norm = image.plot_norm(stretch='sqrt', max_percent=99) >>> image.plot(norm=norm) """ import astropy.visualization as v from astropy.visualization.mpl_normalize import ImageNormalize if percent is not None: interval = v.PercentileInterval(percent) elif min_percent is not None or max_percent is not None: interval = v.AsymmetricPercentileInterval(min_percent or 0., max_percent or 100.) elif min_cut is not None or max_cut is not None: interval = v.ManualInterval(min_cut, max_cut) else: interval = v.MinMaxInterval() if stretch == 'linear': stretch = v.LinearStretch() elif stretch == 'sqrt': stretch = v.SqrtStretch() elif stretch == 'power': stretch = v.PowerStretch(power) elif stretch == 'log': stretch = v.LogStretch() elif stretch == 'asinh': stretch = v.AsinhStretch(asinh_a) else: raise ValueError('Unknown stretch: {0}.'.format(stretch)) vmin, vmax = interval.get_limits(self.data) return ImageNormalize(vmin=vmin, vmax=vmax, stretch=stretch, clip=clip)
def test_norm(self): from astropy.visualization import LogStretch from astropy.visualization.mpl_normalize import ImageNormalize norm = ImageNormalize(vmin=0., vmax=1000, stretch=LogStretch()) a = ScatterDensityArtist(self.ax, self.x1, self.y1, norm=norm) self.ax.add_artist(a) self.ax.set_xlim(-3, 5) self.ax.set_ylim(-2, 4) return self.fig
def __init__(self, data, header, **kwargs): # Assume pixel units are arcesc if not given header['cunit1'] = header.get('cunit1', 'arcsec') header['cunit2'] = header.get('cunit2', 'arcsec') if 'waveunit' not in header or not header['waveunit']: header['waveunit'] = "Angstrom" super().__init__(data, header, **kwargs) self._nickname = self.detector self.plot_settings['cmap'] = self._get_cmap_name() self.plot_settings['norm'] = ImageNormalize(stretch=source_stretch( self.meta, PowerStretch(0.5)), clip=False)
def imageshow(data,positions,aper=[8,12,20],rim_size=50): min_x=int(np.min(positions.T[0]))-rim_size;max_x=int(np.max(positions.T[0]))+rim_size min_y=int(np.min(positions.T[1]))-rim_size;max_y=int(np.max(positions.T[1]))+rim_size data=data[min_y:max_y,min_x:max_x] positions=positions-np.array([min_x,min_y]) apertures = CircularAperture(positions, r=aper[0]) annulus_apertures = CircularAnnulus(positions, r_in=aper[1], r_out=aper[2]) fig = plt.figure(figsize=(20,20));fig.add_subplot(111) apertures.plot(color='blue',lw=2,alpha=1) annulus_apertures.plot(color='red',lw=2,alpha=0.5) norm = ImageNormalize(stretch=HistEqStretch(data)) plt.imshow(data, cmap='Greys', origin='lower', norm=norm) plt.show()
def plot(self, stretch="hist", cmap="gray", origin="lower"): self.fig, self.ax = plt.subplots() if stretch == "hist": norm = ImageNormalize(stretch=HistEqStretch(self.data)) self.im = self.ax.imshow(self.data, cmap=cmap, origin=origin, norm=norm) else: self.im = self.ax.imshow(self.data, cmap=cmap, origin=origin) self.ax.set_xlim(0, self.data.shape[0]) self.ax.set_ylim(0, self.data.shape[1]) self.fig.colorbar(self.im)