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 _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