def load(self, filename): """Load a mask from an image file. :param str filename: File name from which to load the mask :raise Exception: An exception in case of failure :raise RuntimeWarning: In case the mask was applied but with some import changes to notice """ _, extension = os.path.splitext(filename) extension = extension.lower()[1:] if extension == "npy": try: mask = numpy.load(filename) except IOError: _logger.error("Can't load filename '%s'", filename) _logger.debug("Backtrace", exc_info=True) raise RuntimeError('File "%s" is not a numpy file.', filename) elif extension in ["tif", "tiff"]: try: image = TiffIO(filename, mode="r") mask = image.getImage(0) except Exception as e: _logger.error("Can't load filename %s", filename) _logger.debug("Backtrace", exc_info=True) raise e elif extension == "edf": try: mask = EdfFile(filename, access='r').GetData(0) except Exception as e: _logger.error("Can't load filename %s", filename) _logger.debug("Backtrace", exc_info=True) raise e elif extension == "msk": if fabio is None: raise ImportError( "Fit2d mask files can't be read: Fabio module is not available" ) try: mask = fabio.open(filename).data except Exception as e: _logger.error("Can't load fit2d mask file") _logger.debug("Backtrace", exc_info=True) raise e elif ("." + extension) in NEXUS_HDF5_EXT: mask = self._loadFromHdf5(filename) if mask is None: raise IOError("Could not load mask from HDF5 dataset") else: msg = "Extension '%s' is not supported." raise RuntimeError(msg % extension) effectiveMaskShape = self.setSelectionMask(mask, copy=False) if effectiveMaskShape is None: return if mask.shape != effectiveMaskShape: msg = 'Mask was resized from %s to %s' msg = msg % (str(mask.shape), str(effectiveMaskShape)) raise RuntimeWarning(msg)
def save(self, filename, kind): """Save current mask in a file :param str filename: The file where to save to mask :param str kind: The kind of file to save in 'edf', 'tif', 'npy', 'h5' or 'msk' (if FabIO is installed) :raise Exception: Raised if the file writing fail """ if kind == 'edf': edfFile = EdfFile(filename, access="w+") edfFile.WriteImage({}, self.getMask(copy=False), Append=0) elif kind == 'tif': tiffFile = TiffIO(filename, mode='w') tiffFile.writeImage(self.getMask(copy=False), software='silx') elif kind == 'npy': try: numpy.save(filename, self.getMask(copy=False)) except IOError: raise RuntimeError("Mask file can't be written") elif ("." + kind) in NEXUS_HDF5_EXT: self._saveToHdf5(filename, self.getMask(copy=False)) elif kind == 'msk': if fabio is None: raise ImportError( "Fit2d mask files can't be written: Fabio module is not available" ) try: data = self.getMask(copy=False) image = fabio.fabioimage.FabioImage(data=data) image = image.convert(fabio.fit2dmaskimage.Fit2dMaskImage) image.save(filename) except Exception: _logger.debug("Backtrace", exc_info=True) raise RuntimeError("Mask file can't be written") else: raise ValueError("Format '%s' is not supported" % kind)
def _saveImage(self, plot, filename, nameFilter): """Save an image from the plot. :param str filename: The name of the file to write :param str nameFilter: The selected name filter :return: False if format is not supported or save failed, True otherwise. """ if nameFilter not in self.DEFAULT_IMAGE_FILTERS: return False image = plot.getActiveImage() if image is None: qt.QMessageBox.warning( plot, "No Data", "No image to be saved") return False data = image.getData(copy=False) # TODO Use silx.io for writing files if nameFilter == self.IMAGE_FILTER_EDF: edfFile = EdfFile(filename, access="w+") edfFile.WriteImage({}, data, Append=0) return True elif nameFilter == self.IMAGE_FILTER_TIFF: tiffFile = TiffIO(filename, mode='w') tiffFile.writeImage(data, software='silx') return True elif nameFilter == self.IMAGE_FILTER_NUMPY: try: numpy.save(filename, data) except IOError: self._errorMessage('Save failed\n') return False return True elif nameFilter == self.IMAGE_FILTER_NXDATA: entryPath = self._selectWriteableOutputGroup(filename) if entryPath is None: return False xorigin, yorigin = image.getOrigin() xscale, yscale = image.getScale() xaxis = xorigin + xscale * numpy.arange(data.shape[1]) yaxis = yorigin + yscale * numpy.arange(data.shape[0]) xlabel, ylabel = self._getAxesLabels(image) interpretation = "image" if len(data.shape) == 2 else "rgba-image" return save_NXdata(filename, nxentry_name=entryPath, signal=data, axes=[yaxis, xaxis], signal_name="image", axes_names=["y", "x"], axes_long_names=[ylabel, xlabel], title=plot.getGraphTitle(), interpretation=interpretation) elif nameFilter in (self.IMAGE_FILTER_ASCII, self.IMAGE_FILTER_CSV_COMMA, self.IMAGE_FILTER_CSV_SEMICOLON, self.IMAGE_FILTER_CSV_TAB): csvdelim, filetype = { self.IMAGE_FILTER_ASCII: (' ', 'txt'), self.IMAGE_FILTER_CSV_COMMA: (',', 'csv'), self.IMAGE_FILTER_CSV_SEMICOLON: (';', 'csv'), self.IMAGE_FILTER_CSV_TAB: ('\t', 'csv'), }[nameFilter] height, width = data.shape rows, cols = numpy.mgrid[0:height, 0:width] try: save1D(filename, rows.ravel(), (cols.ravel(), data.ravel()), filetype=filetype, xlabel='row', ylabels=['column', 'value'], csvdelim=csvdelim, autoheader=True) except IOError: self._errorMessage('Save failed\n') return False return True elif nameFilter == self.IMAGE_FILTER_RGB_PNG: # Get displayed image rgbaImage = image.getRgbaImageData(copy=False) # Convert RGB QImage qimage = convertArrayToQImage(rgbaImage[:, :, :3]) if qimage.save(filename, 'PNG'): return True else: _logger.error('Failed to save image as %s', filename) qt.QMessageBox.critical( self.parent(), 'Save image as', 'Failed to save image') return False
def main(argv=None): """Display an image from a file in an :class:`ImageView` widget. :param argv: list of command line arguments or None (the default) to use sys.argv. :type argv: list of str :return: Exit status code :rtype: int :raises IOError: if no image can be loaded from the file """ import argparse import os.path from silx.third_party.EdfFile import EdfFile # Command-line arguments parser = argparse.ArgumentParser( description='Browse the images of an EDF file.') parser.add_argument( '-o', '--origin', nargs=2, type=float, default=(0., 0.), help="""Coordinates of the origin of the image: (x, y). Default: 0., 0.""") parser.add_argument( '-s', '--scale', nargs=2, type=float, default=(1., 1.), help="""Scale factors applied to the image: (sx, sy). Default: 1., 1.""") parser.add_argument( '-l', '--log', action="store_true", help="Use logarithm normalization for colormap, default: Linear.") parser.add_argument( 'filename', nargs='?', help='EDF filename of the image to open') args = parser.parse_args(args=argv) # Open the input file if not args.filename: logger.warning('No image file provided, displaying dummy data') edfFile = None data = numpy.arange(1024 * 1024.).reshape(1024, 1024) nbFrames = 1 else: if not os.path.isfile(args.filename): raise IOError('No input file: %s' % args.filename) else: edfFile = EdfFile(args.filename) data = edfFile.GetData(0) nbFrames = edfFile.GetNumImages() if nbFrames == 0: raise IOError( 'Cannot read image(s) from file: %s' % args.filename) global app # QApplication must be global to avoid seg fault on quit app = qt.QApplication([]) sys.excepthook = qt.exceptionHandler mainWindow = ImageViewMainWindow() mainWindow.setAttribute(qt.Qt.WA_DeleteOnClose) if args.log: # Use log normalization by default colormap = mainWindow.getDefaultColormap() colormap['normalization'] = 'log' mainWindow.setColormap(colormap) mainWindow.setImage(data, origin=args.origin, scale=args.scale) if edfFile is not None and nbFrames > 1: # Add a toolbar for multi-frame EDF support multiFrameToolbar = qt.QToolBar('Multi-frame') multiFrameToolbar.addWidget(qt.QLabel( 'Frame [0-%d]:' % (nbFrames - 1))) spinBox = qt.QSpinBox() spinBox.setRange(0, nbFrames - 1) def updateImage(index): mainWindow.setImage(edfFile.GetData(index), origin=args.origin, scale=args.scale, reset=False) spinBox.valueChanged[int].connect(updateImage) multiFrameToolbar.addWidget(spinBox) mainWindow.addToolBar(multiFrameToolbar) mainWindow.show() mainWindow.setFocus(qt.Qt.OtherFocusReason) return app.exec_()
def _saveImage(self, filename, nameFilter): """Save an image from the plot. :param str filename: The name of the file to write :param str nameFilter: The selected name filter :return: False if format is not supported or save failed, True otherwise. """ if nameFilter not in self.IMAGE_FILTERS: return False image = self.plot.getActiveImage() if image is None: qt.QMessageBox.warning(self.plot, "No Data", "No image to be saved") return False data = image.getData(copy=False) # TODO Use silx.io for writing files if nameFilter == self.IMAGE_FILTER_EDF: edfFile = EdfFile(filename, access="w+") edfFile.WriteImage({}, data, Append=0) return True elif nameFilter == self.IMAGE_FILTER_TIFF: tiffFile = TiffIO(filename, mode='w') tiffFile.writeImage(data, software='silx') return True elif nameFilter == self.IMAGE_FILTER_NUMPY: try: numpy.save(filename, data) except IOError: self._errorMessage('Save failed\n') return False return True elif nameFilter in (self.IMAGE_FILTER_ASCII, self.IMAGE_FILTER_CSV_COMMA, self.IMAGE_FILTER_CSV_SEMICOLON, self.IMAGE_FILTER_CSV_TAB): csvdelim, filetype = { self.IMAGE_FILTER_ASCII: (' ', 'txt'), self.IMAGE_FILTER_CSV_COMMA: (',', 'csv'), self.IMAGE_FILTER_CSV_SEMICOLON: (';', 'csv'), self.IMAGE_FILTER_CSV_TAB: ('\t', 'csv'), }[nameFilter] height, width = data.shape rows, cols = numpy.mgrid[0:height, 0:width] try: save1D(filename, rows.ravel(), (cols.ravel(), data.ravel()), filetype=filetype, xlabel='row', ylabels=['column', 'value'], csvdelim=csvdelim, autoheader=True) except IOError: self._errorMessage('Save failed\n') return False return True elif nameFilter in (self.IMAGE_FILTER_RGB_PNG, self.IMAGE_FILTER_RGB_TIFF): # Get displayed image rgbaImage = image.getRgbaImageData(copy=False) # Convert RGB QImage qimage = convertArrayToQImage(rgbaImage[:, :, :3]) if nameFilter == self.IMAGE_FILTER_RGB_PNG: fileFormat = 'PNG' else: fileFormat = 'TIFF' if qimage.save(filename, fileFormat): return True else: _logger.error('Failed to save image as %s', filename) qt.QMessageBox.critical(self.parent(), 'Save image as', 'Failed to save image') return False