Save a matplotlib figure to a png with metadata
435234
def save_png_with_metadata(fig, filename, fig_kwds, kwds):
    
    from PIL import Image, PngImagePlugin
    fig.savefig(filename, **fig_kwds)

    im = Image.open(filename)
    meta = PngImagePlugin.PngInfo()

    for key in kwds:
        meta.add_text(str(key), str(kwds[key]))

    im.save(filename, "png", pnginfo=meta)
634512
def save_cb(self):
        """"""

        # This just defines the basename.
        # Extension has to be explicitly defined or things can get messy.
        w = Widgets.SaveDialog(title='Save plot')
        target = w.get_path()
        if target is None:
            # Save canceled
            return

        plot_ext = self.settings.get('file_suffix', '.png')

        if not target.endswith(plot_ext):
            target += plot_ext

        # TODO: This can be a user preference?
        fig_dpi = 100

        try:
            fig = self.tab_plot.get_figure()
            fig.savefig(target, dpi=fig_dpi)

        except Exception as e:
            self.logger.error(str(e))
        else:
            self.logger.info('Table plot saved as {0}'.format(target))
1343720
def __view_to_selected_graphics(self, data_and_metadata: DataAndMetadata.DataAndMetadata) -> None:
        """"""
        all_graphics = self.__graphics
        graphics = [graphic for graphic_index, graphic in enumerate(all_graphics) if self.__graphic_selection.contains(graphic_index)]
        intervals = list()
        for graphic in graphics:
            if isinstance(graphic, Graphics.IntervalGraphic):
                intervals.append(graphic.interval)
        self.__view_to_intervals(data_and_metadata, intervals)
1046462
def convert_mat_to_images(args):
    '''
    '''
    dataset = scipy.io.loadmat("{}/{}".format(args.save_path, args.dataset))

    # image pixel data
    X = dataset['X']

    # image class labels (not used in this project)
    Y = dataset['Y']

    total_image = X.shape[0]

    h=args.height
    w=args.width

    for i in range(total_image):
        img = X[i]
        img = np.reshape(img, (28, 28))
        if args.invert:
            img = (1-img)*255
        else:
            img = img*255
        img = Image.fromarray(img, 'L')
        img = img.rotate(-90)
        img = img.resize([h, w], Image.BILINEAR)
        img.save(args.save_path + '/img' + str(i) + '.png')
244498
def svg_html_from_pyplot_figure(fig: "Figure") -> str:
    
    if fig is None:
        return ""
    memfile = io.BytesIO()  # StringIO doesn't like mixing str/unicode
    fig.savefig(memfile, format="svg")
    return memfile.getvalue().decode("utf-8")
607788
def save_mat(ts, filename):
    
    import scipy.io as sio
    tspan = ts.tspan
    fs = (1.0*len(tspan) - 1) / (tspan[-1] - tspan[0])
    mat_dict = {'data': np.asarray(ts),
                'fs': fs,
                'labels': ts.labels[1]}
    sio.savemat(filename, mat_dict, do_compression=True)
    return
1021736
def image_to_tf_summary_value(image, tag):
  
  curr_image = np.asarray(image, dtype=np.uint8)
  height, width, n_channels = curr_image.shape
  # If monochrome image, then reshape to [height, width]
  if n_channels == 1:
    curr_image = np.reshape(curr_image, [height, width])
  s = io.BytesIO()
  matplotlib_pyplot().imsave(s, curr_image, format="png")
  img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
                             height=height, width=width,
                             colorspace=n_channels)
  return tf.Summary.Value(tag=tag, image=img_sum)
530896
def _plt_handle_figure(plot):
    """

    # Preserve documentation of plot.
    @functools.wraps(plot)

    def inner(obj, **kwargs):

        # Create a figure and an axis if none were passed.
        if kwargs['ax'] is None:
            _, plt, _ = _import_plt()
            fig = plt.figure()
            global _plt_figures
            _plt_figures.append(fig)

            if (hasattr(obj, 'coords') and obj.coords.ndim == 2 and
                    obj.coords.shape[1] == 3):
                kwargs['ax'] = fig.add_subplot(111, projection='3d')
            else:
                kwargs['ax'] = fig.add_subplot(111)

        title = kwargs.pop('title')

        plot(obj, **kwargs)

        kwargs['ax'].set_title(title)

        try:
            fig.show(warn=False)
        except NameError:
            # No figure created, an axis was passed.
            pass

        return kwargs['ax'].figure, kwargs['ax']

    return inner
1100089
def save_as_png(self, filename, width=300, height=250, render_time=1):
        """"""
        self.driver.set_window_size(width, height)
        self.driver.get('file://{path}/{filename}'.format(
            path=os.getcwd(), filename=filename + ".html"))
        time.sleep(render_time)
        self.driver.save_screenshot(filename + ".png")
1131560
def png_img_html_from_pyplot_figure(fig: "Figure",
                                    dpi: int = 100,
                                    extra_html_class: str = None) -> str:
    
    if fig is None:
        return ""
    # Make a file-like object
    memfile = io.BytesIO()
    # In general, can do
    #   fig.savefig(filename/file-like-object/backend, format=...)
    # or
    #   backend.savefig(fig):
    # see e.g. http://matplotlib.org/api/backend_pdf_api.html
    fig.savefig(memfile, format="png", dpi=dpi)
    memfile.seek(0)
    pngblob = memoryview(memfile.read())
    return rnc_web.get_png_img_html(pngblob, extra_html_class)
535616
def encode(self, s):
    
    try:
      import matplotlib.image as im  # pylint: disable=g-import-not-at-top
    except ImportError as e:
      tf.logging.warning(
          "Reading an image requires matplotlib to be installed: %s", e)
      raise NotImplementedError("Image reading not implemented.")
    return im.imread(s)
1041419
def save_figure_tofile(fig, fmt, fname):
    """"""
    root, ext = osp.splitext(fname)
    if ext == '.png' and fmt == 'image/svg+xml':
        qimg = svg_to_image(fig)
        qimg.save(fname)
    else:
        if fmt == 'image/svg+xml' and is_unicode(fig):
            fig = fig.encode('utf-8')

        with open(fname, 'wb') as f:
            f.write(fig)
712464
def _save_plot(self, *args, extension='pdf', **kwargs):
        
        import matplotlib.pyplot as plt

        tmp_path = make_temp_dir()
        filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.'))
        filepath = posixpath.join(tmp_path, filename)

        plt.savefig(filepath, *args, **kwargs)
        return filepath
1082775
def _save_image(fig, filename, filetype='png', resolution=300):
    
    if filename:
        filename, filetype, resolution = build_filename(filename,
                                                        filetype,
                                                        resolution)
        fig.savefig(filename, dpi=resolution, format=filetype)
    else:
        pass
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)
408267
def add_image(self, figure, dpi=72):
        '''
        
        '''
        name = os.path.join(self._dir, '/fig%s.png' % self.fig_counter)
        self.fig_counter += 1
        figure.savefig(name, dpi=dpi)
        plt.close(figure)
        self.body += '<img src="%s" />\n' % name
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()