【发布时间】:2011-09-29 07:12:29
【问题描述】:
为 Windows 寻找某种简单的工具或流程,让我可以将一个或多个标准 PNG 转换为预乘 alpha。
命令行工具是理想的;我可以轻松访问 PIL(Python Imaging Library)和 Imagemagick,但如果它能让生活更轻松,我会安装另一个工具。
谢谢!
【问题讨论】:
标签: png imagemagick python-imaging-library premultiplied-alpha
为 Windows 寻找某种简单的工具或流程,让我可以将一个或多个标准 PNG 转换为预乘 alpha。
命令行工具是理想的;我可以轻松访问 PIL(Python Imaging Library)和 Imagemagick,但如果它能让生活更轻松,我会安装另一个工具。
谢谢!
【问题讨论】:
标签: png imagemagick python-imaging-library premultiplied-alpha
更完整的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())
瞧!
【讨论】:
根据要求使用 ImageMagick:
convert in.png -write mpr:image -background black -alpha Remove mpr:image -compose Copy_Opacity -composite out.png
感谢@mf511 的更新。
【讨论】:
convert in.png -background black -alpha Remove in.png -compose Copy_Opacity -composite out.png
我刚刚发布了一些 Python 和 C 代码,可以满足您的需求。在github上:http://github.com/maxme/PNG-Alpha-Premultiplier
Python 版本基于 cssndrx 响应。 C版本基于libpng。
【讨论】:
应该可以通过 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)
【讨论】:
仅使用 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)
【讨论】: