save figure image to file
355842
def save_figure(self,event=None, transparent=False, dpi=600):
        
        if self.panel is not None:
            self.panel.save_figure(event=event,
                                   transparent=transparent, dpi=dpi)
997391
async def artwork_save(self):
        """"""
        artwork = await self.atv.metadata.artwork()
        if artwork is not None:
            with open('artwork.png', 'wb') as file:
                file.write(artwork)
        else:
            print('No artwork is currently available.')
            return 1
        return 0
1366342
def _save_seaborn_chart(self, report, folderpath):
        
        if folderpath is None:
            if self.imgs_path is None:
                self.err(self._save_seaborn_chart,
                         "Please set a path where to save images: ds.imgs_path"
                         " = '/my/path'")
                return
            path = self.imgs_path
        else:
            path = folderpath
        path = path + "/" + report["slug"] + ".png"
        try:
            try:
                # print("*** TRY", report["seaborn_chart"].figure.show())
                fig = report["seaborn_chart"].figure
                fig.savefig(path)
            except Exception as e:
                try:
                    fig = report["seaborn_chart"]
                    fig.savefig(path)
                except Exception:
                    plot = report["seaborn_chart"]
                    plot = plot.get_figure()
                    plot.savefig(path)
        except Exception as e:
            self.err(e, self._save_seaborn_chart, "Can not save Seaborn chart")
            return
        if self.autoprint is True:
            self.ok("Seaborn chart writen to " + path)
26853
def _finalise_figure(fig, **kwargs):  # pragma: no cover
    
    title = kwargs.get("title") or None
    show = kwargs.get("show") or False
    save = kwargs.get("save") or False
    savefile = kwargs.get("savefile") or "EQcorrscan_figure.png"
    return_fig = kwargs.get("return_figure") or False
    if title:
        fig.suptitle(title)
    if show:
        fig.show()
    if save:
        fig.savefig(savefile)
        print("Saved figure to {0}".format(savefile))
    if return_fig:
        return fig
    return None
833402
def save_plot(self, filename, img_format="eps", ylim=None,
                  zero_to_efermi=True, smooth=False):
        
        plt = self.get_plot(ylim=ylim, zero_to_efermi=zero_to_efermi,
                            smooth=smooth)
        plt.savefig(filename, format=img_format)
        plt.close()
1285194
def plot_and_save(self, **kwargs):
        """"""
        self.fig = pyplot.figure()
        self.plot()
        self.axes = pyplot.gca()
        self.save_plot(self.fig, self.axes, **kwargs)
        pyplot.close(self.fig)
