def example(self): """ This function ... :return: """ # Read in the three images downloaded from here: # g: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-g-001737-5-0039.fits.bz2 # r: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-r-001737-5-0039.fits.bz2 # i: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-i-001737-5-0039.fits.bz2 g = fits.open('frame-g-001737-5-0039.fits.bz2')[0] r = fits.open('frame-r-001737-5-0039.fits.bz2')[0] i = fits.open('frame-i-001737-5-0039.fits.bz2')[0] # remap r and i onto g r_new, r_mask = reproject_interp(r, g.header) i_new, i_mask = reproject_interp(i, g.header) # zero out the unmapped values i_new[np.logical_not(i_mask)] = 0 r_new[np.logical_not(r_mask)] = 0 # red=i, green=r, blue=g # make a file with the default scaling rgb_default = make_lupton_rgb(i_new, r_new, g.data, filename="ngc6976-default.jpeg") # this scaling is very similar to the one used in Lupton et al. (2004) rgb = make_lupton_rgb(i_new, r_new, g.data, Q=10, stretch=0.5, filename="ngc6976.jpeg")
def make_example_rgbs(self): """ This function ... :return: """ # Read in the three images downloaded from here: # g: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-g-001737-5-0039.fits.bz2 # r: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-r-001737-5-0039.fits.bz2 # i: http://dr13.sdss.org/sas/dr13/eboss/photoObj/frames/301/1737/5/frame-i-001737-5-0039.fits.bz2 g = fits.open('frame-g-001737-5-0039.fits.bz2')[0] r = fits.open('frame-r-001737-5-0039.fits.bz2')[0] i = fits.open('frame-i-001737-5-0039.fits.bz2')[0] # remap r and i onto g r_new, r_mask = reproject_interp(r, g.header) i_new, i_mask = reproject_interp(i, g.header) # zero out the unmapped values i_new[np.logical_not(i_mask)] = 0 r_new[np.logical_not(r_mask)] = 0 # red=i, green=r, blue=g # make a file with the default scaling rgb_default = make_lupton_rgb(i_new, r_new, g.data, filename="ngc6976-default.jpeg") # this scaling is very similar to the one used in Lupton et al. (2004) rgb = make_lupton_rgb(i_new, r_new, g.data, Q=10, stretch=0.5, filename="ngc6976.jpeg")
def RGB_with_same_stretch(): red = input("Enter name of the red channel : ") green = input("Enter name of the green channel : ") blue = input("Ennter name of the blue channel : ") #function calling to view stretched image and save them print("~~~~~~~~~~AVAIABLE STRETCH~~~~~~~~~~\n") print("\t1.LogStretch(default a=1000)") #input of stretch choice st_ch = int( input("\n\nEnter the number whose stretch you want to apply : ")) if st_ch == 1: #red file red = stretch.log(red) #green file green = stretch.log(green) #blue file blue = stretch.log(blue) #RGB image using make_lupton_RGB RGB_image = viz.make_lupton_rgb(red, green, blue, Q=10, stretch=0.5) plt.imshow(RGB_image) plt.show()
def view_image_rgb(images, Q=2.0, stretch=4.0, **imshow_kwargs): """ Merge images into a single RGB image. This function assumes the image array is ordered [g, r, i]. Args: images (List[np.array]): a list of at least 3 2-dimensional arrays of pixel values corresponding to different photometric bandpasses imshow_kwargs (dict): dictionary of keyword arguments and their values to pass to matplotlib.pyplot.imshow """ assert len(images) > 2, "3 images are needed to generate an RGB image" rgb = make_lupton_rgb(images[2], images[1], images[0], Q=Q, stretch=stretch) plt.figure() plt.imshow(rgb, **imshow_kwargs) plt.xticks([], []) plt.yticks([], []) plt.show(block=True) plt.close() return
def plot_RGB(img): import numpy as np from astropy.io import fits from astropy.visualization import SqrtStretch, LogStretch from astropy.visualization import LinearStretch, AsinhStretch from astropy.visualization import make_lupton_rgb forCasting = np.float_() g = img[0] r = img[1] i = img[2] max_size = np.max([g.shape[0], r.shape[0], i.shape[0]]) image_b = fix_size(g, max_size) image_g = fix_size(r, max_size) image_r = fix_size(i, max_size) norm = np.nanpercentile(image_b, 99) image_r /= norm image_g /= norm image_b /= norm image = make_lupton_rgb(image_r, image_g, image_b, Q=8, stretch=0.5, minimum=image_b.min()) # Cut the top rows - contains black pixels return image
def master_color(R_hdul, G_hdul, B_hdul, dtype=np.float32, saveto=None, **kwargs): r""" Generate an RGB image based on three science frames (preferable R, V, B). This use `astropy.visualization.make_lupton_rgb`. Parameters ---------- R_hdul : astropy.io.fits.HDUList Used for red channel. G_hdul : astropy.io.fits.HDUList Used for green channel (normally use V-filter). B_hdul : astropy.io.fits.HDUList Used for blue channel. dtype : data-type, optional Type to use for computing, defaults to np.float32. saveto : str, optional If this is not set (None, default) files won't be saved. If this is set to a string, save the file with the string as name. The format is determined by the file extension. Files are ALWAYS OVERWRITTEN! For other parameters see astropy.visualization.make_lupton_rgb. Returns ------- data : numpy.ndarray """ data = np.array( [R_hdul[0].data.astype(dtype), G_hdul[0].data.astype(dtype), B_hdul[0].data.astype(dtype)], dtype ) return make_lupton_rgb(*data, filename=saveto, **kwargs)
def process_image(self, x): """Process data.""" if self.augment: # flip and transpose # this is not correct now, labels change too!!! x = aug_im(x, self.rng.rand() > 0.5, self.rng.rand() > 0.5, self.rng.rand() > 0.5) if self.luptonize: rgb_q = 15 rgb_stretch = 0.5 rgb_min = 0 x = make_lupton_rgb(x[:, :, 2], x[:, :, 1], x[:, :, 0], Q=rgb_q, stretch=rgb_stretch, minimum=rgb_min) #x = make_lupton_rgb(x[:,:,2], x[:,:,2], x[:,:,2], # Q=rgb_q, stretch=rgb_stretch, minimum=rgb_min) x = np.array(x) x = np.array([xi / 255. for xi in x]) if self.smooth: #x = np.array([gaussian_filter(xi, sigma=1) for xi in x]) x = cv2.blur(x, (5, 5)) if self.normalize: x = np.arcsinh(x) x = (x - np.min(x)) / np.ptp(x) #print(x.shape) x = x.transpose(2, 0, 1) #print(x.shape) x = x.reshape(self.x_shape) return x
def make_rgb_image(self, stretch=0.4, Q=8): rgb_image = make_lupton_rgb(self.rgb_data.red, self.rgb_data.green, self.rgb_data.blue, stretch=stretch, Q=Q) return rgb_image
def make_rgb(self, rgb_bands='irg', stretch=0.4, Q=8): from astropy.visualization import make_lupton_rgb rgb = make_lupton_rgb(self[rgb_bands[0]].getImage().getArray(), self[rgb_bands[1]].getImage().getArray(), self[rgb_bands[2]].getImage().getArray(), stretch=stretch, Q=Q) return rgb
def draw_snapshot_rgb(s, num, ax, minimum=20.0, stretch=15000, Q=15): ds = s.load_vtk(num) dd = ds.get_field(['nH2', 'nHI', 'nH', 'j_X', 'nesq']) dd['NH_neu'] = (2.0 * dd['nH2'].sum(dim='z') + 2.0 * dd['nHI'].sum(dim='z')) * dd.domain['dx'][2] dd['I_X'] = dd['j_X'].sum( dim='z') * dd.domain['dx'][2] * s.u.length.cgs.value dd['EM'] = dd['nesq'].sum(dim='z') * dd.domain['dx'][2] # Make r and g to have the same maximum #norm_b = dd['NH_neu'].data.max()/dd['I_X'].data.max() #norm_g = dd['NH_neu'].data.max()/dd['EM'].data.max() #norm_b = 1.0 #norm_g = 1.0 norm_b = 1625343998.93 norm_g = 0.04300 r = dd['NH_neu'].data b = dd['I_X'].data * norm_b g = dd['EM'].data * norm_g #print(r.max(),g.max(),b.max(),r.min(),g.min(),b.min()) #print(norm_b,norm_g) image = make_lupton_rgb(r, g, b, minimum=minimum, stretch=stretch, Q=Q) ax.imshow(image, interpolation='bicubic', origin='lower') ax.set_xticks([]) ax.set_yticks([]) ax.set_xticklabels('') ax.set_yticklabels('') return ax, dd, image
def get_images(self, **kwargs): """ main method: get cutout images for the given options return a list of (dataid, image). If no images found, return an empty list """ if 'ra' in kwargs and 'dec' in kwargs: self.coord = kwargs['ra'], kwargs['dec'] if 'visit_level' in kwargs: self.visit_level = kwargs['visit_level'] if 'filter' in kwargs: self.filter = kwargs['filter'] if 'size' in kwargs: self.size = kwargs['size'] if 'image_size' in kwargs: self.image_size = kwargs['image_size'] if 'pixel_scale' in kwargs: self.pixel_scale = kwargs['pixel_scale'] if len(self.filter) == 3: results = list(self._iter_dataid_raw_images(limit=3)) if len(results) < 3 or all(image is None for _, image in results): return [] zero = np.zeros((self.side_pixel, self.side_pixel)) images = [zero if image is None else image for _, image in results] filters = ''.join(('' if image is None else dataid['filter'] for dataid, image in results)) dataid = dict(results[0][0], filter=filters) return [(dataid, self.image_to_png_data(make_lupton_rgb(*images[::-1], stretch=3, Q=8), composite=True))] return [(dataid, self.image_to_png_data(image)) for dataid, image in self._iter_dataid_raw_images(limit=10) if image is not None]
def make_rgb(self, rgb_bands='irg', stretch=0.4, Q=8): from astropy.visualization import make_lupton_rgb rgb = make_lupton_rgb(self[rgb_bands[0]].getImage().getArray(), self[rgb_bands[1]].getImage().getArray(), self[rgb_bands[2]].getImage().getArray(), stretch=stretch, Q=Q) return rgb
def make_rgb(self, rgb_bands='irg', stretch=0.8, Q=8): rgb = make_lupton_rgb(self.image[rgb_bands[0]], self.image[rgb_bands[1]], self.image[rgb_bands[2]], stretch=stretch, Q=Q) return rgb
def plot_batch(self, index=0, filename=None): # FIXME : Currently hardcoded for a batchsize of 128 if self.batch_size != 128: warnings.warn('This method is hard coded for batchsize of 128 for now') if not has_astropy(): warnings.warn('Plotting galaxies requires the astropy package') return else: from astropy.visualization import make_lupton_rgb (images, ebvs), z_truths = self._get_batch_at(index, is_categorical=True) cols = 10 rows = math.ceil(self.batch_size / cols) fig, axes = plt.subplots(rows, cols, figsize=(rows, cols)) fig.suptitle(f'batch {index} from the dataset') for row_count in range(rows): for col_count in range(cols): axes[row_count][col_count].tick_params( axis='x', which='both', bottom=False, top=False, labelbottom=False ) axes[row_count][col_count].tick_params( axis='y', which='both', left=False, right=False, labelleft=False ) row_count, col_count = 0, 0 plt.subplots_adjust(hspace=0.8, wspace=0.2) for i, (image, ebv, z_truth) in enumerate(zip(images, ebvs, z_truths)): im = make_lupton_rgb(image[:, :, 3], image[:, :, 2], image[:, :, 1], Q=10, stretch=0.5) axes[row_count, col_count].imshow(im) axes[row_count, col_count].set_xlabel(f'z = {str(round(z_truth, 6))} \n' f'ebv = {ebv}', fontsize=6) col_count += 1 if col_count == cols: row_count += 1 col_count = 0 for j in range(col_count, cols): axes[row_count][j].axis('off') if filename is None: filename = f'batch_{index}.png' plt.savefig(filename, bbox_inches='tight')
def draw_velocity_map(city): image_r = pickle.load( open('velocity_arrays/image_r_array_{}.p'.format(city), 'rb')) image_g = pickle.load( open('velocity_arrays/image_g_array_{}.p'.format(city), 'rb')) image_b = pickle.load( open('velocity_arrays/image_b_array_{}.p'.format(city), 'rb')) image = make_lupton_rgb(image_r, image_g, image_b, stretch=0.5) plt.imsave('velocity_maps/{}_velocity_map.png'.format(city), image)
def plot_lupton(img): g = img[:, :, 1:2] r = img[:, :, 2:3] i = img[:, :, 3:4] rgb = make_lupton_rgb(i, r, g, Q=10, stretch=0.5) plt.axis('off') plt.imshow(rgb)
def save_images(X, save_path, luptonize=False, unnormalize=False): # [0, 1] -> [0,255] if luptonize: unnormalize = False print(X.ndim) print(X.shape) print(np.max(X.flatten()), np.min(X.flatten())) #if isinstance(X.flatten()[0], np.floating): # X = (255.99*X).astype('uint8') n_samples = X.shape[0] rows = int(np.sqrt(n_samples)) while n_samples % rows != 0: rows -= 1 nh, nw = rows, n_samples / rows if X.ndim == 2: X = np.reshape( X, (X.shape[0], int(np.sqrt(X.shape[1])), int(np.sqrt(X.shape[1])))) if X.ndim == 4: # BCHW -> BHWC #X = X.transpose(0,2,3,1) #print("transpose") #print(X.shape) if unnormalize: X = (255. * X).astype('uint8') h, w = X[0].shape[:2] img = np.zeros((int(h * nh), int(w * nw), 3)) #X = X.transpose(0,2,3,1) elif X.ndim == 3: h, w = X[0].shape[:2] img = np.zeros((int(h * nh), int(w * nw))) rgb_q = 15 rgb_stretch = 0.5 rgb_min = 0 for n, x in enumerate(X): j = n // nw i = n % nw if luptonize: x = make_lupton_rgb(x[:, :, 2], x[:, :, 1], x[:, :, 0], Q=rgb_q, stretch=rgb_stretch, minimum=rgb_min) #x = np.roll(x, 1, axis=2) if n == 0: print(x.shape) print(x[40:-40, 40:-40]) #x = np.roll(x, 1, axis=2) img[int(j * h):int(j * h + h), int(i * w):int(i * w + w)] = x imwrite(save_path, img)
def RGB(): Data = fits.getdata(input('input fits file:')) B = Data[0, :, :] G = Data[1, :, :] R = Data[2, :, :] image = make_lupton_rgb(R, G, B, stretch=0.01) mean = np.mean(image) std = np.std(image) plt.imshow(image) #,vmin = mean-std , vmax = mean+3*std) plt.show()
def plot_field_rgb(filepath): fits_im = fits.open(filepath.format('R')) data_r = fits_im[1].data fits_im = fits.open(filepath.format('G')) data_g = fits_im[1].data fits_im = fits.open(filepath.format('U')) data_u = fits_im[1].data im = make_lupton_rgb(data_r, data_g, data_u, stretch=1) plt.imshow(im, interpolation='nearest') plt.axis('off') plt.show()
def show_all_thumbnails(label='j022708p4901_00273', filters=['f775w', 'f814w', 'f098m', 'f105w', 'f110w', 'f125w', 'f140w', 'f160w'], scale_ab=21, close=True): """ Show individual filter and RGB thumbnails """ from astropy.visualization import make_lupton_rgb import matplotlib.pyplot as plt #from PIL import Image ims = {} for filter in filters: drz_files = glob.glob('{0}-{1}*_dr*sci.fits'.format(label, filter)) if len(drz_files) > 0: im = pyfits.open(drz_files[0]) ims[filter] = im slx, sly, filts, fig = auto_script.field_rgb(root=label, xsize=4, output_dpi=None, HOME_PATH=None, show_ir=False, pl=1, pf=1, scl=1, rgb_scl=[1, 1, 1], ds9=None, force_ir=False, filters=ims.keys(), add_labels=False, output_format='png', rgb_min=-0.01, xyslice=None, pure_sort=False, verbose=True, force_rgb=None, suffix='.rgb', scale_ab=scale_ab) if close: plt.close() #rgb = np.array(Image.open('{0}.rgb.png'.format(label))) rgb = plt.imread('{0}.rgb.png'.format(label)) NX = (len(filters)+1) fig = plt.figure(figsize=[1.5*NX, 1.5]) ax = fig.add_subplot(1, NX, NX) ax.imshow(rgb, origin='upper', interpolation='nearest') ax.text(0.5, 0.95, label, ha='center', va='top', transform=ax.transAxes, fontsize=7, bbox=dict(facecolor='w', edgecolor='None', alpha=0.5)) for i, filter in enumerate(filters): if filter in ims: zp_i = utils.calc_header_zeropoint(ims[filter], ext=0) scl = 10**(-0.4*(zp_i-5-scale_ab)) img = ims[filter][0].data*scl image = make_lupton_rgb(img, img, img, stretch=0.1, minimum=-0.01) ax = fig.add_subplot(1, NX, i+1) ax.imshow(255-image, origin='lower', interpolation='nearest') ax.text(0.5, 0.95, filter, ha='center', va='top', transform=ax.transAxes, fontsize=7, bbox=dict(facecolor='w', edgecolor='None', alpha=0.5)) for ax in fig.axes: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout(pad=0.1) fig.savefig('{0}.thumb.png'.format(label)) if close: plt.close()
def df_color_image(img_r, img_g, b=1.0, vmin=0.0, Q=10, stretch=25, filename=None, quiet=False): ''' Display tri-color image of Dragonfly based on ``g`` and ``r`` band images. The red channel uses ``img_r``, blue channel uses ``b * img_g``, and we make up the green channel to be ``(img_r + b * img_g) * 0.5``. Parameters: img_r (numpy 2-D array): image of r-band. Must have subtracted background. img_g (numpy 2-D array): image of g-band. Must have subtracted background. b (float): the proportion of ``img_g`` in blue channel, default is 1.0. vmin (float): the minimum value shown in tri-color image. Q (float): The asinh softening parameter. Smaller Q means higher contrast. stretch (float): The linear stretch of the image. Smaller value gives more low-SB details. save (bool): whether save the RGB image. filename (str): Write the resulting RGB image to a file (file type determined from extension). quiet (bool): whether showing the RGB image. Returns: None ''' from astropy.visualization import make_lupton_rgb import matplotlib.pyplot as plt import numpy as np red = img_r.copy() blue = img_g.copy() blue *= b green = (red + blue) * 0.5 rgb = make_lupton_rgb(red, green, blue, Q=Q, stretch=stretch, minimum=vmin, filename=filename) if not quiet: fig = plt.figure(figsize=(13, 13)) plt.imshow(rgb, origin='lower') plt.axis('off') plt.show() if filename is not None: print('# RGB image has been save at {}'.format(filename)) return rgb
def mergeButton(self, evt): global r_name global g_name global b_name r0 = fits.open(r_name)[0].data - 255 g0 = fits.open(g_name)[0].data - 255 b0 = fits.open(b_name)[0].data - 255 r=r0.astype(float) g=g0.astype(float) b=b0.astype(float) rgb = make_lupton_rgb(r, g, b, Q=10, stretch=0.1, filename=img_name)
def get_img_paths(nameG, nameR, nameI, stretch): image_fileG = f'{nameG}' image_dataG = fits.getdata(image_fileG, ext=0) image_fileR = f'{nameR}' image_dataR = fits.getdata(image_fileR, ext=0) image_fileI = f'{nameI}' image_dataI = fits.getdata(image_fileI, ext=0) image = make_lupton_rgb(image_dataI, image_dataR, image_dataG, stretch=stretch, Q=5) return image
def show_all_thumbnails(label='j022708p4901_00273', filters=['f775w','f814w','f098m','f105w','f110w','f125w','f140w','f160w'], scale_ab=21, close=True): """ Show individual filter and RGB thumbnails """ from astropy.visualization import make_lupton_rgb from PIL import Image ims = {} for filter in filters: drz_files = glob.glob('{0}-{1}*_dr*sci.fits'.format(label, filter)) if len(drz_files) > 0: im = pyfits.open(drz_files[0]) ims[filter] = im slx, sly, filts, fig = auto_script.field_rgb(root=label, xsize=4, output_dpi=None, HOME_PATH=None, show_ir=False, pl=1, pf=1, scl=1, rgb_scl=[1, 1, 1], ds9=None, force_ir=False, filters=ims.keys(), add_labels=False, output_format='png', rgb_min=-0.01, xyslice=None, pure_sort=False, verbose=True, force_rgb=None, suffix='.rgb', scale_ab=scale_ab) if close: plt.close() rgb = np.array(Image.open('{0}.rgb.png'.format(label))) NX = (len(filters)+1) fig = plt.figure(figsize=[1.5*NX,1.5]) ax = fig.add_subplot(1,NX,NX) ax.imshow(rgb, origin='upper', interpolation='nearest') ax.text(0.5, 0.95, label, ha='center', va='top', transform=ax.transAxes, fontsize=7, bbox=dict(facecolor='w', edgecolor='None', alpha=0.5)) for i, filter in enumerate(filters): if filter in ims: zp_i = utils.calc_header_zeropoint(ims[filter], ext=0) scl = 10**(-0.4*(zp_i-5-scale_ab)) img = ims[filter][0].data*scl image = make_lupton_rgb(img, img, img, stretch=0.1, minimum=-0.01) ax = fig.add_subplot(1,NX,i+1) ax.imshow(255-image, origin='lower', interpolation='nearest') ax.text(0.5, 0.95, filter, ha='center', va='top', transform=ax.transAxes, fontsize=7, bbox=dict(facecolor='w', edgecolor='None', alpha=0.5)) for ax in fig.axes: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout(pad=0.1) fig.savefig('{0}.thumb.png'.format(label)) if close: plt.close()
def luptonize(x): rgb_q = 15 rgb_stretch = 0.5 rgb_min = 0 if x.ndim == 3: x = make_lupton_rgb(x[:, :, 2], x[:, :, 1], x[:, :, 0], Q=rgb_q, stretch=rgb_stretch, minimum=rgb_min) elif x.ndim == 4: x = np.array([ make_lupton_rgb(xi[:, :, 2], xi[:, :, 1], xi[:, :, 0], Q=rgb_q, stretch=rgb_stretch, minimum=rgb_min) for xi in x ]) else: raise ValueError( f"Wrong number of dimensions! Gave {x.ndim}, need 3 or 4") return x
def mergeButton(self, evt): global r_name global g_name global b_name r0 = fits.open(r_name)[0].data - 255 g0 = fits.open(g_name)[0].data - 255 b0 = fits.open(b_name)[0].data - 255 r = r0.astype(float) g = g0.astype(float) b = b0.astype(float) rgb = make_lupton_rgb(r, g, b, Q=10, stretch=0.1, filename=img_name) plt.imshow(rgb, origin='lower') plt.waitforbuttonpress()
def make_rgb(self, kind, rgb_bands='irg', stretch=0.8, Q=8): if not hasattr(self, kind): logger.error(f'image of kind {kind} not found') rgb = None elif getattr(self, kind) is None: logger.error(f'image of kind {kind} not found') rgb = None else: image = getattr(self, kind) rgb = make_lupton_rgb(image[rgb_bands[0]], image[rgb_bands[1]], image[rgb_bands[2]], stretch=stretch, Q=Q) return rgb
def plot_image(self, idx): image = images[idx] new_image = np.empty((3, 45, 45)) new_image[0], new_image[1], new_image[2] = self.normalize_image(image) new_image = new_image.transpose(1, 2, 0) new_image = Image.fromarray(np.uint8(255 * new_image)).convert("RGB") #new_image = Image.fromarray(np.uint16(255*new_image)).convert("RGB") plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.imshow(np.asarray(new_image)) plt.axis('off') plt.subplot(1, 2, 2) rgb = make_lupton_rgb(image[2], image[1], image[0], Q=11., stretch=40.) plt.imshow(rgb, aspect='equal') plt.axis('off') plt.show()
def plt_RGB(filename, fieldnames_list, rad_or_ref, plot=True): ''' INPUT filename: - string , filepath to file fieldnames_list: - string list, contains 500m res and 250m reshape such that bands 1,4,3 for RGB i.e. 'EV_500_Aggr1km_RefSB' RETURN plots RGB picture of MODIS 02 product data ''' #make channels for RGB photo (index 01234 -> band 34567) image_blue = prepare_data(filename, fieldnames_list[0], rad_or_ref)[0, :, :] #band 3 from 500 meter res image_green = prepare_data(filename, fieldnames_list[0], rad_or_ref)[1, :, :] #band 4 from 500 meter res image_red = prepare_data(filename, fieldnames_list[1], rad_or_ref)[0, :, :] #band 1 from 250 meter res #force reflectance values to max out at 1.0/ normalize radiance if not rad_or_ref: np.place(image_red, image_red > 1.0, 1.0) #2d image array, condition, value np.place(image_blue, image_blue > 1.0, 1.0) np.place(image_green, image_green > 1.0, 1.0) image_RGB = np.dstack([image_red, image_green, image_blue]) else: #use astropy to normalize radiance values to usable pixel brightness from astropy.visualization import make_lupton_rgb image_RGB = make_lupton_rgb(image_red, image_green, image_blue, stretch=0.5) #plot or return image if plot: plt.imshow(image_RGB) plt.show() else: return image_RGB
def get_img(name, stretch): PATH_G = "/Users/schwarzam/Documents/cutouts" PATH_R = "/Users/schwarzam/Documents/cutouts" PATH_I = "/Users/schwarzam/Documents/cutouts" print(PATH_G) image_fileG = f'{PATH_G}/{name}_G.fits' image_dataG = fits.getdata(image_fileG, ext=0) image_fileR = f'{PATH_R}/{name}_R.fits' image_dataR = fits.getdata(image_fileR, ext=0) image_fileI = f'{PATH_I}/{name}_I.fits' image_dataI = fits.getdata(image_fileI, ext=0) image = make_lupton_rgb(image_dataI, image_dataR, image_dataG, stretch=stretch, Q=5) return image
def make_rgb_image(self, ra=None, dec=None, width=2.0, height=None, band='irg', stretch=5, Q=8, images=None): """ Make RGB image. Parameters ---------- ra, dec : float in degrees width, height : float in arcseconds band : string of characters HSC band names for in RGB order stretch : float Linear stretch of HSC RGB image Q : float The asinh softening parameter for HSC RGB image images : ndarray If not None, will make rgb image using these images Returns ------- rgb : ndarry The RGB image """ if images is None: images = self.fetch_hsc_cutout(ra, dec, width, height, band) rgb = make_lupton_rgb(images[:, :, 0], images[:, :, 1], images[:, :, 2], stretch=stretch, Q=Q) return rgb
def make_fir_maps(self): """ This function ... :return: """ # Inform the user log.info("Making RGB maps based on FIR images ...") # Set method name method_name = "TIR" # The RGB maps maps = dict() origins = dict() # Loop over the names for name in self.available_fir_rgb_names: # Get the filters fltr_a, fltr_b, fltr_c = get_filters(name, "-") # Load and uniformize to same resolution and unit of Jansky a, b, c = self.get_frames_for_filters(fltr_a, fltr_b, fltr_c, uniformize=True, unit="Jy") # Make the map rgb = make_lupton_rgb(a, b, c, Q=self.config.fir_softening, stretch=self.config.optical_stretch) rgb_image = Image.from_3d_array(rgb, name=name, wcs=a.wcs, names=["r", "g", "b"]) # Add the map maps[name] = rgb_image origins[name] = [fltr_a, fltr_b, fltr_c] # Set the maps self.maps[method_name] = maps # Set the origins self.origins[method_name] = origins
def plot_target_color(ra,dec,filepaths,name,image_size=10): from astropy.visualization import make_lupton_rgb #image_size = 10 # " cutout_b = cutout_image(filepaths["g"],ra,dec,image_size) cutout_g = cutout_image(filepaths["r"],ra,dec,image_size) cutout_r = cutout_image(filepaths["i"],ra,dec,image_size) fig = plt.figure() ax = fig.add_subplot(111) rgb = make_lupton_rgb(cutout_r.data, cutout_g.data, cutout_b.data,stretch=10) plt.imshow(rgb, origin='lower') add_compass(ax,color='white') add_scale_bar(ax,1,image_size) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.xticks([]) plt.yticks([]) plt.title(name+" (DES color image)") plt.savefig("coadd_color.png",bbox_inches='tight',dpi=100) plt.close()
def plot_rgb(filename): arr = np.load(filename) obj_id = filename.split('/')[-1].replace('.npy', '') field = obj_id.split('.')[1] print(obj_id) im = cv2.imread('../raw-data/train_images/{}.trilogy.png'.format(field)) cat = pd.read_csv('sloan_splus_matches.csv') obj = cat[cat['id'] == obj_id].iloc[0] x = obj['x'] #1341 y = 11000 - obj['y'] #11000-3955 d = 10 print(x, y) obj = im[y - d:y + d, x - d:x + d] ax1 = plt.subplot(121) ax1.axis('off') ax1.imshow(obj) im_lupton = make_lupton_rgb(arr[:, :, 7], arr[:, :, 5], arr[:, :, 0], stretch=1) #rgu ax2 = plt.subplot(122) ax2.imshow(im_lupton, interpolation='nearest', cmap=plt.cm.gray_r) ax2.axis('off') plt.show()
result = Observations.query_object('M83') selected_bands = result[(result['obs_collection'] == 'HST') & (result['instrument_name'] == 'WFC3/UVIS') & ((result['filters'] == 'F657N') | (result['filters'] == 'F487N') | (result['filters'] == 'F336W')) & (result['target_name'] == 'MESSIER-083')] prodlist = Observations.get_product_list(selected_bands) filtered_prodlist = Observations.filter_products(prodlist) downloaded = Observations.download_products(filtered_prodlist) blue = fits.open(downloaded['Local Path'][2]) red = fits.open(downloaded['Local Path'][5]) green = fits.open(downloaded['Local Path'][8]) target_header = red['SCI'].header green_repr, _ = reproject.reproject_interp(green['SCI'], target_header) blue_repr, _ = reproject.reproject_interp(blue['SCI'], target_header) rgb_img = make_lupton_rgb(ImageNormalize(vmin=0, vmax=1)(red['SCI'].data), ImageNormalize(vmin=0, vmax=0.3)(green_repr), ImageNormalize(vmin=0, vmax=1)(blue_repr), stretch=0.1, minimum=0, ) plt.imshow(rgb_img, origin='lower', interpolation='none')