使用 Python PIL 库将具有透明背景的图像垂直淡化为透明
Vertically fade an image with transparent background to transparency using Python PIL library
所以我想淡出已经有透明背景的图像。
我在 this question 中找到了非透明图像的解决方案,但它不适用于具有透明背景的图像。那么我该怎么做才能使具有透明背景的图像垂直淡化为透明?
比如我要 this image become 这个,背景还是透明的
这是我用来创建透明图像的代码
bg = Image.new("RGBA", (width, height), (r,g,b,inputBgAlpha))
...
bg.paste(deviceBg, devicePadding, mask=deviceBg)
下面是我试过的。它会导致背景有颜色而不是透明。
#
arr = numpy.array(bg)
alpha = arr[:, :, 3]
n = len(alpha)
alpha[:] = numpy.interp(numpy.arange(n), [0, 0.55*n, 0.05*n, n], [255, 255, 0, 0])[:,numpy.newaxis]
bg = Image.fromarray(arr, mode='RGBA')
对代码稍作改动 here 即可使其正常运行 :)
from PIL import Image
im = Image.open('bird.jpg')
width, height = im.size
pixels = im.load()
for y in range(int(height*.55), int(height*.75)):
for x in range(width):
alpha = pixels[x, y][3]-int((y - height*.55)/height/.20 * 255)
if alpha <= 0:
alpha = 0
pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (0,)
bg.save('birdfade.png')
所以我想淡出已经有透明背景的图像。
我在 this question 中找到了非透明图像的解决方案,但它不适用于具有透明背景的图像。那么我该怎么做才能使具有透明背景的图像垂直淡化为透明?
比如我要
这是我用来创建透明图像的代码
bg = Image.new("RGBA", (width, height), (r,g,b,inputBgAlpha))
...
bg.paste(deviceBg, devicePadding, mask=deviceBg)
下面是我试过的。它会导致背景有颜色而不是透明。
#
arr = numpy.array(bg)
alpha = arr[:, :, 3]
n = len(alpha)
alpha[:] = numpy.interp(numpy.arange(n), [0, 0.55*n, 0.05*n, n], [255, 255, 0, 0])[:,numpy.newaxis]
bg = Image.fromarray(arr, mode='RGBA')
对代码稍作改动 here 即可使其正常运行 :)
from PIL import Image
im = Image.open('bird.jpg')
width, height = im.size
pixels = im.load()
for y in range(int(height*.55), int(height*.75)):
for x in range(width):
alpha = pixels[x, y][3]-int((y - height*.55)/height/.20 * 255)
if alpha <= 0:
alpha = 0
pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
for x in range(width):
pixels[x, y] = pixels[x, y][:3] + (0,)
bg.save('birdfade.png')