533777
def save_image(xdata: DataAndMetadata.DataAndMetadata, file):
    
    # we need to create a basic DM tree suitable for an image
    # we'll try the minimum: just an data list
    # doesn't work. Do we need a ImageSourceList too?
    # and a DocumentObjectList?

    data = xdata.data
    data_descriptor = xdata.data_descriptor
    dimensional_calibrations = xdata.dimensional_calibrations
    intensity_calibration = xdata.intensity_calibration
    metadata = xdata.metadata
    modified = xdata.timestamp
    timezone = xdata.timezone
    timezone_offset = xdata.timezone_offset
    needs_slice = False
    is_sequence = False

    if len(data.shape) == 3 and data.dtype != numpy.uint8 and data_descriptor.datum_dimension_count == 1:
        data = numpy.moveaxis(data, 2, 0)
        dimensional_calibrations = (dimensional_calibrations[2],) + tuple(dimensional_calibrations[0:2])
    if len(data.shape) == 2 and data.dtype != numpy.uint8 and data_descriptor.datum_dimension_count == 1:
        is_sequence = data_descriptor.is_sequence
        data = numpy.moveaxis(data, 1, 0)
        data = numpy.expand_dims(data, axis=1)
        dimensional_calibrations = (dimensional_calibrations[1], Calibration.Calibration(), dimensional_calibrations[0])
        data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 1)
        needs_slice = True
    data_dict = ndarray_to_imagedatadict(data)
    ret = {}
    ret["ImageList"] = [{"ImageData": data_dict}]
    if dimensional_calibrations and len(dimensional_calibrations) == len(data.shape):
        dimension_list = data_dict.setdefault("Calibrations", dict()).setdefault("Dimension", list())
        for dimensional_calibration in reversed(dimensional_calibrations):
            dimension = dict()
            if dimensional_calibration.scale != 0.0:
                origin = -dimensional_calibration.offset / dimensional_calibration.scale
            else:
                origin = 0.0
            dimension['Origin'] = origin
            dimension['Scale'] = dimensional_calibration.scale
            dimension['Units'] = dimensional_calibration.units
            dimension_list.append(dimension)
    if intensity_calibration:
        if intensity_calibration.scale != 0.0:
            origin = -intensity_calibration.offset / intensity_calibration.scale
        else:
            origin = 0.0
        brightness = data_dict.setdefault("Calibrations", dict()).setdefault("Brightness", dict())
        brightness['Origin'] = origin
        brightness['Scale'] = intensity_calibration.scale
        brightness['Units'] = intensity_calibration.units
    if modified:
        timezone_str = None
        if timezone_str is None and timezone:
            try:
                import pytz
                tz = pytz.timezone(timezone)
                timezone_str = tz.tzname(modified)
            except:
                pass
        if timezone_str is None and timezone_offset:
            timezone_str = timezone_offset
        timezone_str = " " + timezone_str if timezone_str is not None else ""
        date_str = modified.strftime("%x")
        time_str = modified.strftime("%X") + timezone_str
        ret["DataBar"] = {"Acquisition Date": date_str, "Acquisition Time": time_str}
    # I think ImageSource list creates a mapping between ImageSourceIds and Images
    ret["ImageSourceList"] = [{"ClassName": "ImageSource:Simple", "Id": [0], "ImageRef": 0}]
    # I think this lists the sources for the DocumentObjectlist. The source number is not
    # the indxe in the imagelist but is either the index in the ImageSourceList or the Id
    # from that list. We also need to set the annotation type to identify it as an data
    ret["DocumentObjectList"] = [{"ImageSource": 0, "AnnotationType": 20}]
    # finally some display options
    ret["Image Behavior"] = {"ViewDisplayID": 8}
    dm_metadata = copy.deepcopy(metadata)
    if metadata.get("hardware_source", dict()).get("signal_type", "").lower() == "eels":
        if len(data.shape) == 1 or (len(data.shape) == 2 and data.shape[0] == 1):
            dm_metadata.setdefault("Meta Data", dict())["Format"] = "Spectrum"
            dm_metadata.setdefault("Meta Data", dict())["Signal"] = "EELS"
    elif data_descriptor.collection_dimension_count == 2 and data_descriptor.datum_dimension_count == 1:
        dm_metadata.setdefault("Meta Data", dict())["Format"] = "Spectrum image"
        dm_metadata.setdefault("Meta Data", dict())["Signal"] = "EELS"
    elif data_descriptor.datum_dimension_count == 1:
        dm_metadata.setdefault("Meta Data", dict())["Format"] = "Spectrum"
    if (1 if data_descriptor.is_sequence else 0) + data_descriptor.collection_dimension_count == 1 or needs_slice:
        if data_descriptor.is_sequence or is_sequence:
            dm_metadata.setdefault("Meta Data", dict())["IsSequence"] = True
        ret["ImageSourceList"] = [{"ClassName": "ImageSource:Summed", "Do Sum": True, "Id": [0], "ImageRef": 0, "LayerEnd": 0, "LayerStart": 0, "Summed Dimension": len(data.shape) - 1}]
        if needs_slice:
            ret["DocumentObjectList"][0]["AnnotationGroupList"] = [{"AnnotationType": 23, "Name": "SICursor", "Rectangle": (0, 0, 1, 1)}]
            ret["DocumentObjectList"][0]["ImageDisplayType"] = 1  # display as an image
    if modified:
        dm_metadata["Timestamp"] = modified.isoformat()
    if timezone:
        dm_metadata["Timezone"] = timezone
    if timezone_offset:
        dm_metadata["TimezoneOffset"] = timezone_offset
    ret["ImageList"][0]["ImageTags"] = dm_metadata
    ret["InImageMode"] = True
    parse_dm3.parse_dm_header(file, ret)
