def set_naxis_cb(self, w, n): idx = int(w.get_value()) - 1 self.logger.debug("naxis %d index is %d" % (n+1, idx+1)) image = AstroImage() image.set(path=self.path) try: hdu = self.fits_f[self.curhdu] data = hdu.data self.logger.debug("HDU #%d has naxis=%s" % ( self.curhdu+1, str(data.shape))) # invert index m = len(data.shape) - (n+1) self.naxispath[m] = idx self.logger.debug("m=%d naxispath=%s" % (m, str(self.naxispath))) image.load_hdu(hdu, naxispath=self.naxispath) self.fitsimage.set_image(image) self.logger.debug("NAXIS%d slice %d loaded." % (n+1, idx+1)) except Exception, e: errmsg = "Error loading NAXIS%d slice %d: %s" % ( n+1, idx+1, str(e)) self.logger.error(errmsg) self.fv.error(errmsg)
def set_naxis_cb(self, idx, n): self.logger.debug("naxis %d index is %d" % (n+1, idx+1)) image = AstroImage() image.set(path=self.path) try: hdu = self.fits_f[self.curhdu] data = hdu.data self.logger.debug("HDU #%d has naxis=%s" % ( self.curhdu, str(data.shape))) # invert index m = len(data.shape) - (n+1) self.naxispath[m] = idx self.logger.debug("m=%d naxispath=%s" % (m, str(self.naxispath))) self.logger.info("loading image from pyfits") start_time = time.time() image.load_hdu(hdu, fobj=self.fits_f, naxispath=self.naxispath) end_time = time.time() self.logger.info("loading image time %.3f sec" % (end_time - start_time)) start_time = end_time self.fitsimage.set_image(image) end_time = time.time() self.logger.debug("NAXIS%d slice %d loaded (%.3f sec)." % ( n+1, idx+1, end_time-start_time)) except Exception, e: errmsg = "Error loading NAXIS%d slice %d: %s" % ( n+1, idx+1, str(e)) self.logger.error(errmsg) self.fv.error(errmsg)
def load_fits(self, fitsorfn, numhdu=None, memmap=None): """ Load a FITS file into the viewer. Parameters ---------- fitsorfn : str or HDU Either a file name or an HDU (*not* an HDUList). If file name is given, WCS in primary header is automatically inherited. If a single HDU is given, WCS must be in the HDU header. numhdu : int or `None` Extension number of the desired HDU. If `None`, it is determined automatically. memmap : bool or `None` Memory mapping. If `None, it is determined automatically. """ if isinstance(fitsorfn, str): image = AstroImage(logger=self.logger, inherit_primary_header=True) image.load_file(fitsorfn, numhdu=numhdu, memmap=memmap) self._viewer.set_image(image) elif isinstance(fitsorfn, (fits.ImageHDU, fits.CompImageHDU, fits.PrimaryHDU)): self._viewer.load_hdu(fitsorfn)
def load(self, fitspath): # clear plotting area self.chartDev.fig.gca().cla() # load an image image = AstroImage(self.logger) image.load_file(fitspath) self.fitsimage.set_image(image) self.fitsimage.add_axes()
def load(self, fitspath): # clear plotting area self.chartDev.fig.gca().cla() # load an image image = AstroImage(self.logger) image.load_file(fitspath) self.fitsimage.set_image(image) self.fitsimage.add_axes()
def load(self, fitspath): self.logger.info("fplot is loading image.") try: # clear plotting area self.chartDev.fig.gca().cla() # load an image self.image = AstroImage(logger=self.logger) self.image.load_file(fitspath) self.fitsimage.set_image(self.image) self.fitsimage.add_axes() except Exception as e: self.logger.error(e)
def load(self, fitspath): self.etc.log("fplot is loading image.") try: # clear plotting area self.chartDev.fig.gca().cla() # load an image image = AstroImage() image.load_file(fitspath) self.fitsimage.set_image(image) self.fitsimage.add_axes() except Exception as e: self.etc.log(e)
def __init__(self, proxy, metadata=None, logger=None, #wcsclass=wcsClass, ioclass=ioClass, inherit_primary_header=False): self._proxy = proxy self._shape = tuple([]) self.id = None AstroImage.__init__(self, data_np=None, metadata=metadata, logger=logger, #wcsclass=wcsClass, ioclass=ioClass, inherit_primary_header=inherit_primary_header) self._data = None
def load_fits(self, fname="", extver=None): """Load fits image to current frame. Parameters ---------- fname: string, optional The name of the file to be loaded. You can specify the full extension in the name, such as filename_flt.fits[sci,1] or filename_flt.fits[1] extver: int, optional The extension to load (EXTVER in the header) Notes ----- Extname isn't used here, ginga wants the absolute extension number, not the version number associated with a name """ if fname is None: raise ValueError("No filename provided") try: shortname, extn, extv = util.verify_filename(fname) image = AstroImage(logger=self.logger) if extn is not None: raise ValueError("Extension name given, must specify " "the absolute extension you want") # prefer specified over filename if extver is None: extver = extv if (extv is None and extver is None): mef_file, nextend, first_image = util.check_valid(shortname) # if mef_file: # extver = 1 # MEF fits # else: # extver = 0 # simple fits extver = first_image # really ext number for first IMAGE with fits.open(shortname) as filedata: hdu = filedata[extver] image.load_hdu(hdu) except Exception as e: self.logger.error("Exception opening file: {0}".format(repr(e))) raise Exception(repr(e)) self._set_frameinfo(fname=shortname, hdu=hdu, image=image) self.ginga_view.set_image(image)
def _make_image(self, data_np, oldimage, name): """Generate new image object.""" image = AstroImage() image.set_data(data_np) image.update_keywords(oldimage.get_header()) image.set(name=name, path=None) return image
def load_fits(self, fname="", extver=None): """Load fits image to current frame. Parameters ---------- fname: string, optional The name of the file to be loaded. You can specify the full extension in the name, such as filename_flt.fits[sci,1] or filename_flt.fits[1] extver: int, optional The extension to load (EXTVER in the header) Notes ----- Extname isn't used here, ginga wants the absolute extension number, not the version number associated with a name """ if fname is None: raise ValueError("No filename provided") try: shortname, extn, extv = util.verify_filename(fname) image = AstroImage(logger=self.logger) if extn is not None: raise ValueError("Extension name given, must specify " "the absolute extension you want") # prefer specified over filename if extver is None: extver = extv if (extv is None and extver is None): mef = util.check_filetype(shortname) if mef: extver = 1 # MEF fits else: extver = 0 # simple fits with fits.open(shortname) as filedata: hdu = filedata[extver] image.load_hdu(hdu) except Exception as e: self.logger.error("Exception opening file: {0}".format(repr(e))) raise Exception(repr(e)) self._set_frameinfo(fname=shortname, hdu=hdu, image=image) self.ginga_view.set_image(image)
def auto_mosaic(self): """Create new mosaic using image list from Contents.""" astroimage_obj = AstroImage() self._imlist = {} self._recreate_fp = True self.treeview.clear() self.treeviewsel.clear() # Get image list from Contents, excluding other mosaics file_dict = self.list_plugin_obj.name_dict[self.chname] for bnch in six.itervalues(file_dict): if ((not isinstance(bnch, Bunch.Bunch)) or ('mosaic' in bnch.NAME.lower())): continue # Calculate image footprint, counter-clockwise from # bottom-left. Format is [[X1, Y1], ..., [X4, Y4]] imname = bnch.NAME impath = bnch.path datasrc = self.chinfo.datasrc if imname in datasrc: image = datasrc[imname] else: image = astroimage_obj image.load_file(impath) footprint = image.wcs.wcs.calc_footprint() # Astropy only? self._imlist[imname] = Bunch.Bunch(footprint=footprint, path=impath) if len(self._imlist) == 0: s = 'No images available for mosaic' self.logger.error(s) self.update_status(s) return True # Always start a new mosaic. # Remove duplicates in case an image have multiple extensions opened. images = list(set([bnch.path for bnch in six.itervalues(self._imlist)])) self.fv.nongui_do(self.fv.error_wrap, self.mosaic, images, new_mosaic=True) self.fitsimage.auto_levels() # Only allow this to happen once, otherwise footprint highlighting # gets confusing. self.w.create_mosaic.set_enabled(False) self.w.select_all.set_enabled(True) self.w.deselect_all.set_enabled(True) # Populate table listing. treedict = Bunch.caselessDict() for imname in self._imlist: treedict[imname] = Bunch.Bunch(IMAGE=imname) self.treeview.set_tree(treedict) return True
def load_fits(self, fileorhdu, viewer_name='Main Viewer'): """Load FITS image into the desired Ginga image viewer. Parameters ---------- fileorhdu File or HDU list object. viewer_name : str Name of Ginga image viewer to display to. Raises ------ KeyError Viewer name does not exist. ValueError Invalid file or HDU list object, or HDU list does not contain any image. """ if isinstance(fileorhdu, file): fileorhdu = fits.HDUList.fromfile(fileorhdu) if isiterable(fileorhdu): for hdui in fileorhdu: if hasattr(hdui, 'is_image') and hdui.is_image: hdu = hdui break else: raise ValueError( 'fileorhdu was iterable but did not contain any ' 'image HDUs') elif hasattr(fileorhdu, 'data') and hasattr(fileorhdu, 'header'): # quacks like an HDU - give it a shot hdu = fileorhdu else: raise ValueError('fileorhdu was not a fits file or HDU-ish thing') viewer = self.viewers[viewer_name] if viewer.fitsimage.get_image() is None: aim = AstroImage(logger=self.logger) aim.load_hdu(hdu) viewer.fitsimage.set_image(aim) else: viewer.fitsimage.get_image().load_hdu(hdu)
def load_fits(self, fileorhdu, viewer_name='Main Viewer'): """Load FITS image into the desired Ginga image viewer. Parameters ---------- fileorhdu File or HDU list object. viewer_name : str Name of Ginga image viewer to display to. Raises ------ KeyError Viewer name does not exist. ValueError Invalid file or HDU list object, or HDU list does not contain any image. """ if isinstance(fileorhdu, file): fileorhdu = fits.HDUList.fromfile(fileorhdu) if isiterable(fileorhdu): for hdui in fileorhdu: if hasattr(hdui, 'is_image') and hdui.is_image: hdu = hdui break else: raise ValueError( 'fileorhdu was iterable but did not contain any ' 'image HDUs') elif hasattr(fileorhdu, 'data') and hasattr(fileorhdu, 'header'): # quacks like an HDU - give it a shot hdu = fileorhdu else: raise ValueError('fileorhdu was not a fits file or HDU-ish thing') viewer = self.viewers[viewer_name] if viewer.fitsimage.get_image() is None: aim = AstroImage(logger=self.logger) aim.load_hdu(hdu) viewer.fitsimage.set_image(aim) else: viewer.fitsimage.get_image().load_hdu(hdu)
def load_fits(self, fitsfile): """ Load a FITS image into the viewer. """ image = AstroImage(logger=self.logger) image.load_file(fitsfile) self.viewer.set_image(image) panimage = AstroImage(logger=self.logger) panimage.load_file(fitsfile) self.panviewer.set_image(panimage)
def load_hdu(self, hdu, dstobj=None, **kwargs): typ = self.get_hdu_type(hdu) if typ == 'image': # <-- data is an image ahdr = AstroHeader() self.fromHDU(hdu, ahdr) metadata = dict(header=ahdr) data = hdu.read() if dstobj is None: dstobj = AstroImage(logger=self.logger) dstobj.load_data(data, metadata=metadata) else: dstobj.load_data(data, metadata=metadata) elif typ == 'table': # <-- data is a table raise FITSError( "FITS tables are not yet readable using ginga/fitsio") dstobj.io = self return dstobj
def _make_image(self, data_np, oldimage, name): """Generate new image object.""" image = AstroImage() image.set_data(data_np) image.update_keywords(oldimage.get_header()) image.set(name=name, path=None) return image
def fetch_cache_hdu(self, idx): with self._hdu_cache_lock: if self.hdu_cache.has_key(idx): self.logger.debug("HDU cache hit for index %d" % (idx)) image, dims = self.hdu_cache[idx] return dims, image else: hdu = self.fits_f[idx] path = self.path image = AstroImage() image.set(path=path) dims = list(hdu.data.shape) dims.reverse() image.load_hdu(hdu, fobj=self.fits_f) # TODO: when we've added cache size limiting #self.add_cache_hdu(idx, (image, dims)) return dims, image
def __init__( self, proxy, metadata=None, logger=None, #wcsclass=wcsClass, ioclass=ioClass, inherit_primary_header=False): self._proxy = proxy self._shape = tuple([]) self.id = None AstroImage.__init__( self, data_np=None, metadata=metadata, logger=logger, #wcsclass=wcsClass, ioclass=ioClass, inherit_primary_header=inherit_primary_header) self._data = None
def load_fits(self, fname="", extver=1, extname=None): """Load fits image to current frame. Parameters ---------- fname: string, optional The name of the file to be loaded. You can specify the full extension in the name, such as filename_flt.fits[sci,1] or filename_flt.fits[1] extver: int, optional The extension to load (EXTVER in the header) extname: string, optional The name (EXTNAME in the header) of the image to load Notes ----- """ if fname: # see if the image is MEF or Simple fname = os.path.abspath(fname) short = True try: mef = util.check_filetype(fname) if not mef: extver = 0 cstring = util.verify_filename(fname, getshort=short) image = AstroImage(logger=self.logger) with fits.open(cstring) as filedata: hdu = filedata[extver] image.load_hdu(hdu) except Exception as e: self.logger.error("Exception opening file: {0}".format(e)) raise IOError(str(e)) self._set_frameinfo(fname=fname, hdu=hdu, image=image) self.ginga_view.set_image(image) else: print("No filename provided")
def set_hdu(self, idx): self.logger.debug("Loading fits hdu #%d" % (idx)) image = AstroImage() image.set(path=self.path) try: hdu = self.fits_f[idx-1] dims = list(hdu.data.shape) dims.reverse() image.load_hdu(hdu) self.fitsimage.set_image(image) self.build_naxis(dims) self.curhdu = idx-1 self.logger.debug("hdu #%d loaded." % (idx)) except Exception, e: errmsg = "Error loading fits hdu #%d: %s" % ( idx, str(e)) self.logger.error(errmsg) self.fv.error(errmsg)
def load_fits(self, fname="", extver=1, extname=None): """Load fits image to current frame. Parameters ---------- fname: string, optional The name of the file to be loaded. You can specify the full extension in the name, such as filename_flt.fits[sci,1] or filename_flt.fits[1] extver: int, optional The extension to load (EXTVER in the header) extname: string, optional The name (EXTNAME in the header) of the image to load Notes ----- """ if fname: # see if the image is MEF or Simple fname = os.path.abspath(fname) short = True try: mef = util.check_filetype(fname) if not mef: extver = 0 cstring = util.verify_filename(fname, getshort=short) image = AstroImage(logger=self.logger) with fits.open(cstring) as filedata: hdu = filedata[extver] image.load_hdu(hdu) except Exception as e: self.logger.error("Exception opening file: {0}".format(e)) raise IOError(str(e)) self._set_frameinfo(fname=fname, hdu=hdu, image=image) self.ginga_view.set_image(image) else: print("No filename provided")
def load_hdu(self, hdu, dstobj=None, **kwargs): typ = self.get_hdu_type(hdu) if typ == 'image': if dstobj is None: dstobj = AstroImage(logger=self.logger) dstobj.load_hdu(hdu, **kwargs) else: # TODO: migrate code from AstroImage to here dstobj.load_hdu(hdu, **kwargs) elif typ == 'table': # <-- data may be a table if hdu.name == 'ASDF': if dstobj is not None: raise ValueError( "It is not supported to load ASDF HDU with dstobj != None" ) self.logger.debug('Attempting to load {} extension from ' 'FITS'.format(hdu.name)) from ginga.util.io import io_asdf opener = io_asdf.ASDFFileHandler(self.logger) return opener.load_asdf_hdu_in_fits(self.fits_f, hdu, **kwargs) if dstobj is None: dstobj = AstroTable(logger=self.logger) self.logger.debug('Attempting to load table from FITS') # TODO: migrate code from AstroTable to here dstobj.load_hdu(hdu, **kwargs) else: raise FITSError("I don't know how to read this HDU") dstobj.io = self return dstobj
def quick_reduce(self): image = self.fitsimage.get_image() if image is None: # Nothing to do return path = image.get('path', None) if path is None: return self.q_image.onscreen_message("Working ...") try: #img_data = image.get_data().astype(np.float32) with fits.open(path, 'readonly') as in_f: n = len(in_f) - 1 img_data = in_f[n].data.astype(np.float32) if self.sb_hdu1: # get HDU 1 from the file and subtract it if path != self.hdu1_path: # if not cached then we have to re-fetch it self.hdu1_path = path self.hdu1_data = in_f[1].data sbr_data = img_data - self.hdu1_data else: sbr_data = img_data # create a new image metadata = dict(header=image.get_header()) new_img = AstroImage(data_np=sbr_data, metadata=metadata, logger=self.logger) # no thumbnails presently new_img.set(nothumb=True, path=None, name=image.get('name')) self.q_image.set_image(new_img) finally: self.q_image.onscreen_message(None)
def set_naxis_cb(self, idx, n): self.logger.debug("naxis %d index is %d" % (n + 1, idx + 1)) image = AstroImage() image.set(path=self.path) try: hdu = self.fits_f[self.curhdu] data = hdu.data self.logger.debug("HDU #%d has naxis=%s" % (self.curhdu, str(data.shape))) # invert index m = len(data.shape) - (n + 1) self.naxispath[m] = idx self.logger.debug("m=%d naxispath=%s" % (m, str(self.naxispath))) self.logger.info("loading image from pyfits") start_time = time.time() image.load_hdu(hdu, fobj=self.fits_f, naxispath=self.naxispath) end_time = time.time() self.logger.info("loading image time %.3f sec" % (end_time - start_time)) start_time = end_time self.fitsimage.set_image(image) end_time = time.time() self.logger.debug("NAXIS%d slice %d loaded (%.3f sec)." % (n + 1, idx + 1, end_time - start_time)) except Exception, e: errmsg = "Error loading NAXIS%d slice %d: %s" % (n + 1, idx + 1, str(e)) self.logger.error(errmsg) self.fv.error(errmsg)
def set_naxis_cb(self, w, n): idx = int(w.get_value()) - 1 self.logger.debug("naxis %d index is %d" % (n + 1, idx + 1)) image = AstroImage() image.set(path=self.path) try: hdu = self.fits_f[self.curhdu] data = hdu.data self.logger.debug("HDU #%d has naxis=%s" % (self.curhdu + 1, str(data.shape))) # invert index m = len(data.shape) - (n + 1) self.naxispath[m] = idx self.logger.debug("m=%d naxispath=%s" % (m, str(self.naxispath))) image.load_hdu(hdu, naxispath=self.naxispath) self.fitsimage.set_image(image) self.logger.debug("NAXIS%d slice %d loaded." % (n + 1, idx + 1)) except Exception, e: errmsg = "Error loading NAXIS%d slice %d: %s" % (n + 1, idx + 1, str(e)) self.logger.error(errmsg) self.fv.error(errmsg)
def convert(filepath, outfilepath): """Convert FITS image to PDF.""" logger = logging.getLogger("example1") logger.setLevel(logging.INFO) fmt = logging.Formatter(STD_FORMAT) stderrHdlr = logging.StreamHandler() stderrHdlr.setFormatter(fmt) logger.addHandler(stderrHdlr) fi = ImageViewCairo(logger) fi.configure(500, 1000) # Load fits file image = AstroImage(logger=logger) image.load_file(filepath) # Make any adjustments to the image that we want fi.set_bg(1.0, 1.0, 1.0) fi.set_image(image) fi.auto_levels() fi.zoom_fit() fi.center_image() ht_pts = 11.0 / point_in wd_pts = 8.5 / point_in off_x, off_y = 0, 0 out_f = open(outfilepath, 'w') surface = cairo.PDFSurface(out_f, wd_pts, ht_pts) # set pixels per inch surface.set_fallback_resolution(300, 300) surface.set_device_offset(off_x, off_y) try: fi.save_image_as_surface(surface) surface.show_page() surface.flush() surface.finish() finally: out_f.close()
def load_nddata(self, nddata): """ Load an ``NDData`` object into the viewer. .. todo:: Add flag/masking support, etc. Parameters ---------- nddata : `~astropy.nddata.NDData` ``NDData`` with image data and WCS. """ from ginga.util.wcsmod.wcs_astropy import AstropyWCS image = AstroImage(logger=self.logger) image.set_data(nddata.data) _wcs = AstropyWCS(self.logger) if nddata.wcs: _wcs.load_header(nddata.wcs.to_header()) try: image.set_wcs(_wcs) except Exception as e: print('Unable to set WCS from NDData: {}'.format(str(e))) self._viewer.set_image(image)
def _mtv(self, image, mask=None, wcs=None, title=""): """Display an Image and/or Mask on a ginga display""" self._erase() self._canvas.delete_all_objects() Aimage = AstroImage(inherit_primary_header=True) Aimage.set_data(image.getArray()) self._gingaViewer.set_image(Aimage) if wcs is not None: _wcs = AstropyWCS(self.logger) Aimage.lsst_wcs = WcsAdaptorForGinga(wcs) _wcs.pixtoradec = Aimage.lsst_wcs.pixtoradec _wcs.pixtosystem = Aimage.lsst_wcs.pixtosystem _wcs.radectopix = Aimage.lsst_wcs.radectopix Aimage.set_wcs(_wcs) Aimage.wcs.wcs = Aimage.lsst_wcs if mask: maskColorFromName = { 'BAD': 'red', 'SAT': 'green', 'INTRP': 'green', 'CR': 'magenta', 'EDGE': 'yellow', 'DETECTED': 'blue', 'DETECTED_NEGATIVE': 'cyan', 'SUSPECT': 'yellow', 'NO_DATA': 'orange', 'CROSSTALK': None, 'UNMASKEDNAN': None } maskDict = dict() for plane, bit in mask.getMaskPlaneDict().items(): color = maskColorFromName.get(plane, None) if color: maskDict[1 << bit] = color # CZW: This value of 0.9 is pretty thick for the alpha. self.overlay_mask(mask, maskDict, self._maskTransparencyAlpha) self._flush()
def load_file(self, filepath): p = Path(filepath.strip('file:')) print(f"Loading file: {p}") kd = fits_reader(p) image = AstroImage(data_np=kd.iraf_mosaic(), logger=self.logger) image.wcs.load_header(kd.headers[0]) # image = load_data(filepath, logger=self.logger) w = image.wcs.wcs fp = w.calc_footprint() self.catalog_coordinate = c.SkyCoord( np.mean(fp[:, 0]) * u.deg, np.mean(fp[:, 1]) * u.deg) self.catalog_radius = 0.1 for radec in fp: corner = c.SkyCoord(radec[0] * u.deg, radec[1] * u.deg) sep = self.catalog_coordinate.separation(corner) if sep.deg > self.catalog_radius: self.catalog_radius = sep.deg self.fitsimage.set_image(image) self.setWindowTitle(filepath) self.get_gaia()
def fetch_cache_hdu(self, idx): with self._hdu_cache_lock: if self.hdu_cache.has_key(idx): self.logger.debug("HDU cache hit for index %d" % (idx)) image, dims = self.hdu_cache[idx] return dims, image else: hdu = self.fits_f[idx] path = self.path image = AstroImage() image.set(path=path) dims = list(hdu.data.shape) dims.reverse() image.load_hdu(hdu, fobj=self.fits_f) # TODO: when we've added cache size limiting #self.add_cache_hdu(idx, (image, dims)) return dims, image
def set_hdu(self, idx): self.logger.debug("Loading fits hdu #%d" % (idx)) image = AstroImage() image.set(path=self.path) try: hdu = self.fits_f[idx - 1] dims = list(hdu.data.shape) dims.reverse() image.load_hdu(hdu) self.fitsimage.set_image(image) self.build_naxis(dims) self.curhdu = idx - 1 self.logger.debug("hdu #%d loaded." % (idx)) except Exception, e: errmsg = "Error loading fits hdu #%d: %s" % (idx, str(e)) self.logger.error(errmsg) self.fv.error(errmsg)
def load(self, filepath): image = AstroImage(logger=self.logger) image.load_file(filepath) self.set_image(image)
# tell it about the figure fi = ImageViewCanvas(logger) fi.enable_autocuts('on') fi.set_autocut_params('zscale') #fi.set_cmap(cmap.get_cmap('rainbow3')) fi.set_figure(fig) # enable all interactive ginga features fi.get_bindings().enable_all(True) # load an image if len(sys.argv) < 2: print("Please provide a FITS file on the command line") sys.exit(1) image = AstroImage(logger) image.load_file(sys.argv[1]) fi.set_image(image) #fi.rotate(45) # plot some example graphics via matplotlib # Note adding axis from ginga (mpl backend) object ax = fi.add_axes() ax.hold(True) wd, ht = image.get_size() # plot a line l = ax.plot((wd*0.33, wd*0.75), (ht*0.5, ht*0.75), 'go-', c="g",
def load_file(path): image = AstroImage(logger) image.load_file(path) viewer.set_image(image)
class FitsPlot: def __init__(self, chartDev, logger): self.logger = logger self.chartDev = chartDev self.fig = self.chartDev.fig self.logger.info("fplot is doing something.") self.images = [] try: # create a ginga object and tell it about the figure self.chartDev.fig.clf() fi = ImageViewCanvas(self.logger) fi.enable_autocuts('on') fi.set_autocut_params('zscale') fi.set_figure(self.chartDev.fig) fi.ui_setActive(True) self.fitsimage = fi setup_Qt(chartDev, fi) # enable all interactive features fi.get_bindings().enable_all(True) self.fitsimage = fi except Exception as e: self.logger.error(e) def get_xy(self): return self.fitsimage.get_last_data_xy() def get_data_size(self): return self.fitsimage.get_data_size() def get_data(self, point=True): try: if point: x, y = self.get_xy() w, h = self.get_data_size() if 0 < x < w and 0 < y < h: return self.fitsimage.get_data(int(x), int(y)) else: return None else: return self.fitsimage.get_data() except Exception as e: self.logger.error(e) def get_image_data(self): return self.fitsimage.get_data() def clear(self): try: self.fitsimage.clear() except Exception as e: self.logger.error(e) def load(self, fitspath): self.logger.info("fplot is loading image.") try: # clear plotting area self.chartDev.fig.gca().cla() # load an image self.image = AstroImage(logger=self.logger) self.image.load_file(fitspath) self.fitsimage.set_image(self.image) self.fitsimage.add_axes() except Exception as e: self.logger.error(e) def load_array(self, fitspath): self.chartDev.fig.gca().cla() self.images = [] for file in fitspath: self.images.append(AstroImage()) self.images[-1].load_file(file) def show_from_all(self, number): if self.images is not None: if 0 <= number < len(self.images): self.fitsimage.set_image(self.images[number]) self.fitsimage.add_axes()
def load_array(self, fitspath): self.chartDev.fig.gca().cla() self.images = [] for file in fitspath: self.images.append(AstroImage()) self.images[-1].load_file(file)
def load(self, filepath): image = AstroImage(logger=self.logger) image.load_file(filepath) self.set_image(image)
def load_fits(self, fname=None, extver=None): """Load fits image to current frame. Parameters ---------- fname: string, FITS HDU The name of the file to be loaded. You can specify the full extension in the name, such as filename_flt.fits[sci,1] or filename_flt.fits[1] extver: int, optional The extension to load (EXTVER in the header) Notes ----- Extname isn't used here, ginga wants the absolute extension number, not the version number associated with a name """ if fname is None: raise ValueError("No filename or HDU provided") image = AstroImage(logger=self.logger) if isinstance(fname, (fits.hdu.image.PrimaryHDU, fits.hdu.image.ImageHDU)): # Simple fits, data + header shortname = fname extn = None if extver is None: extv = None extver = 0 if extver: hdu = shortname[extver] else: hdu = shortname elif isinstance(fname, fits.hdu.hdulist.HDUList): shortname = fname extn = None extv = extver if extver: hdu = shortname[extver] else: hdu = shortname elif isinstance(fname, str): shortname, extn, extv = util.verify_filename(fname) if extn is not None: raise ValueError("Extension name given, must " "specify the absolute extension you want") # prefer the keyword value over the extension in the name if extver is None: extver = extv # safety for a valid imexam file if ((extv is None) and (extver is None)): mef_file, nextend, first_image = util.check_valid(shortname) extver = first_image # the extension of the first IMAGE else: raise TypeError("Expected FITS data as input") try: if isinstance(shortname, str): with fits.open(shortname) as filedata: hdu = filedata[extver] image.load_hdu(hdu) else: image.load_hdu(hdu) self._set_frameinfo(fname=shortname, hdu=hdu, image=image) self.ginga_view.set_image(image) except Exception as e: self.logger.error(f"Exception loading image: {repr(e)}") raise Exception(repr(e))
class CubeWidget(ImageWidget): def __init__(self, hdu=None, im=None, wcs=None, show_rainbow=True, *args, **kwargs): super().__init__(*args, **kwargs) # self._4d_idx = 0 # Lock 4th dim to this for now if hdu is not None: self.im = hdu.data self.wcs = WCS(hdu.header) elif im is not None: self.im = im self.wcs = wcs else: print("Provide a 3D HDU or image and wcs object") self.nddata = NDData(self.im, wcs=self.wcs) self.load_nddata(self.nddata, n=0) # get wave info: self.dwave = self.wcs.wcs.cdelt[2] self.wave_start = self.wcs.wcs.crval[2] self.nwave = np.shape(self.im)[0] self.wave_end = self.wave_start + self.nwave * self.dwave self.show_rainbow = show_rainbow #zscale = ZScaleInterval(contrast=0.3, krej=2.5) #vmin, vmax = zscale.get_limits(values=self.im) self.cuts = 'stddev' self.wave_widget = widgets.IntSlider( min=self.wave_start, max=self.wave_end, step=self.dwave, value=4540, continuous_update=False, ) self.slider = widgets.interactive(self.show_slice, wave=self.wave_widget) self.animate_button = widgets.Button( description="Scan Cube", disabled=False, button_style="success", tooltip="Click this to scan in wavelength dimension", ) # For line profile plot self._cur_islice = None self._cur_ix = None self._cur_iy = None self.line_out = widgets.Output() self.line_plot = None self.plot_xlabel = "Wavelength (A)" self.plot_ylabel = "Flux Density" # (10^-17 erg cm-2 s-1 arcsec-2" if self.show_rainbow: self.set_rainbow() # If plot shows, rerun cell to hide it. ax = plt.gca() self.line_plot = ax self.scan = widgets.Play( value=self.wave_start, min=self.wave_start, max=self.wave_end, step=self.dwave, # interval=500, description="Scan Cube", disabled=False, ) widgets.jslink((self.scan, "value"), (self.wave_widget, "value")) left_panel = widgets.VBox( [widgets.HBox([self.wave_widget, self.scan]), self]) display(widgets.HBox([left_panel, self.line_out])) def load_nddata(self, nddata, n=0): # update this for wavelength later self.image = AstroImage() self.image.load_nddata(nddata, naxispath=[n]) self._viewer.set_image(self.image) def _mouse_click_cb(self, viewer, event, data_x, data_y): self._cur_ix = int(round(data_x)) self._cur_iy = int(round(data_y)) self.plot_line_profile() # Ensure only active marker is shown self.reset_markers() if self._cur_ix is not None: mrk_tab = Table(names=["x", "y"]) mrk_tab.add_row([self._cur_ix, self._cur_iy]) self.marker = {"color": "red", "radius": 1, "type": "circle"} self.add_markers(mrk_tab) # self.reset_markers() super()._mouse_click_cb(viewer, event, data_x, data_y) def plot_line_profile(self): if self.line_plot is None or self._cur_ix is None or self._cur_iy is None: return # image = self._viewer.get_image() if self.image is None: return with self.line_out: mddata = self.image.get_mddata() self.line_plot.clear() self.wavelengths = (self.wave_start + self.dwave * np.arange(self.nwave)) try: self.spectrum = mddata[:, self._cur_iy, self._cur_ix] except IndexError: return self.line_plot.plot( self.wavelengths, self.spectrum, color="black", linewidth=1.2, ) if self._cur_islice is not None: y = mddata[self._cur_islice, self._cur_iy, self._cur_ix] x = self.wave_start + self.dwave * self._cur_islice self.line_plot.axvline(x=x, color="r", linewidth=1) # self.line_plot.set_title(f'X={self._cur_ix + 1} Y={self._cur_iy + 1}') self.line_plot.set_xlabel(self.plot_xlabel) self.line_plot.set_ylabel(self.plot_ylabel) self.line_plot.set_xlim(self.wave_start, self.wave_end) if self.show_rainbow: y2 = np.linspace(np.min(self.spectrum), np.max(self.spectrum), 100) X, Y = np.meshgrid(self.wavelengths, y2) extent = (self.wave_start, self.wave_end, np.min(y2), np.max(y2)) self.line_plot.imshow(X, clim=self.clim, extent=extent, cmap=self.spectralmap, aspect='auto') self.line_plot.fill_between(self.wavelengths, self.spectrum, np.max(y2), color='w') clear_output(wait=True) display(self.line_plot.figure) def set_rainbow(self): self.clim = (self.wave_start, self.wave_end) norm = plt.Normalize(*self.clim) wl = np.arange(self.clim[0], self.clim[1] + 1, 2) colorlist = list(zip(norm(wl), [wavelength_to_rgb(w) for w in wl])) self.spectralmap = matplotlib.colors.LinearSegmentedColormap.from_list( "spectrum", colorlist) def image_show_slice(self, n): # image = self._viewer.get_image() self.image.set_naxispath([n]) self._viewer.redraw(whence=0) self._cur_islice = n def show_slice(self, wave): n = int((wave - self.wave_start) / self.dwave) self.image_show_slice(n - 1) self.plot_line_profile()
def load_fits(self, fname=None, extver=None): """Load fits image to current frame. Parameters ---------- fname: string, FITS HDU The name of the file to be loaded. You can specify the full extension in the name, such as filename_flt.fits[sci,1] or filename_flt.fits[1] extver: int, optional The extension to load (EXTVER in the header) Notes ----- Extname isn't used here, ginga wants the absolute extension number, not the version number associated with a name """ if fname is None: raise ValueError("No filename or HDU provided") if isinstance(fname, (fits.hdu.image.PrimaryHDU, fits.hdu.image.ImageHDU)): # Simple fits, data + header shortname = fname extn = None if extver is None: extv = None extver = 0 elif isinstance(fname, fits.hdu.hdulist.HDUList): shortname = fname extn = None extv = extver elif isinstance(fname, str): shortname, extn, extv = util.verify_filename(fname) if extn is not None: raise ValueError("Extension name given, must " "specify the absolute extension you want") # prefer the keyword value over the extension in the name if extver is None: extver = extv else: raise TypeError("Expected FITS data as input") # safety for a valid imexam file if ((extv is None) and (extver is None)): mef_file, nextend, first_image = util.check_valid(shortname) extver = first_image # the extension of the first IMAGE image = AstroImage(logger=self.logger) try: if isinstance(fname, str): with fits.open(shortname) as filedata: hdu = filedata[extver] image.load_hdu(hdu) else: if extver: hdu = shortname[extver] else: hdu = shortname image.load_hdu(hdu) self._set_frameinfo(fname=shortname, hdu=hdu, image=image) self.ginga_view.set_image(image) except Exception as e: self.logger.error("Exception loading image: {0}".format(repr(e))) raise Exception(repr(e))
# tell it about the figure fi = ImageViewCanvas(logger=logger) fi.enable_autocuts('on') fi.set_autocut_params('zscale') #fi.set_cmap(cmap.get_cmap('rainbow3')) fi.set_figure(fig) # enable all interactive ginga features fi.get_bindings().enable_all(True) # load an image if len(sys.argv) < 2: print("Please provide a FITS file on the command line") sys.exit(1) image = AstroImage(logger=logger) image.load_file(sys.argv[1]) fi.set_image(image) #fi.rotate(45) # plot some example graphics via matplotlib # Note adding axis from ginga (mpl backend) object ax = fi.add_axes() ax.hold(True) wd, ht = image.get_size() # plot a line l = ax.plot((wd * 0.33, wd * 0.75), (ht * 0.5, ht * 0.75), 'go-',
def load_file(path): image = AstroImage(logger) image.load_file(path) viewer.set_image(image)
def load(self, fitspath): # load an image image = AstroImage(logger=self.logger) image.load_file(fitspath) self.fitsimage.set_image(image)
def load(self, fitspath): # load an image image = AstroImage(self.logger) image.load_file(fitspath) self.fitsimage.set_image(image)