Method for converting PNGs to premultiplied alpha [closed]

早过忘川 提交于 2019-11-30 14:11:22

问题


Looking 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!


回答1:


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.




回答2:


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 !




回答3:


Using ImageMagick, as requested:

convert in.png -background black -alpha Remove in.png -compose Copy_Opacity -composite out.png

Thanks @mf511 for the update.




回答4:


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)



回答5:


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)


来源:https://stackoverflow.com/questions/6591361/method-for-converting-pngs-to-premultiplied-alpha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!