671544
def save_image(image, destination=None, filename=None, **options):
    
    if destination is None:
        destination = BytesIO()
    filename = filename or ''
    # Ensure plugins are fully loaded so that Image.EXTENSION is populated.
    Image.init()
    format = Image.EXTENSION.get(os.path.splitext(filename)[1].lower(), 'JPEG')
    if format in ('JPEG', 'WEBP'):
        options.setdefault('quality', 85)
    saved = False
    if format == 'JPEG':
        if image.mode.endswith('A'):
            # From PIL 4.2, saving an image with a transparency layer raises an
            # IOError, so explicitly remove it.
            image = image.convert(image.mode[:-1])
        if settings.THUMBNAIL_PROGRESSIVE and (
                max(image.size) >= settings.THUMBNAIL_PROGRESSIVE):
            options['progressive'] = True
        try:
            image.save(destination, format=format, optimize=1, **options)
            saved = True
        except IOError:
            # Try again, without optimization (PIL can't optimize an image
            # larger than ImageFile.MAXBLOCK, which is 64k by default). This
            # shouldn't be triggered very often these days, as recent versions
            # of pillow avoid the MAXBLOCK limitation.
            pass
    if not saved:
        image.save(destination, format=format, **options)
    if hasattr(destination, 'seek'):
        destination.seek(0)
    return destination
877476
def dump_img(fname):
    
    img = Image.open(fname)
    width, _ = img.size
    txt = ''
    pixels = list(img.getdata())
    for col in range(width):
        txt += str(pixels[col:col+width])
    return txt
815048
def to_picture(self, filename):
        
        fileformat = path.splitext(filename)[1][1:]
        with NamedTemporaryFile("wb", delete=False) as dotfile:
            dotfilename = dotfile.name
            for line in self:
                dotfile.write(("%s\n" % line).encode("utf-8"))
            dotfile.flush()
            cmd = ["dot", dotfilename, "-T", fileformat, "-o", filename]
            check_call(cmd)
        try:
            remove(dotfilename)
        except Exception:  # pragma: no cover
            msg = 'Could not remove temporary file %s' % dotfilename
            logging.getLogger(__name__).warn(msg)
990428
def save(output_filename, labels, palette, dpi, options):

    '''

    '''

    if not options.quiet:
        print('  saving {}...'.format(output_filename))

    if options.saturate:
        palette = palette.astype(np.float32)
        pmin = palette.min()
        pmax = palette.max()
        palette = 255 * (palette - pmin)/(pmax-pmin)
        palette = palette.astype(np.uint8)

    if options.white_bg:
        palette = palette.copy()
        palette[0] = (255, 255, 255)

    output_img = Image.fromarray(labels, 'P')
    output_img.putpalette(palette.flatten())
    output_img.save(output_filename, dpi=dpi)
526021
def plot(config, image, file):
    
    image = np.squeeze(image)
    print(file, image.shape)
    imsave(file, image)
679124
def save_figure(self,event=None,panel=None):
        
        if panel is None: panel = self.current_panel
        self.panels[panel].save_figure(event=event)
531622
def save(self, path, **kwargs):
        
        self.plot if not hasattr(self, '_plot') else None
        self.figure.savefig(path, **kwargs)
1022417
def savefig(writekey, dpi=None, ext=None):
    
    if dpi is None:
        # we need this as in notebooks, the internal figures are also influenced by 'savefig.dpi' this...
        if not isinstance(rcParams['savefig.dpi'], str) and rcParams['savefig.dpi'] < 150:
            if settings._low_resolution_warning:
                logg.warn(
                    'You are using a low resolution (dpi<150) for saving figures.\n'
                    'Consider running `set_figure_params(dpi_save=...)`, which will '
                    'adjust `matplotlib.rcParams[\'savefig.dpi\']`')
                settings._low_resolution_warning = False
        else:
            dpi = rcParams['savefig.dpi']
    if not os.path.exists(settings.figdir): os.makedirs(settings.figdir)
    if settings.figdir[-1] != '/': settings.figdir += '/'
    if ext is None: ext = settings.file_format_figs
    filename = settings.figdir + writekey + settings.plot_suffix + '.' + ext
    # output the following msg at warning level; it's really important for the user
    logg.msg('saving figure to file', filename, v=1)
    pl.savefig(filename, dpi=dpi, bbox_inches='tight')
1197821
def save(self, filename):
        
        plt.savefig(filename, fig=self.fig, facecolor='black', edgecolor='black')
252056
def save_image(self, img, filename=None, **kwargs):  # floating_point=False,
        
        filename = filename or self.get_filename(**img.data.attrs)
        nt.save(img, filename, **kwargs)