我正在寻找一种简单的工具或过程,能够在 Windows 上让我将一个或多个标准 PNG 转换为预乘 alpha。
命令行工具是理想的选择;我可以很容易地使用 PIL(Python Imaging Library)和 Imagemagick,但如果有其他更方便的工具,我也可以安装。
谢谢!
我正在寻找一种简单的工具或过程,能够在 Windows 上让我将一个或多个标准 PNG 转换为预乘 alpha。
命令行工具是理想的选择;我可以很容易地使用 PIL(Python Imaging Library)和 Imagemagick,但如果有其他更方便的工具,我也可以安装。
谢谢!
使用 ImageMagick,如所请求:
convert in.png -write mpr:image -background black -alpha Remove mpr:image -compose Copy_Opacity -composite out.png
感谢 @mf511 的更新。
使用numpy切片来提高速度的cssndrx答案的更完整版本:
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())
完成了!
使用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)
convert in.png -background black -alpha Remove in.png -compose Copy_Opacity -composite out.png
- mf511