def to_fig(self, rowrange, colrange, extension=1, cmap='Greys_r', cut=None, dpi=50): """Turns a fits file into a cropped and contrast-stretched matplotlib figure.""" fts = fitsio.FITS(self.fits_filename) if (np.isfinite(fts[extension].read())).sum() == 0: raise InvalidFrameException() image = fts[extension].read()[rowrange[0]:rowrange[1], colrange[0]:colrange[1]] fts.close() if cut is None: cut = np.percentile(image[np.isfinite(image)], [10, 99.5]) image_scaled = visualization.scale_image(image, scale="log", min_cut=cut[0], max_cut=cut[1]) #min_percent=0.5, max_percent=99.5) px_per_kepler_px = 20 dimensions = [image.shape[0] * px_per_kepler_px, image.shape[1] * px_per_kepler_px] figsize = [dimensions[1]/dpi, dimensions[0]/dpi] dpi = 440 / float(figsize[0]) fig = pl.figure(figsize=figsize, dpi=dpi) ax = fig.add_subplot(1, 1, 1, axisbg='green') ax.matshow(image_scaled, aspect='auto', cmap=cmap, origin='lower', interpolation='nearest') ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') #ax.set_axis_bgcolor('red') fig.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0) fig.canvas.draw() return fig
def generate_tweet(): """Generate a tweet and jpg. Returns ------- (status, jpg) : (str, str) """ imageid, fitsurl = select_random_image() log.info('Opening {0}'.format(fitsurl)) fts = fits.open(fitsurl) # Create the status message imgtime = fts[0].header['IMG-TIME'] instrument = fts[0].header['INSTRUME'][8:] exptime = fts[0].header['EXPTIME'] timestr = Time(imgtime).datetime.strftime('%d %b %Y, %H:%M UT').lstrip("0") url = 'http://imagearchives.esac.esa.int/picture.php?/{0}'.format(imageid) status = ('A new #Rosetta image was recently released!\n' '⌚ {}.\n' '📷 #{}.\n' '⌛ {:.2f}s.\n' '🔗 {}'.format(timestr, instrument, exptime, url)) # Create the cropped and scaled image image_cropped = entropy_crop(fts[0].data, width=600, height=300) image_scaled = scale_image(image_cropped, scale='linear', min_percent=0.05, max_percent=99.95) # Save the result as an image image_fn = '/tmp/rosettabot.png' log.info('Writing {0}'.format(image_fn)) imsave(image_fn, image_scaled, cmap=cm.gray) return (status, image_fn)
def scale_and_downsample(data, downsample=4, min_percent=20, max_percent=99.5): scaled_data = scale_image(data, min_percent=min_percent, max_percent=max_percent) if downsample > 1: scaled_data = block_reduce(scaled_data, block_size=(downsample, downsample)) return scaled_data
def render_fits_image(hdu, scale='asinh', cmap=plt.cm.gray, xlabel='RA', ylabel='Dec', title=None): "Use matplotlib and astropy to render a FITS image HDU" wcs = astropy.wcs.WCS(hdu.header) fig = plt.figure() axes = fig.add_subplot(111, projection=wcs) plt.imshow(viz.scale_image(hdu.data, scale=scale), cmap=cmap, origin='lower', interpolation='none') plt.xlabel(xlabel) plt.ylabel(ylabel) if title is not None: axes.set_title(title) return fig
def scale(self, scale = 'linear', power = 1.0, min_cut = None, max_cut = None): """ Name: scale Description: Allows for rescaling the image. This will always scale the original image so calling scale a second time on the image will overwrite a previous scaling. Parameters: scale power min_cut max_cut """ self.__image = vis.scale_image(self.__original, scale = scale, power = power, min_cut = min_cut, max_cut = max_cut)
def ndarray_to_png(x, min_percent=20, max_percent=99.5): shape = np.array(x.shape) # Reverse order for reasons I do not understand... shape = shape[::-1] if len(shape) != 2: return width = 600 # pixels downsample = (shape[0] // width) + 1 scaled_data = scale_image(x, min_percent=min_percent, max_percent=max_percent) if downsample > 1: scaled_data = block_reduce(scaled_data, block_size=(downsample, downsample)) img_buffer = BytesIO() mimg.imsave(img_buffer, scaled_data, format='png', cmap='gray') return img_buffer.getvalue()
def to_fig(self, rowrange, colrange, extension=1, cmap='Greys_r', cut=None, dpi=50): """Turns a fits file into a cropped and contrast-stretched matplotlib figure.""" with fits.open(self.fits_filename) as fts: if (-np.isnan(fts[extension].data)).sum() == 0: raise InvalidFrameException() image = fts[extension].data[rowrange[0]:rowrange[1], colrange[0]:colrange[1]] if cut is None: cut = np.percentile(image[-np.isnan(image)], [10, 99.5]) image_scaled = visualization.scale_image( image, scale="log", min_cut=cut[0], max_cut=cut[1]) #min_percent=0.5, max_percent=99.5) px_per_kepler_px = 20 dimensions = [ image.shape[0] * px_per_kepler_px, image.shape[1] * px_per_kepler_px ] figsize = [dimensions[1] / dpi, dimensions[0] / dpi] dpi = 440 / float(figsize[0]) fig = pl.figure(figsize=figsize, dpi=dpi) ax = fig.add_subplot(1, 1, 1, axisbg='green') ax.matshow(image_scaled, aspect='auto', cmap=cmap, origin='lower', interpolation='nearest') ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') #ax.set_axis_bgcolor('red') fig.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0) fig.canvas.draw() return fig
lmaxb=base #lmr=(99.6,99.5,99.9,99.95,99.5,99.93,99.91) for i in files: image=[] for j in range(7): image_file_B = i+'_'+type[j]+'_B.fits' image_file_I = i+'_'+type[j]+'_I.fits' image_file_V = i+'_'+type[j]+'_V.fits' image_data_B = fits.getdata(image_file_B) image_data_V = fits.getdata(image_file_V) image_data_I = fits.getdata(image_file_I) image_log_r=scale_image(image_data_I,'log',max_cut= lmaxr[j]) image_log_b=scale_image(image_data_B,'log',max_cut= lmaxb[j]) image_log_g=scale_image(image_data_V,'log',max_cut= lmaxg[j]) # image_log_r=scale_image(image_data_I,'log',max_percent= lmr[j]) # image_log_b=scale_image(image_data_B,'log',max_percent= lmr[j]) # image_log_g=scale_image(image_data_V,'log',max_percent= lmr[j]) if j==4: image.append(image_cut(image_log_r,image_log_g,image_log_b,1.0,0.05,True)) else: image.append(image_cut(image_log_r,image_log_g,image_log_b,1.0,0.05)) image_seven=image_align7(image[0],image[1],image[2],image[3], image[4],image[5],image[6]) fig = plt.figure(figsize=(6*3,6*(np.sqrt(3)+1))) fontsize=20
if image_entropy(top_slice, img_min, img_max) < image_entropy(bottom_slice, img_min, img_max): top_y = top_y + slice_size top_slice = None else: bottom_y = bottom_y - slice_size bottom_slice = None return img[top_y : top_y + height, left_x + width : left_x : -1] if __name__ == "__main__": """Example use""" from matplotlib.image import imsave from matplotlib import cm from astropy.io import fits from astropy import log from astropy.visualization import scale_image fts = fits.open( "http://imagearchives.esac.esa.int/data_raw/ROSETTA/NAVCAM" "/RO-C-NAVCAM-2-PRL-MTP007-V1.0/DATA/CAM1" "/ROS_CAM1_20140922T060854F.FIT" ) img = fts[0].data width, height = 512, 256 image_cropped = entropy_crop(img, width, height) image_scaled = scale_image(image_cropped, scale="linear", min_percent=0.05, max_percent=99.95) jpg_fn = "test.jpg" log.info("Writing {0}".format(jpg_fn)) imsave(jpg_fn, image_scaled, cmap=cm.gray)
def overlap_skeletons(image, big_skel, norm_skel, aplpy_plot=True, save_figure=True, save_name="skeletons", output_file_type="png", rasterized=True, vmin=None, vmax=None): ''' Make a nice aplpy plot of the different skeletons. The original image should be passed, and it will be expanded to match the dimensions of the regridded skeleton. ''' # Load files in image, hdr = fits.getdata(image, header=True) image[np.isnan(image)] = 0.0 norm_skel = fits.getdata(norm_skel) norm_skel = (norm_skel > 0).astype(int) big_skel = fits.getdata(big_skel) big_skel = (big_skel > 0).astype(int) big_skel_hdu = fits.PrimaryHDU(big_skel, header=hdr) # The original image and the normal skeleton should have the same # dimensions. assert image.shape == norm_skel.shape image = zoom(image, [i / float(j) for j, i in zip(image.shape, big_skel.shape)]) assert image.shape == big_skel.shape hdr['NAXIS1'] = image.shape[1] hdr['NAXIS2'] = image.shape[0] image_hdu = fits.PrimaryHDU(image, header=hdr) norm_skel_zoom = \ zoom(norm_skel, [i/float(j) for j, i in zip(norm_skel.shape, big_skel.shape)], order=0) assert norm_skel_zoom.shape == big_skel.shape norm_skel_hdu = fits.PrimaryHDU(norm_skel_zoom, header=hdr) if aplpy_plot: try: import aplpy except ImportError: ImportError("Cannot import aplpy. Do not enable aplpy.") fig = aplpy.FITSFigure(image_hdu) fig.show_grayscale(invert=True, stretch="arcsinh", vmin=vmin, vmax=vmax) fig.tick_labels.set_xformat('hh:mm') fig.tick_labels.set_yformat('dd:mm') fig.tick_labels.set_font(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') fig.axis_labels.set_font(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') # fig.add_grid() # NOTE! - rasterization will only work with my fork of aplpy! # [email protected]:e-koch/aplpy.git on branch 'rasterize_contours' fig.show_contour(norm_skel_hdu, colors="red", linewidths=1.5, rasterize=True) fig.show_contour(big_skel_hdu, colors="blue", rasterize=True) fig.show_colorbar() fig.colorbar.set_label_properties(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') fig.colorbar.set_axis_label_text('Surface Brightness (MJy/sr)') fig.colorbar.set_axis_label_font(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') if save_figure: fig.save(save_name + "." + output_file_type) fig.close() else: # Using matplotlib from astropy.visualization import scale_image scaled_image = scale_image(image, scale='asinh', asinh_a=0.005) p.imshow(scaled_image, interpolation='nearest', origin='lower', cmap='binary') p.contour(norm_skel_zoom, colors='r', linewidths=2) p.contour(big_skel, colors='b', linewidths=1) if save_figure: p.save(save_name + "." + output_file_type, rasterized=rasterized) p.close() else: p.show(block=True)
tp.lightcurve(info) position = (xnew,ynew) aperture = CircularAperture(position, r=radius) bkg_aperture = CircularAnnulus(position, r_in=15., r_out=20.) # perform the photometry; the default method is 'exact' phot = aperture_photometry(image, aperture) bkg = aperture_photometry(image, bkg_aperture) # calculate the mean background level (per pixel) in the annuli bkg_mean = bkg['aperture_sum'] / bkg_aperture.area() bkg_mean bkg_sum = bkg_mean * aperture.area() # plot the apertures plt.imshow(scale_image(image, scale='sqrt', percent=98.), origin='lower',cmap='gray') aperture.plot(color='blue') bkg_aperture.plot(color='cyan', hatch='//', alpha=0.8) plt.xlim(xnew-100,xnew+100) plt.ylim(ynew-100,ynew+100) phot['bkg_sum'] = bkg_sum
def overlap_skeletons(image, big_skel, norm_skel, aplpy_plot=True, save_figure=True, save_name="skeletons", output_file_type="png", rasterized=True, vmin=None, vmax=None): ''' Make a nice aplpy plot of the different skeletons. The original image should be passed, and it will be expanded to match the dimensions of the regridded skeleton. ''' # Load files in image, hdr = fits.getdata(image, header=True) image[np.isnan(image)] = 0.0 norm_skel = fits.getdata(norm_skel) norm_skel = (norm_skel > 0).astype(int) big_skel = fits.getdata(big_skel) big_skel = (big_skel > 0).astype(int) big_skel_hdu = fits.PrimaryHDU(big_skel, header=hdr) # The original image and the normal skeleton should have the same # dimensions. assert image.shape == norm_skel.shape image = zoom(image, [i/float(j) for j, i in zip(image.shape, big_skel.shape)]) assert image.shape == big_skel.shape hdr['NAXIS1'] = image.shape[1] hdr['NAXIS2'] = image.shape[0] image_hdu = fits.PrimaryHDU(image, header=hdr) norm_skel_zoom = \ zoom(norm_skel, [i/float(j) for j, i in zip(norm_skel.shape, big_skel.shape)], order=0) assert norm_skel_zoom.shape == big_skel.shape norm_skel_hdu = fits.PrimaryHDU(norm_skel_zoom, header=hdr) if aplpy_plot: try: import aplpy except ImportError: ImportError("Cannot import aplpy. Do not enable aplpy.") fig = aplpy.FITSFigure(image_hdu) fig.show_grayscale(invert=True, stretch="arcsinh", vmin=vmin, vmax=vmax) fig.tick_labels.set_xformat('hh:mm') fig.tick_labels.set_yformat('dd:mm') fig.tick_labels.set_font(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') fig.axis_labels.set_font(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') # fig.add_grid() # NOTE! - rasterization will only work with my fork of aplpy! # [email protected]:e-koch/aplpy.git on branch 'rasterize_contours' fig.show_contour(norm_skel_hdu, colors="red", linewidths=1.5, rasterize=True) fig.show_contour(big_skel_hdu, colors="blue", rasterize=True) fig.show_colorbar() fig.colorbar.set_label_properties(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') fig.colorbar.set_axis_label_text('Surface Brightness (MJy/sr)') fig.colorbar.set_axis_label_font(size='large', weight='medium', stretch='normal', family='sans-serif', style='normal', variant='normal') if save_figure: fig.save(save_name+"."+output_file_type) fig.close() else: # Using matplotlib from astropy.visualization import scale_image scaled_image = scale_image(image, scale='asinh', asinh_a=0.005) p.imshow(scaled_image, interpolation='nearest', origin='lower', cmap='binary') p.contour(norm_skel_zoom, colors='r', linewidths=2) p.contour(big_skel, colors='b', linewidths=1) if save_figure: p.save(save_name+"."+output_file_type, rasterized=rasterized) p.close() else: p.show(block=True)