Method for converting PNGs to premultiplied alpha [closed]
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this questionLooking for some kind of simple tool or process for Windows that will let me convert one or more standard PNGs to premultiplied alpha.
Command line tools are ideal; I have easy access to PIL (Python Imaging Library) and Imagemagick, but will install another tool if it makes life easier.
Thanks!
A more complete version of the cssndrx answer, using slicing in numpy to improve speed:
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())
Et voila !
Using ImageMagick, as requested:
convert in.png -write mpr:image -background black -alpha Remove mpr:image -compose Copy_Opacity -composite out.png
Thanks @mf511 for the update.
I just released a bit of code in Python and in C that does what you are looking for. It's on github: http://github.com/maxme/PNG-Alpha-Premultiplier
The Python version is based on the cssndrx response. C version is based on libpng.
It should be possible to do this through PIL. Here is a rough outline of the steps:
1) Load the image and convert to numpy array
im = Image.open('myimage.png').convert('RGBA')
matrix = numpy.array(im)
2) Modify the matrix in place. The matrix is a list of lists of the pixels within each row. Pixels are represented as [r, g, b, a]. Write your own function to convert each [r, g, b, a] pixel to the [r, g, b] value you desire.
3) Convert the matrix back to an image using
new_im = Image.fromarray(matrix)
Using PIL only:
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)
精彩评论