本文整理汇总了Python中matplotlib._png.write_png函数的典型用法代码示例。如果您正苦于以下问题:Python write_png函数的具体用法?Python write_png怎么用?Python write_png使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write_png函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_image
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"\[email protected]{%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"\[email protected]{%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}")
示例2: get_diff_image
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()
示例3: save_diff_image
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)
示例4: save
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)
示例5: save_diff_image
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)
示例6: write_trailer
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,
)
示例7: refresh
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
示例8: print_png
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
示例9: write_png_to_string
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
示例10: draw_image
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')
示例11: print_png
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
示例12: write_png
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)
示例13: write_trailer
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)
示例14: print_png
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)
示例15: print_png
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