• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python _png.write_png函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib._png.write_png函数的典型用法代码示例。如果您正苦于以下问题:Python write_png函数的具体用法?Python write_png怎么用?Python write_png使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了write_png函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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}")
开发者ID:adnanb59,项目名称:matplotlib,代码行数:33,代码来源:backend_pgf.py


示例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()
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:32,代码来源:backend_webagg.py


示例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)
开发者ID:Creence,项目名称:matplotlib,代码行数:27,代码来源:compare.py


示例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)
开发者ID:andsild,项目名称:PSB,代码行数:7,代码来源:tryplot.py


示例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)
开发者ID:Eric89GXL,项目名称:matplotlib,代码行数:29,代码来源:compare.py


示例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,
                )
开发者ID:mhoffman,项目名称:kmos,代码行数:25,代码来源:png.py


示例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
开发者ID:podhmo,项目名称:individual-sandbox,代码行数:31,代码来源:serve_figure.py


示例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
开发者ID:bcongdon,项目名称:matplotlib,代码行数:25,代码来源:backend_agg.py


示例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
开发者ID:danielgrassinger,项目名称:yt_new_frontend,代码行数:8,代码来源:png_writer.py


示例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')
开发者ID:mwiebe,项目名称:matplotlib,代码行数:54,代码来源:backend_svg.py


示例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
开发者ID:08s011003,项目名称:nupic,代码行数:11,代码来源:backend_agg.py


示例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)
开发者ID:SungSingSong,项目名称:matplotlib,代码行数:11,代码来源:image.py


示例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)
开发者ID:JConwayAWT,项目名称:PGSS14CC,代码行数:11,代码来源:png.py


示例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)
开发者ID:DanHickstein,项目名称:matplotlib,代码行数:15,代码来源:backend_agg.py


示例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
开发者ID:7924102,项目名称:matplotlib,代码行数:16,代码来源:backend_agg.py


示例16: draw_image

    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>")
开发者ID:mattfoster,项目名称:matplotlib,代码行数:46,代码来源:backend_svg.py


示例17: get_diff_image

    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()
开发者ID:NICKLAB,项目名称:matplotlib,代码行数:45,代码来源:backend_webagg_core.py


示例18: draw_image

    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}")
开发者ID:717524640,项目名称:matplotlib,代码行数:18,代码来源:backend_pgf.py


示例19: 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

        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
开发者ID:mspacek,项目名称:matplotlib,代码行数:19,代码来源:backend_agg.py


示例20: save_diff_image

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)
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:41,代码来源:compare.py



注:本文中的matplotlib._png.write_png函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python _pylab_helpers.Gcf类代码示例发布时间:2022-05-27
下一篇:
Python _png.read_png_int函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap