def combine_multicolor(im_list_colorized, gamma=2.2, inverse=False): """ Combines input colorized RGB images [:,:,3] into one intensity-rescaled RGB image Parameters ---------- im_list_colorized : list List of colorized RGB images. e.g., [ halpha_purple, co21_orange, sio54_teal ] gamma : float Value used for gamma correction ^1/gamma. Default=2.2. inverse : bool True will invert the scale so that white is the background Returns ------- array Colorized RGB image (combined), shape=[ypixels,xpixels,3] """ combined_RGB = LinearStretch()(np.nansum(im_list_colorized, axis=0)) if inverse == True: RGB_maxints = tuple(1. - np.nanmax(combined_RGB[:, :, i]) for i in [0, 1, 2]) else: RGB_maxints = tuple( np.nanmax(combined_RGB[:, :, i]) for i in [0, 1, 2]) for i in [0, 1, 2]: combined_RGB[:, :, i] = np.nan_to_num( rescale_intensity(combined_RGB[:, :, i], out_range=(0, combined_RGB[:, :, i].max() / np.max(RGB_maxints)))) combined_RGB = LinearStretch()(combined_RGB**(1. / gamma)) # gamma correction if inverse == True: combined_RGB = 1. - combined_RGB # gamma correction return combined_RGB
def combine_cutouts( filenames, OT_coords, coords_type="world", output_name="cutout_comb.png", size=[200, 200], FoV=-1, title=None, fmts="png", ): """Create a png file with the cutouts from science image, reference image and substarcted image.""" # FIXME: need to optimise this function # May be provide the list of cutouts to create as inputs # to reuse the plt axes and avoid recreating a new pyplot # frame each time. datas, origins = _combined_cutouts(filenames, OT_coords, coords_type, size, FoV) norm1 = ImageNormalize( datas[0], # - np.median(data1), interval=ZScaleInterval(), stretch=LinearStretch(), ) norm2 = ImageNormalize( datas[1], # - np.median(data2), interval=ZScaleInterval(), stretch=LinearStretch(), ) norm3 = ImageNormalize( datas[2], # - np.median(data3), interval=ZScaleInterval(), stretch=LinearStretch(), ) # stretch=SinhStretch()) fig, axs = plt.subplots(1, 3, figsize=(15, 5)) # Substracting by the median is a trick to highlight the source # when skybackground is important. It is not correct but just # used for illustration. # axs[1].imshow(data1 - np.median(data1), axs[1].imshow(datas[0], cmap="gray", origin=origins[0], norm=norm1) axs[1].set_xlabel("Science", size=20) # axs[2].imshow(data2 - np.median(data2), axs[2].imshow(datas[1], cmap="gray", origin=origins[1], norm=norm2) axs[2].set_xlabel("Reference", size=20) # axs[0].imshow(data3 #- np.median(data3), axs[0].imshow(datas[2], cmap="gray", origin=origins[2], norm=norm3) axs[0].set_xlabel("Residuals", size=20) if title is not None: fig.suptitle(title, size=20) # Tight_layout() does not support suptitle so need to do it manually. fig.tight_layout(rect=[0, 0.03, 1, 0.80]) fig.savefig(output_name) plt.close()
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, LinearStretch()), clip=False)
def main(): filename = get_filename() ad = astrodata.open(filename) print(ad.info()) fig = plt.figure(num=filename, figsize=(8, 8)) fig.suptitle('{}'.format(filename)) palette = copy(plt.cm.viridis) palette.set_bad('w', 1.0) norm = ImageNormalize(np.dstack([ad[i].data for i in range(len(ad))]), stretch=LinearStretch(), interval=ZScaleInterval()) wcs = WCS(ad[0].hdr) ax1 = fig.add_subplot(111, projection=wcs) ax1.imshow(np.ma.masked_where(ad[0].mask > 0, ad[0].data), norm=colors.Normalize(vmin=norm.vmin, vmax=norm.vmax), origin='lower', cmap=palette) ax1.set_xlabel('RA') ax1.set_ylabel('DEC') fig.tight_layout(rect=[0.15, 0.05, 1, 0.95]) plt.savefig(filename.replace('.fits', '.png')) plt.show()
def ds9_imitate(ax, image, extent=None): norm = ImageNormalize(image, interval=ZScaleInterval(), stretch=LinearStretch()) ax.imshow(image, cmap='bone', norm=norm, origin=1, extent=extent) return
def main(fname): with fits.open(fname) as hdu: data = hdu[0].data smoothed_data = ndimage.filters.gaussian_filter(data, sigma=3, mode='nearest') norm = ImageNormalize(data, stretch=LinearStretch(), interval=ZScaleInterval()) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 5)) ax1.set_title('Cosmic Ray Incidence Map') ax2.set_title('Smoothed Cosmic Ray Incidence Map') im1 = ax1.imshow(data, norm=norm, cmap='gray', origin='lower') im2 = ax2.imshow(smoothed_data, norm=norm, cmap='gray', origin='lower') divider = make_axes_locatable(ax2) for ax in [ax1, ax2]: ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) cax = fig.add_axes([0.2, 0.15, 0.6, 0.04]) cbar = fig.colorbar(im2, cax=cax, orientation='horizontal') cbar.set_label('CR Incidences', fontweight='bold') fig.savefig('cr_incidence_plot_gauss5sig_smoothed_ACS_WFC.png', format='png', dpi=350, bbox_inches='tight') plt.show()
def source_stretch(meta, fits_stretch): """ Assign the correct source-dependent image stretching function. Parameters ---------- meta : `~astropy.utils.metadata.MetaData` The metadata to parse. fits_stretch : `~astropy.visualization.BaseStretch` Image stretching function used when the source image data comes from a FITS file. Returns ------- An image stretching function appropriate to the image data source. """ if from_helioviewer_project(meta): # Helioviewer JPEG2000 files already have a stretched data values, so # just use a linear stretch. return LinearStretch() else: # Not a Helioviewer JPEG2000 file, so assume the data has not been # stretched and so use the FITS stretching as defined in the instrument # source. return fits_stretch
def combine_multicolor(im_list_colorized, gamma=2.2, inverse=False): #Combines input colorized RGB images [:,:,3] into one intensity-rescaled #im_list_colorized: list of colorized images. e.g., [halpha_purple,co21_orange,sio54_teal] #gamma = value used for gamma correction ^1/gamma [default=2.2]. If inverse=True, will automatically use ^gamma instead. #inverse=True will invert the scale so that white is the background combined_RGB = LinearStretch()(np.nansum(im_list_colorized, axis=0)) RGB_maxints = tuple(np.nanmax(combined_RGB[:, :, i]) for i in [0, 1, 2]) for i in [0, 1, 2]: combined_RGB[:, :, i] = np.nan_to_num( rescale_intensity(combined_RGB[:, :, i], out_range=(0, combined_RGB[:, :, i].max() / np.max(RGB_maxints)))) combined_RGB = LinearStretch()(combined_RGB**(1. / gamma)) #gamma correction if inverse == True: combined_RGB = 1. - combined_RGB #gamma correction return combined_RGB
def plot_tramlines(image_data, tramlines, tramlines_bg=None): """ Displays image data with the tramline extraction regions using the viridis colour map, and the remainder in grey. """ norm = ImageNormalize(image_data, interval=PercentileInterval(99.5), stretch=LinearStretch(), clip=False) spectrum_data = np.ma.array(image_data, copy=True) tramline_mask = np.ones(spectrum_data.shape, dtype=np.bool) for tramline in tramlines: tramline_mask[tramline] = False spectrum_data[tramline_mask] = np.ma.masked fig = plt.figure(figsize=(15, 6), tight_layout=True) ax1 = fig.add_subplot(1, 1, 1) ax1.set_aspect('equal') if tramlines_bg: background_data = np.ma.array(image_data, copy=True) background_mask = np.ones(background_data.shape, dtype=np.bool) for tramline_bg in tramlines_bg: background_mask[tramline_bg] = False background_data[background_mask] = np.ma.masked ax1.imshow(background_data, cmap='gray_r', norm=norm, origin='lower') else: ax1.imshow(image_data, cmap='gray_r', norm=norm, origin='lower') spectrum_image = ax1.imshow(spectrum_data, cmap='viridis_r', norm=norm, origin='lower') fig.colorbar(spectrum_image) plt.show()
def exposeSF(self): watchpath = path_to_watch+"/Reference" before = dict ([(f, None) for f in os.listdir (watchpath)]) print("Acquiring Single Frame") self.s.send("ACQUIRESINGLEFRAME") response = self.s.recv(buffersize) print(response) self.l1["text"] = response after = dict ([(f, None) for f in os.listdir (watchpath)]) added = [f for f in after if not f in before] self.status["text"] = "READY" self.status["bg"] = "green" print("Added File: "+added[0]) hdu = fits.open(watchpath+"/"+added[0]) image = hdu[0].data*1.0 if(self.correctData): channelrefcorrect(image) norm = ImageNormalize(image, interval=PercentileInterval(99.5), stretch=LinearStretch()) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) im = ax.imshow(image, origin='lower', norm=norm, interpolation='none') ax.format_coord = Formatter(im) ax.set_title(added[0]) fig.colorbar(im)
def plot_segmap(self, img_data, segmap, centroids=None, ax1=None, ax2=None, vmin=None, vmax=None, units=None, fs=10): """ Plot segmentation map returned by SExtractor Parameters ---------- img_data segmap centroids ax1 ax2 vmin vmax units fs Returns ------- """ if vmin is not None and vmax is not None: interval = ManualInterval(vmin=vmin, vmax=vmax) else: interval = ZScaleInterval() norm = ImageNormalize(img_data, stretch=LinearStretch(), interval=interval) segm_cmap = self.rand_cmap(np.max(segmap)) self._segm_cmap = segm_cmap if ax1 is None or ax2 is None: fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True) else: fig = ax1.get_figure() im1 = ax1.imshow(img_data, norm=norm, cmap='gray', origin='lower') divider = make_axes_locatable(ax1) cax = divider.append_axes('right', size='5%', pad=0.05) cbar = fig.colorbar(im1, cax=cax, orientation='vertical') cbar.set_label(units, fontsize=fs) im2 = ax2.imshow(segmap, cmap=self.segm_cmap, origin='lower') if centroids is not None: for xy in centroids: aperture = self.mk_aperture(xy, r=3, c='red') ax1.add_patch(aperture) return fig, ax1, ax2
def show_sources(data, sources): """ Convenience method for plotting the identified sources Parameters ---------- data : FITS data to plot sources : Sources found in the FITS data Returns ------- """ fig, ax = plt.subplots(nrows=1, ncols=1) norm = ImageNormalize(data, stretch=LinearStretch(), interval=ZScaleInterval()) im = ax.imshow(data, norm=norm, cmap='gray', origin='lower') # Make apertures apertures = CircularAperture((sources['xcentroid'], sources['ycentroid']),r=3) apertures.plot(color='red', lw=1.5, alpha=0.75) ax.grid(False) fig.savefig('example_image.png', format='png', dpi=275) plt.show()
def takeImage(self): if self.cam and self.foc: if self.imgtypeVariable.get() == 'Dark': self.cam.end_exposure() self.cam.set_exposure(int(self.entryExpVariable.get()), frametype='dark') img = self.cam.take_photo() self.cam.set_exposure(int(self.entryExpVariable.get()), frametype='normal') else: self.cam.end_exposure() self.cam.set_exposure(int(self.entryExpVariable.get()), frametype='normal') img = self.cam.take_photo() mpl.close() fig = mpl.figure() ax = fig.add_subplot(1, 1, 1) norm = ImageNormalize(img, interval=PercentileInterval(99.9), stretch=LinearStretch()) im = ax.imshow(img, interpolation='none', norm=norm, cmap='gray', origin='lower') ax.format_coord = Formatter(im) fig.colorbar(im) mpl.show() return img
def set_compass(self, image): """Update the Compass plugin with info from the given image Data object.""" if self.compass is None: # Maybe another viewer has it return zoom_limits = (self.state.x_min, self.state.y_min, self.state.x_max, self.state.y_max) if data_has_valid_wcs(image): wcs = image.coords # Convert X,Y from reference data to the one we are actually seeing. if self.get_link_type(image.label) == 'wcs': x = wcs.world_to_pixel( self.state.reference_data.coords.pixel_to_world( (self.state.x_min, self.state.x_max), (self.state.y_min, self.state.y_max))) zoom_limits = (x[0][0], x[1][0], x[0][1], x[1][1]) else: wcs = None arr = image[image.main_components[0]] vmin, vmax = PercentileInterval(95).get_limits(arr) norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=LinearStretch()) self.compass.draw_compass( image.label, wcs_utils.draw_compass_mpl(arr, wcs, show=False, zoom_limits=zoom_limits, norm=norm))
def ds9_imitate(ax, image): norm = ImageNormalize(image, interval=ZScaleInterval(), stretch=LinearStretch()) ax.imshow(image, cmap='bone', norm=norm) return
def _make_image_plot(self, data, apertures, im_name): self.info('Image plot making has been started') norm = ImageNormalize(data, interval=ZScaleInterval(), stretch=LinearStretch()) plt.imshow(data, cmap='Greys', origin='lower', norm=norm) for aperture in apertures: aperture[0].plot( linewidth=self.config_section.get('aperture_linewidth'), color=self.config_section.get('aperture_in_color')) aperture[1].plot(fill=False, linewidth=self.config_section.get( 'aperture_linewidth'), color=self.config_section.get('aperture_out_color')) area = aperture[0] area.r, area.a, area.b = [self.config_section.get('r_mask')] * 3 area.plot(linewidth=self.config_section.get('area_linewidth'), color=self.config_section.get('area_color'), ls=self.config_section.get('area_linestyle')) plt.savefig(os.path.join(self.output_directory, im_name + '.png'), dpi=self.config_section.get('plot_images_dpi')) plt.clf() self.info('Image plot making has been finished')
def norm_set(self, text): stretch_dict = { 'No Stretch': None, 'Sqrt Stretch': SqrtStretch(), 'Linear Stretch': LinearStretch(), 'Squared Stretch': SquaredStretch(), 'Power Stretch': PowerStretch(self.a), 'Log Stretch': LogStretch(self.a) } self.stretch_val = stretch_dict[text] if text == 'Log Stretch': self.var_max = 10000 self.var_int = 10 self.cube = self.stretch_val(self.cube_base) #self.norm = ImageNormalize(interval=self.interval, stretch=self.stretch_val, clip=True) elif text == 'Sqrt Stretch': self.cube = np.sqrt(self.cube) elif text == 'No Stretch': self.norm = None self.cube = self.cube_base else: self.var_max = 10 self.var_int = 1 self.cube = self.stretch_val(self.cube_base, clip=False) #self.norm = ImageNormalize(interval=self.interval, stretch=self.stretch_val, clip=True) main.create_image(self.cube)
def fitplot(im, mtbl1, magtype, selected): import matplotlib.pyplot as plt from astropy.wcs import WCS from astropy.io import fits from astropy.visualization import MinMaxInterval, ZScaleInterval, PercentileInterval from astropy.visualization import SqrtStretch, LinearStretch from astropy.visualization import ImageNormalize imdata, imhdr = fits.getdata(im, header=True) norm = ImageNormalize(imdata, interval=ZScaleInterval(), stretch=LinearStretch()) wcs = WCS(imhdr) fig, ax = plt.subplots() ax = plt.subplot(projection=wcs) ax.set_xlabel('RA') ax.set_ylabel('DEC') #ax.invert_xaxis() ax.set_title(im + ' ' + magtype) ax.scatter(mtbl1[selected]['ALPHA_J2000'], mtbl1[selected]['DELTA_J2000'], transform=ax.get_transform('fk5'), s=20, edgecolor='green', facecolor='none') ax.scatter(mtbl1[~selected]['ALPHA_J2000'], mtbl1[~selected]['DELTA_J2000'], transform=ax.get_transform('fk5'), s=20, edgecolor='red', facecolor='none') img = ax.imshow(imdata, cmap='gray', norm=norm, origin='lower') ax.invert_yaxis() fig.colorbar(img) plt.savefig(os.path.splitext(im)[0] + '_' + magtype + '_FOV.png') plt.close()
def get_norm(self, stretch_text, scale_text): image = self.ax.get_images()[0] scale = None if scale_text == "MinMax": scale = MinMaxInterval() else: scale = ZScaleInterval() if stretch_text == "Linear": stretch = LinearStretch() elif stretch_text == "Log": stretch = LogStretch() else: stretch = SqrtStretch() minV, maxV = scale.get_limits( self.cubeObj.data_cube[self.cubeObj.currSlice]) norm = ImageNormalize(vmin=minV, vmax=maxV, stretch=stretch) return norm
def __init__(self): pass self.image_norms = { 'log': LogStretch(), 'linear': LinearStretch(), 'sqrt': SqrtStretch(), } self.map = None
def saveImage(self): if self.cam: if self.imgtypeVariable.get() == 'Dark': self.cam.end_exposure() self.cam.set_exposure(int(self.entryExpVariable.get()), frametype='dark') img = self.cam.take_photo() self.cam.set_exposure(int(self.entryExpVariable.get()), frametype='normal') else: self.cam.end_exposure() self.cam.set_exposure(int(self.entryExpVariable.get()), frametype='normal') img = self.cam.take_photo() telemDict = WG.get_telemetry(self.telSock) hduhdr = self.makeHeader(telemDict) #hdu = fits.PrimaryHDU(header=hduhdr) #hdulist = fits.HDUList([hdu]) if self.entryFilepathVariable.get() == "": print "Writing to: " + self.direc + self.todaydate + 'T' + time.strftime( '%H%M%S') + '.fits' fits.writeto(self.direc + self.todaydate + 'T' + time.strftime('%H%M%S') + '.fits', img, hduhdr, clobber=True) #hdulist.writeto(self.direc+self.todaydate+'T'+time.strftime('%H%M%S')+'.fits', clobber=True) else: print "Writing to: " + self.direc + self.todaydate + 'T' + time.strftime( '%H%M%S') + '_' + self.entryFilepathVariable.get( ) + ".fits" fits.writeto(self.direc + self.todaydate + 'T' + time.strftime('%H%M%S') + '_' + self.entryFilepathVariable.get() + ".fits", img, hduhdr, clobber=True) #hdulist.writeto(self.entryFilepathVariable.get(),clobber=True) #self.entryFilepathVariable.set("") mpl.close() fig = mpl.figure() ax = fig.add_subplot(1, 1, 1) norm = ImageNormalize(img, interval=PercentileInterval(99.9), stretch=LinearStretch()) #norm = ImageNormalize(img, stretch=LinearStretch()) im = ax.imshow(img, interpolation='none', norm=norm, cmap='gray', origin='lower') ax.format_coord = Formatter(im) fig.colorbar(im) mpl.show()
def __call__(self, sample): scale = ZScaleInterval() vmin, vmax = scale.get_limits(sample['image'][0][200:800, 200:800]) newimage = (np.clip(sample['image'][0], vmin, vmax) - vmin) / (vmax - vmin) # deactivate stretching: linear stretch stretch = ContrastBiasStretch(contrast=0.5, bias=0.2) # SquaredStretch() newimage = stretch(newimage) newimage -= newimage[0, 0] newimage = LinearStretch()(newimage) * 512 return { 'image': newimage.reshape(1, *newimage.shape), 'clouds': sample['clouds'] }
def subfield_select(image_data): def on_xlims_change(event_ax): global xlim xlim = event_ax.get_xlim() #print("updated xlims: ", event_ax.get_xlim()) def on_ylims_change(event_ax): global ylim ylim = event_ax.get_ylim() #print("updated ylims: ", event_ax.get_ylim()) fig = plt.figure() ax = fig.add_subplot(111) norm = ImageNormalize(image_data, interval=ZScaleInterval(), stretch=LinearStretch()) #ax.imshow(image_data, cmap = 'viridis',norm=norm) ax.imshow(image_data, vmin=image_data.mean(), vmax=2 * image_data.mean(), cmap='viridis') #ax.imshow(image_data, cmap = 'viridis') ax.callbacks.connect('xlim_changed', on_xlims_change) ax.callbacks.connect('ylim_changed', on_ylims_change) print('Close plot when selected window is satisfactory') plt.show() Xlim = [xlim[0], xlim[1]] Ylim = [ylim[0], ylim[1]] """if abs(int(Xlim[0])-int(Xlim[1])) % 2 != 0: Xlim[1] = Xlim[1]+1 if abs(int(Ylim[0])-int(Ylim[1])) % 2 != 0: Ylim[1] = Ylim[1]+1""" print('X length:', str(abs(Xlim[0] - Xlim[1]))) print('Y length:', str(abs(Ylim[0] - Ylim[1]))) #Debug-- image_data = image_data[int(Ylim[1]):int(Ylim[0]), int(Xlim[0]):int(Xlim[1])] norm = ImageNormalize(image_data, interval=ZScaleInterval(), stretch=LinearStretch()) print(image_data.shape) return image_data, Xlim, Ylim
def plot_surveys(self, img_list, formatted_coord_list, survey_list, plot_coords=True): #print(img_list) wcs_list = [] for i in img_list: #print(i[0]) wcs_list.append(wcs.WCS(i[0].header)) fig = plt.figure(figsize=(20, 20)) fig.clf() for i in range(len(img_list)): ind = i + 1 #ax = fig.add_subplot(len(img_list), 3, ind, projection=wcs_list[0]) ax = fig.add_subplot(len(img_list), 2, ind, projection=wcs_list[0]) ax.set_xlabel('RA') ax.set_ylabel('Dec') ax.set_title(survey_list[i]) #ax.imshow(img_list[i][0].data, cmap='gray') norm = ImageNormalize(img_list[i][0].data, interval=ZScaleInterval(), stretch=LinearStretch()) ax.imshow(img_list[i][0].data, origin='lower', norm=norm, cmap='gray_r') #print((formattedcoord_list[i].ra, formattedcoord_list[i].dec)) if plot_coords: for cat in formatted_coord_list: ax.plot(cat.ra, cat.dec, 'o', transform=ax.get_transform('icrs'), mec='r', mfc='none')
def run( self ): fitslist = glob.glob( r"D:\tmp\20160614\118-nf\*.fits" ) for f in fitslist: t = time.time() data = fits.getdata( f ) norm = ImageNormalize( data, interval = ZScaleInterval(), stretch = LinearStretch() ) self.canvas.img.set_data( data ) self.canvas.img.set_norm( norm ) self.canvas.axes.draw_artist( self.canvas.img ) self.canvas.fig.canvas.update() self.canvas.fig.canvas.flush_events() print( time.time() - t )
def zimshow(ax, image, stretch=LinearStretch(), cmap=None, origin="lower", zscale_kw={}, **kwargs): im = ax.imshow(image, norm=znorm(image, stretch=stretch, **zscale_kw), origin=origin, cmap=cmap, **kwargs) return im
def imshow_zscale(image, fits=False, grid=True, ticks=False): if fits == True: d = fits.getdata(image) else: d = image norm = ImageNormalize(d, interval=ZScaleInterval(), stretch=LinearStretch()) plt.imshow(d, cmap=plt.cm.gray, norm=norm, interpolation='none') if ticks: plt.tick_params(labelsize=16) if grid: plt.grid() return None
def exposeCDS(self): watchpath = path_to_watch + "/CDSReference" before = dict([(f, None) for f in os.listdir(watchpath)]) print("Acquiring CDS Frame") self.s.send("ACQUIRECDS") response = self.s.recv(buffersize) print(response) self.l1["text"] = response after = dict([(f, None) for f in os.listdir(watchpath)]) added = [f for f in after if not f in before] self.status["text"] = "READY" self.status["bg"] = "green" print("Added Directory: " + added[0] + ' , ' + self.sourcename.get()) self.writeObsdata(watchpath + '/' + added[0]) hdu = fits.open(watchpath + "/" + added[0] + "/Result/CDSResult.fits") image = hdu[0].data * 1.0 if (self.correctData.get()): channelrefcorrect(image) norm = ImageNormalize(image, interval=PercentileInterval(99.5), stretch=LinearStretch()) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) im = ax.imshow(image, origin='lower', norm=norm, interpolation='none') ax.format_coord = Formatter(im) ax.set_title(added[0]) fig.colorbar(im) if (self.histogram.get()): fig = plt.figure() subimage = image[900:1100, 900:1100].flatten() mean = np.mean(subimage) std = np.std(subimage) plt.hist(subimage, bins=200) plt.xlim([mean - 3 * std, mean + 3 * std]) plt.title("Mean = %f5, Std = %f5" % (mean, std)) plt.show() if (self.arcfwhm.get()): pointing(watchpath + "/" + added[0] + '/Result/CDSResult.fits') hdu.close()
def plot_hst_loc(self, i = 5, df = None, key='start', save=False): self.fig = plt.figure(figsize=(9, 7)) # Get the model for the SAA self.map = Basemap(projection='cyl') self.draw_map() # Generate an SAA contour saa = [list(t) for t in zip(*costools.saamodel.saaModel(i))] # Ensure the polygon representing the SAA is a closed curve by adding # the starting points to the end of the list of lat/lon coords saa[0].append(saa[0][0]) saa[1].append(saa[1][0]) self.map.plot(saa[1], saa[0], c='r', latlon=True, label='SAA contour {}'.format(i)) if df is None: lat, lon, rate = self.data_df['{}_latitude'.format(key)], \ self.data_df['{}_longitude'.format(key)], \ self.data_df['incident_cr_rate'] else: lat, lon, rate = df['{}_latitude'.format(key)], \ df['{}_longitude'.format(key)], \ df['incident_cr_rate'] norm = ImageNormalize(rate, stretch=LinearStretch(), vmin=0.75, vmax=2) scat = self.map.scatter(lon, lat, marker='o', s=10, latlon=True, c=rate, alpha=0.5, norm = norm, cmap='Reds') cax = self.fig.add_axes([0.1, 0.1, 0.8, 0.05]) cbar = self.fig.colorbar(scat, cax=cax, orientation='horizontal') cbar.set_label('cosmic rays/s/cm^2', fontweight='bold') cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation=45) if save: self.fig.savefig('lat_lon_{}.png'.format(key), format='png', dpi=300) plt.show()
def plot_image(image, scale='linear', origin='lower', xlabel='Pixel Column Number', ylabel='Pixel Row Number', clabel='Flux ($e^{-}s^{-1}$)', title=None, **kwargs): """Utility function to plot a 2D image Parameters ---------- image : 2d array Image data. scale : str Scale used to stretch the colormap. Options: 'linear', 'sqrt', or 'log'. origin : str The origin of the coordinate system. xlabel : str Label for the x-axis. ylabel : str Label for the y-axis. clabel : str Label for the color bar. title : str or None Title for the plot. kwargs : dict Keyword arguments to be passed to `matplotlib.pyplot.imshow`. """ fig, ax = plt.subplots() vmin, vmax = PercentileInterval(95.).get_limits(image) if scale == 'linear': norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=LinearStretch()) elif scale == 'sqrt': norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=SqrtStretch()) elif scale == 'log': norm = ImageNormalize(vmin=vmin, vmax=vmax, stretch=LogStretch()) else: raise ValueError("scale {} is not available.".format(scale)) cax = ax.imshow(image, origin=origin, norm=norm, **kwargs) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_title(title) cbar = fig.colorbar(cax, norm=norm, label=clabel) return fig, ax