使用PIL使所有的白色像素透明?
我试图使用Python图像库使所有的白色像素透明。 (我是一个C黑客试图学习Python,所以要温柔)我有转换工作(至less像素值看起来是正确的),但我不知道如何将列表转换为缓冲区重新创build图片。 这是代码
img = Image.open('img.png') imga = img.convert("RGBA") datas = imga.getdata() newData = list() for item in datas: if item[0] == 255 and item[1] == 255 and item[2] == 255: newData.append([255, 255, 255, 0]) else: newData.append(item) imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1) imgb.save("img2.png", "PNG")
您需要进行以下更改:
- 附加一个元组
(255, 255, 255, 0)
而不是列表[255, 255, 255, 0]
- 使用
img.putdata(newData)
这是工作代码:
from PIL import Image img = Image.open('img.png') img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: if item[0] == 255 and item[1] == 255 and item[2] == 255: newData.append((255, 255, 255, 0)) else: newData.append(item) img.putdata(newData) img.save("img2.png", "PNG")
您也可以使用像素访问模式来就地修改图像:
from PIL import Image img = Image.open('img.png') img = img.convert("RGBA") pixdata = img.load() width, height = image.size for y in xrange(height): for x in xrange(width): if pixdata[x, y] == (255, 255, 255, 255): pixdata[x, y] = (255, 255, 255, 0) img.save("img2.png", "PNG")
import Image import ImageMath def distance2(a, b): return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]) def makeColorTransparent(image, color, thresh2=0): image = image.convert("RGBA") red, green, blue, alpha = image.split() image.putalpha(ImageMath.eval("""convert(((((t - d(c, (r, g, b))) >> 31) + 1) ^ 1) * a, 'L')""", t=thresh2, d=distance2, c=color, r=red, g=green, b=blue, a=alpha)) return image if __name__ == '__main__': import sys makeColorTransparent(Image.open(sys.argv[1]), (255, 255, 255)).save(sys.argv[2]);