def save(fig, filename): """We have to work around `fig.canvas.print_png`, etc calling `draw`.""" renderer = fig.canvas.renderer with open(filename, 'w') as outfile: _png.write_png(renderer._renderer.buffer_rgba(), renderer.width, renderer.height, outfile, fig.dpi)
def save_diff_image(expected, actual, output): expectedImage = _png.read_png(expected) actualImage = _png.read_png(actual) actualImage, expectedImage = crop_to_same(actual, actualImage, expected, expectedImage) expectedImage = np.array(expectedImage).astype(np.float) actualImage = np.array(actualImage).astype(np.float) assert expectedImage.ndim == actualImage.ndim assert expectedImage.shape == actualImage.shape absDiffImage = abs(expectedImage - actualImage) # expand differences in luminance domain absDiffImage *= 255 * 10 save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8) height, width, depth = save_image_np.shape # The PDF renderer doesn't produce an alpha channel, but the # matplotlib PNG writer requires one, so expand the array if depth == 3: with_alpha = np.empty((height, width, 4), dtype=np.uint8) with_alpha[:, :, 0:3] = save_image_np save_image_np = with_alpha # Hard-code the alpha channel to fully solid save_image_np[:, :, 3] = 255 _png.write_png(save_image_np.tostring(), width, height, output)
def save_diff_image(expected, actual, output): expectedImage = _png.read_png(expected) actualImage = _png.read_png(actual) actualImage, expectedImage = crop_to_same( actual, actualImage, expected, expectedImage) expectedImage = np.array(expectedImage).astype(np.float) actualImage = np.array(actualImage).astype(np.float) assert expectedImage.ndim == actualImage.ndim assert expectedImage.shape == actualImage.shape absDiffImage = abs(expectedImage - actualImage) # expand differences in luminance domain absDiffImage *= 255 * 10 save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8) height, width, depth = save_image_np.shape # The PDF renderer doesn't produce an alpha channel, but the # matplotlib PNG writer requires one, so expand the array if depth == 3: with_alpha = np.empty((height, width, 4), dtype=np.uint8) with_alpha[:, :, 0:3] = save_image_np save_image_np = with_alpha # Hard-code the alpha channel to fully solid save_image_np[:, :, 3] = 255 _png.write_png(save_image_np.tostring(), width, height, output)
def write_trailer(self, resolution=72): renderer = self.renderer if hasattr(renderer._renderer, "write_png"): # Old version of matplotlib: renderer._renderer.write_png(self.filename) else: from matplotlib import _png # buffer_rgba does not accept arguments from version 1.2.0 # https://github.com/matplotlib/matplotlib/commit/f4fee350f9fbc639853bee76472d8089a10b40bd import matplotlib if matplotlib.__version__ < "1.2.0": x = renderer._renderer.buffer_rgba(0, 0) _png.write_png( renderer._renderer.buffer_rgba(0, 0), renderer.width, renderer.height, self.filename, resolution ) else: x = renderer._renderer.buffer_rgba() _png.write_png( renderer._renderer.buffer_rgba(), # renderer.width, renderer.height, self.filename, resolution, )
def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if isinstance(filename_or_obj, six.string_types): filename_or_obj = open(filename_or_obj, 'wb') close = True else: close = False version_str = 'matplotlib version ' + __version__ + \ ', http://matplotlib.org/' metadata = OrderedDict({'Software': version_str}) user_metadata = kwargs.pop("metadata", None) if user_metadata is not None: metadata.update(user_metadata) try: _png.write_png(renderer._renderer, filename_or_obj, self.figure.dpi, metadata=metadata) finally: if close: filename_or_obj.close() renderer.dpi = original_dpi
def draw_image(self, gc, x, y, im, transform=None): h, w = im.shape[:2] if w == 0 or h == 0: return # save the images to png files path = os.path.dirname(self.fh.name) fname = os.path.splitext(os.path.basename(self.fh.name))[0] fname_img = "%s-img%d.png" % (fname, self.image_counter) self.image_counter += 1 _png.write_png(im[::-1], os.path.join(path, fname_img)) # reference the image in the pgf picture writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_clip(gc) f = 1. / self.dpi # from display coords to inch if transform is None: writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f)) w, h = w * f, h * f else: tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() writeln(self.fh, r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" % (tr1 * f, tr2 * f, tr3 * f, tr4 * f, (tr5 + x) * f, (tr6 + y) * f)) w = h = 1 # scale is already included in the transform interp = str(transform is None).lower() # interpolation in PDF reader writeln(self.fh, r"\pgftext[left,bottom]" r"{\pgfimage[interpolate=%s,width=%fin,height=%fin]{%s}}" % (interp, w, h, fname_img)) writeln(self.fh, r"\end{pgfscope}")
def refresh(self): if not self.init: return if fig.canvas.toolbar.needs_draw: fig.canvas.draw() fig.canvas.toolbar.needs_draw = False renderer = fig.canvas.get_renderer() buffer = np.array( np.frombuffer(renderer.buffer_rgba(0,0), dtype=np.uint32), copy=True) buffer = buffer.reshape((renderer.height, renderer.width)) last_buffer = self.last_buffer if last_buffer is not None: diff = buffer != last_buffer if not np.any(diff): output = np.zeros((1, 1)) else: output = np.where(diff, buffer, 0) else: output = buffer png_buffer.reset() png_buffer.truncate() #global_timer() _png.write_png(output.tostring(), output.shape[1], output.shape[0], png_buffer) #print global_timer datauri = "data:image/png;base64,{0}".format(png_buffer.getvalue().encode("base64").replace("\n", "")) self.write_message(datauri) self.last_buffer = buffer
def save_diff_image(expected, actual, output): expectedImage = _png.read_png(expected) actualImage = _png.read_png(actual) actualImage, expectedImage = crop_to_same( actual, actualImage, expected, expectedImage) expectedImage = np.array(expectedImage).astype(float) actualImage = np.array(actualImage).astype(float) if expectedImage.shape != actualImage.shape: raise ImageComparisonFailure( "Image sizes do not match expected size: {0} " "actual size {1}".format(expectedImage.shape, actualImage.shape)) absDiffImage = np.abs(expectedImage - actualImage) # expand differences in luminance domain absDiffImage *= 255 * 10 save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8) height, width, depth = save_image_np.shape # The PDF renderer doesn't produce an alpha channel, but the # matplotlib PNG writer requires one, so expand the array if depth == 3: with_alpha = np.empty((height, width, 4), dtype=np.uint8) with_alpha[:, :, 0:3] = save_image_np save_image_np = with_alpha # Hard-code the alpha channel to fully solid save_image_np[:, :, 3] = 255 _png.write_png(save_image_np, output)
def draw_image(self, gc, x, y, im, transform=None): h, w = im.shape[:2] if w == 0 or h == 0: return # save the images to png files path = os.path.dirname(self.fh.name) fname = os.path.splitext(os.path.basename(self.fh.name))[0] fname_img = "%s-img%d.png" % (fname, self.image_counter) self.image_counter += 1 _png.write_png(im[::-1], os.path.join(path, fname_img)) # reference the image in the pgf picture writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_clip(gc) f = 1. / self.dpi # from display coords to inch if transform is None: writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f)) w, h = w * f, h * f else: tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values() writeln( self.fh, r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" % (tr1 * f, tr2 * f, tr3 * f, tr4 * f, (tr5 + x) * f, (tr6 + y) * f)) w = h = 1 # scale is already included in the transform interp = str(transform is None).lower() # interpolation in PDF reader writeln( self.fh, r"\pgftext[left,bottom]" r"{\pgfimage[interpolate=%s,width=%fin,height=%fin]{%s}}" % (interp, w, h, fname_img)) writeln(self.fh, r"\end{pgfscope}")
def get_diff_image(self): if self._png_is_old: # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. buff = np.frombuffer(self._renderer.buffer_rgba(), dtype=np.uint32) buff.shape = (self._renderer.height, self._renderer.width) if not self._force_full: last_buffer = np.frombuffer(self._last_renderer.buffer_rgba(), dtype=np.uint32) last_buffer.shape = (self._renderer.height, self._renderer.width) diff = buff != last_buffer output = np.where(diff, buff, 0) else: output = buff # Clear out the PNG data buffer rather than recreating it # each time. This reduces the number of memory # (de)allocations. self._png_buffer.truncate() self._png_buffer.seek(0) # TODO: We should write a new version of write_png that # handles the differencing inline _png.write_png(output.tostring(), output.shape[1], output.shape[0], self._png_buffer) # Swap the renderer frames self._renderer, self._last_renderer = (self._last_renderer, self._renderer) self._force_full = False self._png_is_old = False return self._png_buffer.getvalue()
def save_diff_image(expected, actual, output): # Drop alpha channels, similarly to compare_images. expectedImage = _png.read_png(expected)[..., :3] actualImage = _png.read_png(actual)[..., :3] actualImage, expectedImage = crop_to_same( actual, actualImage, expected, expectedImage) expectedImage = np.array(expectedImage).astype(float) actualImage = np.array(actualImage).astype(float) if expectedImage.shape != actualImage.shape: raise ImageComparisonFailure( "Image sizes do not match expected size: {} " "actual size {}".format(expectedImage.shape, actualImage.shape)) absDiffImage = np.abs(expectedImage - actualImage) # expand differences in luminance domain absDiffImage *= 255 * 10 save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8) height, width, depth = save_image_np.shape # The PDF renderer doesn't produce an alpha channel, but the # matplotlib PNG writer requires one, so expand the array if depth == 3: with_alpha = np.empty((height, width, 4), dtype=np.uint8) with_alpha[:, :, 0:3] = save_image_np save_image_np = with_alpha # Hard-code the alpha channel to fully solid save_image_np[:, :, 3] = 255 _png.write_png(save_image_np, output)
def write_png_to_string(buffer, dpi=100, gray=0): width = buffer.shape[1] height = buffer.shape[0] fileobj = cStringIO.StringIO() _png.write_png(buffer, width, height, fileobj, dpi) png_str = fileobj.getvalue() fileobj.close() return png_str
def write_png_to_string(buffer, dpi=100, gray=0): width = buffer.shape[1] height = buffer.shape[0] fileobj = cStringIO() _png.write_png(buffer, width, height, fileobj, dpi) png_str = fileobj.getvalue() fileobj.close() return png_str
def print_png(self, filename_or_obj, *args, **kwargs): """ Write the figure to a PNG file. Parameters ---------- filename_or_obj : str or PathLike or file-like object The file to write to. metadata : dict, optional Metadata in the PNG file as key-value pairs of bytes or latin-1 encodable strings. According to the PNG specification, keys must be shorter than 79 chars. The `PNG specification`_ defines some common keywords that may be used as appropriate: - Title: Short (one line) title or caption for image. - Author: Name of image's creator. - Description: Description of image (possibly long). - Copyright: Copyright notice. - Creation Time: Time of original image creation (usually RFC 1123 format). - Software: Software used to create the image. - Disclaimer: Legal disclaimer. - Warning: Warning of nature of content. - Source: Device used to create the image. - Comment: Miscellaneous comment; conversion from other image format. Other keywords may be invented for other purposes. If 'Software' is not given, an autogenerated value for matplotlib will be used. For more details see the `PNG specification`_. .. _PNG specification: \ https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords """ FigureCanvasAgg.draw(self) renderer = self.get_renderer() version_str = ('matplotlib version ' + __version__ + ', http://matplotlib.org/') metadata = OrderedDict({'Software': version_str}) user_metadata = kwargs.pop("metadata", None) if user_metadata is not None: metadata.update(user_metadata) with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \ cbook.open_file_cm(filename_or_obj, "wb") as fh: _png.write_png(renderer._renderer, fh, self.figure.dpi, metadata=metadata)
def print_png(self, filename_or_obj, *args, **kwargs): """ Write the figure to a PNG file. Parameters ---------- filename_or_obj : str or PathLike or file-like object The file to write to. metadata : dict, optional Metadata in the PNG file as key-value pairs of bytes or latin-1 encodable strings. According to the PNG specification, keys must be shorter than 79 chars. The `PNG specification`_ defines some common keywords that may be used as appropriate: - Title: Short (one line) title or caption for image. - Author: Name of image's creator. - Description: Description of image (possibly long). - Copyright: Copyright notice. - Creation Time: Time of original image creation (usually RFC 1123 format). - Software: Software used to create the image. - Disclaimer: Legal disclaimer. - Warning: Warning of nature of content. - Source: Device used to create the image. - Comment: Miscellaneous comment; conversion from other image format. Other keywords may be invented for other purposes. If 'Software' is not given, an autogenerated value for matplotlib will be used. For more details see the `PNG specification`_. .. _PNG specification: \ https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords """ FigureCanvasAgg.draw(self) renderer = self.get_renderer() version_str = ( 'matplotlib version ' + __version__ + ', http://matplotlib.org/') metadata = OrderedDict({'Software': version_str}) user_metadata = kwargs.pop("metadata", None) if user_metadata is not None: metadata.update(user_metadata) with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \ cbook.open_file_cm(filename_or_obj, "wb") as fh: _png.write_png(renderer._renderer, fh, self.figure.dpi, metadata=metadata)
def write_trailer(self): renderer = self.renderer if hasattr(renderer._renderer, 'write_png'): # Old version of matplotlib: renderer._renderer.write_png(self.filename) else: x = renderer._renderer.buffer_rgba(0, 0) from matplotlib import _png _png.write_png(renderer._renderer.buffer_rgba(0, 0), renderer.width, renderer.height, self.filename, 72)
def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = file(filename_or_obj, 'wb') _png.write_png(renderer._renderer.buffer_rgba(0, 0), renderer.width, renderer.height, filename_or_obj, self.figure.dpi) renderer.dpi = original_dpi
def draw_image(self, gc, x, y, im): clipid = self._get_gc_clip_svg(gc) if clipid is None: clippath = u'' else: clippath = u'clip-path="url(#%s)"' % clipid trans = [1, 0, 0, 1, 0, 0] transstr = u'' if rcParams['svg.image_noscale']: trans = list(im.get_matrix()) trans[5] = -trans[5] transstr = u'transform="matrix(%f %f %f %f %f %f)" ' % tuple(trans) assert trans[1] == 0 assert trans[2] == 0 numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) h, w = im.get_size_out() url = getattr(im, '_url', None) if url is not None: self._svgwriter.write(u'<a xlink:href="%s">' % url) self._svgwriter.write( u'<image x="%f" y="%f" width="%f" height="%f" ' u'%s %s xlink:href="' % (x / trans[0], (self.height - y) / trans[3] - h, w, h, transstr, clippath)) if rcParams['svg.image_inline']: self._svgwriter.write(u"data:image/png;base64,\n") bytesio = io.BytesIO() im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, bytesio) im.flipud_out() self._svgwriter.write( encodebytes(bytesio.getvalue()).decode('ascii')) else: self._imaged[self.basename] = self._imaged.get(self.basename, 0) + 1 filename = '%s.image%d.png' % (self.basename, self._imaged[self.basename]) verbose.report('Writing image file for inclusion: %s' % filename) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, filename) im.flipud_out() self._svgwriter.write(filename) self._svgwriter.write(u'"/>\n') if url is not None: self._svgwriter.write(u'</a>')
def write_png(self, fname, noscale=False): """Write the image to png file with fname""" im = self.make_image() if noscale: numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, fname)
def draw_image(self, gc, x, y, im): clipid = self._get_gc_clip_svg(gc) if clipid is None: clippath = u'' else: clippath = u'clip-path="url(#%s)"' % clipid trans = [1,0,0,1,0,0] transstr = u'' if rcParams['svg.image_noscale']: trans = list(im.get_matrix()) trans[5] = -trans[5] transstr = u'transform="matrix(%f %f %f %f %f %f)" ' % tuple(trans) assert trans[1] == 0 assert trans[2] == 0 numrows,numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) h,w = im.get_size_out() url = getattr(im, '_url', None) if url is not None: self._svgwriter.write(u'<a xlink:href="%s">' % url) self._svgwriter.write ( u'<image x="%f" y="%f" width="%f" height="%f" ' u'%s %s xlink:href="' % ( x/trans[0], (self.height-y)/trans[3]-h, w, h, transstr, clippath) ) if rcParams['svg.image_inline']: self._svgwriter.write(u"data:image/png;base64,\n") bytesio = io.BytesIO() im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, bytesio) im.flipud_out() self._svgwriter.write( base64.encodebytes(bytesio.getvalue()).decode('ascii')) else: self._imaged[self.basename] = self._imaged.get(self.basename,0) + 1 filename = '%s.image%d.png'%(self.basename, self._imaged[self.basename]) verbose.report( 'Writing image file for inclusion: %s' % filename) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, filename) im.flipud_out() self._svgwriter.write(filename) self._svgwriter.write(u'"/>\n') if url is not None: self._svgwriter.write(u'</a>')
def write_png(self, fname, noscale=False): """Write the image to png file with fname""" im = self.make_image() if im is None: return if noscale: numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) _png.write_png(im, fname)
def draw_image(self, gc, x, y, im): attrib = {} clipid = self._get_clip(gc) if clipid is not None: # Can't apply clip-path directly to the image because the # image as a transformation, which would also be applied # to the clip-path self.writer.start('g', attrib={'clip-path': 'url(#%s)' % clipid}) trans = [1,0,0,1,0,0] if rcParams['svg.image_noscale']: trans = list(im.get_matrix()) trans[5] = -trans[5] attrib['transform'] = generate_transform('matrix', tuple(trans)) assert trans[1] == 0 assert trans[2] == 0 numrows,numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) h,w = im.get_size_out() url = getattr(im, '_url', None) if url is not None: self.writer.start('a', attrib={'xlink:href': url}) if rcParams['svg.image_inline']: stringio = cStringIO.StringIO() im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, stringio) im.flipud_out() attrib['xlink:href'] = ("data:image/png;base64,\n" + base64.encodestring(stringio.getvalue())) else: self._imaged[self.basename] = self._imaged.get(self.basename,0) + 1 filename = '%s.image%d.png'%(self.basename, self._imaged[self.basename]) verbose.report( 'Writing image file for inclusion: %s' % filename) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, filename) im.flipud_out() attrib['xlink:href'] = filename self.writer.element( 'image', x=str(x/trans[0]), y=str((self.height-y)/trans[3]-h), width=str(w), height=str(h), attrib=attrib) if url is not None: self.writer.end('a') if clipid is not None: self.writer.end('g')
def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() version_str = ( 'matplotlib version ' + __version__ + ', http://matplotlib.org/') metadata = OrderedDict({'Software': version_str}) user_metadata = kwargs.pop("metadata", None) if user_metadata is not None: metadata.update(user_metadata) with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \ cbook.open_file_cm(filename_or_obj, "wb") as fh: _png.write_png(renderer._renderer, fh, self.figure.dpi, metadata=metadata)
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): # MGDTODO: Support clippath here trans = [1, 0, 0, 1, 0, 0] transstr = '' if rcParams['svg.image_noscale']: trans = list(im.get_matrix()) trans[5] = -trans[5] transstr = 'transform="matrix(%f %f %f %f %f %f)" ' % tuple(trans) assert trans[1] == 0 assert trans[2] == 0 numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) h, w = im.get_size_out() url = getattr(im, '_url', None) if url is not None: self._svgwriter.write('<a xlink:href="%s">' % url) self._svgwriter.write( '<image x="%f" y="%f" width="%f" height="%f" ' '%s xlink:href="' % (x / trans[0], (self.height - y) / trans[3] - h, w, h, transstr)) if rcParams['svg.image_inline']: self._svgwriter.write("data:image/png;base64,\n") stringio = cStringIO.StringIO() im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, stringio) im.flipud_out() self._svgwriter.write(base64.encodestring(stringio.getvalue())) else: self._imaged[self.basename] = self._imaged.get(self.basename, 0) + 1 filename = '%s.image%d.png' % (self.basename, self._imaged[self.basename]) verbose.report('Writing image file for inclusion: %s' % filename) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, filename) im.flipud_out() self._svgwriter.write(filename) self._svgwriter.write('"/>\n') if url is not None: self._svgwriter.write('</a>')
def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = open(filename_or_obj, 'wb') close = True else: close = False try: _png.write_png(renderer._renderer, filename_or_obj, self.figure.dpi) finally: if close: filename_or_obj.close() renderer.dpi = original_dpi
def refresh(self): if not self.init: return if fig.canvas.toolbar.needs_draw: fig.canvas.draw() fig.canvas.toolbar.needs_draw = False renderer = fig.canvas.get_renderer() png_buffer.seek(0) png_buffer.truncate() # global_timer() _png.write_png(renderer._renderer, png_buffer) # print global_timer datauri = "data:image/png;base64,{0}".format( base64.encodebytes(png_buffer.getvalue()).decode("ascii")) self.write_message(datauri)
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): # MGDTODO: Support clippath here trans = [1, 0, 0, 1, 0, 0] transstr = "" if rcParams["svg.image_noscale"]: trans = list(im.get_matrix()) trans[5] = -trans[5] transstr = 'transform="matrix(%f %f %f %f %f %f)" ' % tuple(trans) assert trans[1] == 0 assert trans[2] == 0 numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) h, w = im.get_size_out() url = getattr(im, "_url", None) if url is not None: self._svgwriter.write('<a xlink:href="%s">' % url) self._svgwriter.write( '<image x="%f" y="%f" width="%f" height="%f" ' '%s xlink:href="' % (x / trans[0], (self.height - y) / trans[3] - h, w, h, transstr) ) if rcParams["svg.image_inline"]: self._svgwriter.write("data:image/png;base64,\n") stringio = cStringIO.StringIO() im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, stringio) im.flipud_out() self._svgwriter.write(base64.encodestring(stringio.getvalue())) else: self._imaged[self.basename] = self._imaged.get(self.basename, 0) + 1 filename = "%s.image%d.png" % (self.basename, self._imaged[self.basename]) verbose.report("Writing image file for inclusion: %s" % filename) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, filename) im.flipud_out() self._svgwriter.write(filename) self._svgwriter.write('"/>\n') if url is not None: self._svgwriter.write("</a>")
def get_diff_image(self): if self._png_is_old: renderer = self.get_renderer() # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. buff = np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) buff.shape = (renderer.height, renderer.width) # If any pixels have transparency, we need to force a full # draw as we cannot overlay new on top of old. pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,)) if self._force_full or np.any(pixels[:, :, 3] != 255): self.set_image_mode('full') output = buff else: self.set_image_mode('diff') last_buffer = np.frombuffer(self._last_renderer.buffer_rgba(), dtype=np.uint32) last_buffer.shape = (renderer.height, renderer.width) diff = buff != last_buffer output = np.where(diff, buff, 0) # Clear out the PNG data buffer rather than recreating it # each time. This reduces the number of memory # (de)allocations. self._png_buffer.truncate() self._png_buffer.seek(0) # TODO: We should write a new version of write_png that # handles the differencing inline _png.write_png( output.tostring(), output.shape[1], output.shape[0], self._png_buffer) # Swap the renderer frames self._renderer, self._last_renderer = ( self._last_renderer, renderer) self._force_full = False self._png_is_old = False return self._png_buffer.getvalue()
def draw_image(self, gc, x, y, im): # TODO: Almost no documentation for the behavior of this function. # Something missing? # save the images to png files path = os.path.dirname(self.fh.name) fname = os.path.splitext(os.path.basename(self.fh.name))[0] fname_img = "%s-img%d.png" % (fname, self.image_counter) self.image_counter += 1 _png.write_png(im[::-1], os.path.join(path, fname_img)) # reference the image in the pgf picture writeln(self.fh, r"\begin{pgfscope}") self._print_pgf_clip(gc) h, w = im.shape[:2] f = 1. / self.dpi # from display coords to inch writeln(self.fh, r"\pgftext[at=\pgfqpoint{%fin}{%fin},left,bottom]{\pgfimage[interpolate=true,width=%fin,height=%fin]{%s}}" % (x * f, y * f, w * f, h * f, fname_img)) writeln(self.fh, r"\end{pgfscope}")
def save_diff_image(expected, actual, output): ''' Parameters ---------- expected : str File path of expected image. actual : str File path of actual image. output : str File path to save difference image to. ''' # Drop alpha channels, similarly to compare_images. from matplotlib import _png with open(expected, "rb") as expected_file: expected_image = _png.read_png(expected_file)[..., :3] with open(actual, "rb") as actual_file: actual_image = _png.read_png(actual_file)[..., :3] actual_image, expected_image = crop_to_same( actual, actual_image, expected, expected_image) expected_image = np.array(expected_image).astype(float) actual_image = np.array(actual_image).astype(float) if expected_image.shape != actual_image.shape: raise ImageComparisonFailure( "Image sizes do not match expected size: {} " "actual size {}".format(expected_image.shape, actual_image.shape)) abs_diff_image = np.abs(expected_image - actual_image) # expand differences in luminance domain abs_diff_image *= 255 * 10 save_image_np = np.clip(abs_diff_image, 0, 255).astype(np.uint8) height, width, depth = save_image_np.shape # The PDF renderer doesn't produce an alpha channel, but the # matplotlib PNG writer requires one, so expand the array if depth == 3: with_alpha = np.empty((height, width, 4), dtype=np.uint8) with_alpha[:, :, 0:3] = save_image_np save_image_np = with_alpha # Hard-code the alpha channel to fully solid save_image_np[:, :, 3] = 255 with open(output, "wb") as output_file: _png.write_png(save_image_np, output_file)
def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi version_str = 'matplotlib version ' + __version__ + \ ', http://matplotlib.org/' metadata = OrderedDict({'Software': version_str}) user_metadata = kwargs.pop("metadata", None) if user_metadata is not None: metadata.update(user_metadata) try: with cbook.open_file_cm(filename_or_obj, "wb") as fh: _png.write_png(renderer._renderer, fh, self.figure.dpi, metadata=metadata) finally: renderer.dpi = original_dpi
def write_trailer(self, resolution=72): renderer = self.renderer if hasattr(renderer._renderer, 'write_png'): # Old version of matplotlib: renderer._renderer.write_png(self.filename) else: from matplotlib import _png # buffer_rgba does not accept arguments from version 1.2.0 # https://github.com/matplotlib/matplotlib/commit/f4fee350f9fbc639853bee76472d8089a10b40bd import matplotlib if matplotlib.__version__ < '1.2.0': x = renderer._renderer.buffer_rgba(0, 0) _png.write_png(renderer._renderer.buffer_rgba(0, 0), renderer.width, renderer.height, self.filename, resolution) else: x = renderer._renderer.buffer_rgba() _png.write_png(renderer._renderer.buffer_rgba(), renderer.width, renderer.height, self.filename, resolution)
def show(self): # Clear the buffer and return to the beginning self._buffer.truncate() self._buffer.seek(0) # Draw the image self.draw() # Get the renderer, then write the contents of its RGBA buffer in PNG form into the IO buffer renderer = self.get_renderer() _png.write_png(renderer._renderer.buffer_rgba(), renderer.width, renderer.height, self._buffer) # Get the data data = self._buffer.getvalue() # Create a Larch image resource from the binary data img = resource.ImageFromBinary(data, 'image/png', renderer.width, renderer.height) return img
def save_diff_image(expected, actual, output): ''' Parameters ---------- expected : str File path of expected image. actual : str File path of actual image. output : str File path to save difference image to. ''' # Drop alpha channels, similarly to compare_images. from matplotlib import _png expected_image = _png.read_png(expected)[..., :3] actual_image = _png.read_png(actual)[..., :3] actual_image, expected_image = crop_to_same( actual, actual_image, expected, expected_image) expected_image = np.array(expected_image).astype(float) actual_image = np.array(actual_image).astype(float) if expected_image.shape != actual_image.shape: raise ImageComparisonFailure( "Image sizes do not match expected size: {} " "actual size {}".format(expected_image.shape, actual_image.shape)) abs_diff_image = np.abs(expected_image - actual_image) # expand differences in luminance domain abs_diff_image *= 255 * 10 save_image_np = np.clip(abs_diff_image, 0, 255).astype(np.uint8) height, width, depth = save_image_np.shape # The PDF renderer doesn't produce an alpha channel, but the # matplotlib PNG writer requires one, so expand the array if depth == 3: with_alpha = np.empty((height, width, 4), dtype=np.uint8) with_alpha[:, :, 0:3] = save_image_np save_image_np = with_alpha # Hard-code the alpha channel to fully solid save_image_np[:, :, 3] = 255 _png.write_png(save_image_np, output)
def _slipstream_png(self, x, y, im_buffer, width, height): """Insert image directly into HTML canvas as base64-encoded PNG.""" # Shift x, y (top left corner) to the nearest CSS pixel edge, to prevent resampling and consequent image blurring x = math.floor(x + 0.5) y = math.floor(y + 1.5) # Write the image into a WebPNG object f = WebPNG() _png.write_png(im_buffer, width, height, f) # Write test PNG as file as well #_png.write_png(im_buffer, width, height, 'canvas_image_%d.png' % (self._image_count,)) # Extract the base64-encoded PNG and send it to the canvas uname = str(uuid.uuid1()).replace("-","") #self.ctx._context_name + str(self._image_count) # try to use a unique image name enc = "var canvas_image_%s = 'data:image/png;base64,%s';" % (uname, f.get_b64()) s = "function imageLoaded_%s(ev) {\nim = ev.target;\nim_left_to_load_%s -=1;\nif (im_left_to_load_%s == 0) frame_body_%s();\n}\ncanv_im_%s = new Image();\ncanv_im_%s.onload = imageLoaded_%s;\ncanv_im_%s.src = canvas_image_%s;\n" % \ (uname, self.ctx._context_name, self.ctx._context_name, self.ctx._context_name, uname, uname, uname, uname, uname) self.ctx.add_header(enc) self.ctx.add_header(s) # Once the base64 encoded image has been received, draw it into the canvas self.ctx.write("%s.drawImage(canv_im_%s, %g, %g, %g, %g);" % (self.ctx._context_name, uname, x, y, width, height)) # draw the image as loaded into canv_im_%d... self._image_count += 1
def refresh(self): renderer = fig.canvas.get_renderer() buffer = np.array(np.frombuffer(get_buffer(renderer), dtype=np.uint32), copy=True) buffer = buffer.reshape((renderer.height, renderer.width)) if self.last_buffer is not None: diff = buffer != self.last_buffer if not np.any(diff): output = np.zeros((1, 1)) else: output = np.where(diff, buffer, 0) else: output = buffer self.png_buffer.reset() self.png_buffer.truncate() _png.write_png(output.tostring(), output.shape[1], output.shape[0], self.png_buffer) self.last_buffer = buffer
def print_png( self, path_or_stream, *, metadata=None, # These arguments are already taken care of by print_figure(). dpi=72, facecolor=None, edgecolor=None, orientation="portrait", dryrun=False, bbox_inches_restore=None): img = self._get_fresh_unmultiplied_rgba8888() if dryrun: return full_metadata = OrderedDict([ ("Software", "matplotlib version {}, https://matplotlib.org".format( mpl.__version__)) ]) full_metadata.update(metadata or {}) with cbook.open_file_cm(path_or_stream, "wb") as stream: _png.write_png(img, stream, metadata=full_metadata)
def refresh(self): renderer = fig.canvas.get_renderer() buffer = np.array( np.frombuffer(get_buffer(renderer), dtype=np.uint32), copy=True) buffer = buffer.reshape((renderer.height, renderer.width)) if self.last_buffer is not None: diff = buffer != self.last_buffer if not np.any(diff): output = np.zeros((1, 1)) else: output = np.where(diff, buffer, 0) else: output = buffer self.png_buffer.reset() self.png_buffer.truncate() _png.write_png(output.tostring(), output.shape[1], output.shape[0], self.png_buffer) self.last_buffer = buffer
def get_diff_image(self): if self._png_is_old: # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. buff = np.frombuffer(self.get_renderer().buffer_rgba(), dtype=np.uint32) buff.shape = (self._renderer.height, self._renderer.width) if not self._force_full: last_buffer = np.frombuffer(self._last_renderer.buffer_rgba(), dtype=np.uint32) last_buffer.shape = (self._renderer.height, self._renderer.width) diff = buff != last_buffer output = np.where(diff, buff, 0) else: output = buff # Clear out the PNG data buffer rather than recreating it # each time. This reduces the number of memory # (de)allocations. self._png_buffer.truncate() self._png_buffer.seek(0) # TODO: We should write a new version of write_png that # handles the differencing inline _png.write_png(output.tostring(), output.shape[1], output.shape[0], self._png_buffer) # Swap the renderer frames self._renderer, self._last_renderer = (self._last_renderer, self._renderer) self._force_full = False self._png_is_old = False return self._png_buffer.getvalue()
def get_diff_image(self): if self._png_is_old: renderer = self.get_renderer() # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32).reshape( (renderer.height, renderer.width))) # If any pixels have transparency, we need to force a full # draw as we cannot overlay new on top of old. pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4, )) if self._force_full or np.any(pixels[:, :, 3] != 255): self.set_image_mode('full') output = buff else: self.set_image_mode('diff') last_buffer = (np.frombuffer(self._last_renderer.buffer_rgba(), dtype=np.uint32).reshape( (renderer.height, renderer.width))) diff = buff != last_buffer output = np.where(diff, buff, 0) # TODO: We should write a new version of write_png that # handles the differencing inline buff = _png.write_png( output.view(dtype=np.uint8).reshape(output.shape + (4, )), None, compression=6, filter=_png.PNG_FILTER_NONE) # Swap the renderer frames self._renderer, self._last_renderer = (self._last_renderer, renderer) self._force_full = False self._png_is_old = False return buff
def get_diff_image(self): if self._png_is_old: renderer = self.get_renderer() # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. buff = np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) buff.shape = (renderer.height, renderer.width) # If any pixels have transparency, we need to force a full # draw as we cannot overlay new on top of old. pixels = buff.view(dtype=np.uint8).reshape(buff.shape + (4,)) if self._force_full or np.any(pixels[:, :, 3] != 255): self.set_image_mode('full') output = buff else: self.set_image_mode('diff') last_buffer = np.frombuffer(self._last_renderer.buffer_rgba(), dtype=np.uint32) last_buffer.shape = (renderer.height, renderer.width) diff = buff != last_buffer output = np.where(diff, buff, 0) # TODO: We should write a new version of write_png that # handles the differencing inline buff = _png.write_png( output.view(dtype=np.uint8).reshape(output.shape + (4,)), None, compression=6, filter=_png.PNG_FILTER_NONE) # Swap the renderer frames self._renderer, self._last_renderer = ( self._last_renderer, renderer) self._force_full = False self._png_is_old = False return buff
def write_trailer(self): renderer = self.renderer if hasattr(renderer._renderer, 'write_png'): # Old version of matplotlib: renderer._renderer.write_png(self.filename) else: from matplotlib import _png # buffer_rgba does not accept arguments from version 1.2.0 # https://github.com/matplotlib/matplotlib/commit/f4fee350f9f import matplotlib if LooseVersion(matplotlib.__version__) < '1.2.0': _png.write_png(renderer.buffer_rgba(0, 0), renderer.width, renderer.height, self.filename, 72) else: x = renderer.buffer_rgba() try: _png.write_png(x, self.w, self.h, self.filename, 72) except (TypeError, ValueError): x = np.frombuffer(x, np.uint8).reshape( (int(self.h), int(self.w), 4)) _png.write_png(x, self.filename, 72)
def write_png(self, fname): """Write the image to png file with fname""" im = self.make_image() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, fname)
def draw_image(self, gc, x, y, im, transform=None): # docstring inherited h, w = im.shape[:2] if w == 0 or h == 0: return attrib = {} clipid = self._get_clip(gc) if clipid is not None: # Can't apply clip-path directly to the image because the # image has a transformation, which would also be applied # to the clip-path self.writer.start('g', attrib={'clip-path': 'url(#%s)' % clipid}) oid = gc.get_gid() url = gc.get_url() if url is not None: self.writer.start('a', attrib={'xlink:href': url}) if rcParams['svg.image_inline']: bytesio = io.BytesIO() _png.write_png(im, bytesio) oid = oid or self._make_id('image', bytesio.getvalue()) attrib['xlink:href'] = ( "data:image/png;base64,\n" + base64.b64encode(bytesio.getvalue()).decode('ascii')) else: self._imaged[self.basename] = (self._imaged.get(self.basename, 0) + 1) filename = '%s.image%d.png' % (self.basename, self._imaged[self.basename]) _log.info('Writing image file for inclusion: %s', filename) _png.write_png(im, filename) oid = oid or 'Im_' + self._make_id('image', filename) attrib['xlink:href'] = filename attrib['id'] = oid if transform is None: w = 72.0 * w / self.image_dpi h = 72.0 * h / self.image_dpi self.writer.element('image', transform=generate_transform([ ('scale', (1, -1)), ('translate', (0, -h)) ]), x=short_float_fmt(x), y=short_float_fmt(-(self.height - y - h)), width=short_float_fmt(w), height=short_float_fmt(h), attrib=attrib) else: alpha = gc.get_alpha() if alpha != 1.0: attrib['opacity'] = short_float_fmt(alpha) flipped = (Affine2D().scale(1.0 / w, 1.0 / h) + transform + Affine2D().translate(x, y).scale(1.0, -1.0).translate( 0.0, self.height)) attrib['transform'] = generate_transform([('matrix', flipped.frozen())]) self.writer.element('image', width=short_float_fmt(w), height=short_float_fmt(h), attrib=attrib) if url is not None: self.writer.end('a') if clipid is not None: self.writer.end('g')
def write_png(self, fname): """Write the image to png file with fname""" im = self.make_image() _png.write_png(im, fname)
def write_png(self, fname): """Write the image to png file with fname""" im = self.to_rgba(self._A, bytes=True, norm=True) _png.write_png(im, fname)
def write_png(self, fname): """Write the image to png file with fname""" im = self.to_rgba(self._A, bytes=True, norm=False) _png.write_png(im, fname)