【问题标题】:Method for converting PNGs to premultiplied alpha [closed]将PNG转换为预乘alpha的方法[关闭]
【发布时间】:2011-09-29 07:12:29
【问题描述】:

Windows 寻找某种简单的工具或流程,让我可以将一个或多个标准 PNG 转换为预乘 alpha。

命令行工具是理想的;我可以轻松访问 PIL(Python Imaging Library)和 Imagemagick,但如果它能让生活更轻松,我会安装另一个工具。

谢谢!

【问题讨论】:

    标签: png imagemagick python-imaging-library premultiplied-alpha


    【解决方案1】:

    更完整的cssndrx答案版本,在numpy中使用切片来提高速度:

    import Image
    import numpy
    
    im = Image.open('myimage.png').convert('RGBA')
    a = numpy.fromstring(im.tostring(), dtype=numpy.uint8)
    alphaLayer = a[3::4] / 255.0
    a[::4]  *= alphaLayer
    a[1::4] *= alphaLayer
    a[2::4] *= alphaLayer
    
    im = Image.fromstring("RGBA", im.size, a.tostring())
    

    瞧!

    【讨论】:

      【解决方案2】:

      根据要求使用 ImageMagick:

      convert in.png -write mpr:image -background black -alpha Remove mpr:image -compose Copy_Opacity -composite out.png
      

      感谢@mf511 的更新。

      【讨论】:

      • 这不会保留 alpha 通道,它只是将所有通道与 alpha 相乘,然后似乎完全丢弃了 alpha。我在 ImageMagick 7.0.5-4 Q16 上试过这个。
      • 是的,但以前有效。使用它作为替代:convert in.png -background black -alpha Remove in.png -compose Copy_Opacity -composite out.png
      • 第二个命令效果很好!谢谢。
      【解决方案3】:

      我刚刚发布了一些 Python 和 C 代码,可以满足您的需求。在github上:http://github.com/maxme/PNG-Alpha-Premultiplier

      Python 版本基于 cssndrx 响应。 C版本基于libpng。

      【讨论】:

      • 非常感谢。 :) 选择这个答案是因为我发现代码比 madlag 的示例更容易理解,尽管可能没有那么聪明。
      • 我喜欢他的代码检查图像是否被预乘的事实。 OP 没有要求,但仍然非常好。
      • 难怪python版本很慢——你循环遍历每一个像素。 Francois 的 python 解决方案要快得多。
      【解决方案4】:

      应该可以通过 PIL 做到这一点。大致步骤如下:

      1) 加载图片并转换为numpy数组

          im = Image.open('myimage.png').convert('RGBA')
          matrix = numpy.array(im)
      

      2) 就地修改矩阵。该矩阵是每行内像素列表的列表。像素表示为 [r, g, b, a]。编写您自己的函数,将每个 [r, g, b, a] 像素转换为您想要的 [r, g, b] 值。

      3) 使用

      将矩阵转换回图像
          new_im = Image.fromarray(matrix)
      

      【讨论】:

        【解决方案5】:

        仅使用 PIL:

        def premultiplyAlpha(img):
            # fake transparent image to blend with
            transparent = Image.new("RGBA", img.size, (0, 0, 0, 0))
            # blend with transparent image using own alpha
            return Image.composite(img, transparent, img)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-31
          • 2010-09-08
          • 2018-10-11
          相关资源
          最近更新 更多