使用Python PIL库将具有透明背景的图像垂直淡化为透明 [英] Vertically fade an image with transparent background to transparency using Python PIL library

查看:453
本文介绍了使用Python PIL库将具有透明背景的图像垂直淡化为透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想淡出背景已经透明的图像.

So I would like to fade out an image which already had an transparent background.

我在此问题中找到了非透明图像的解决方案,但不适用于带有透明背景.那么如何使具有透明背景的图像垂直淡化为透明呢?

I've found solution for non-transparent image in this question, but it does not work for the image with transparent background. So how can I do to vertically fade an image with transparent background to transparency?

例如,我要此图片变为这仍然具有透明背景.

For example, I want this image become this one, which still have transparent background.

这是我用来创建透明图像的代码

Here is the code I used to create the transparent image

bg = Image.new("RGBA", (width, height), (r,g,b,inputBgAlpha))
...
bg.paste(deviceBg, devicePadding, mask=deviceBg)

以下是我尝试过的.这样会导致背景变成彩色,而不是透明的.

And the following is what I tried. It results in a background with color instead of transprent.

# https://stackoverflow.com/a/19236775/2603230
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')

推荐答案

在代码此处进行一些更改作品:)

A little change on code here can make it works :)

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')

这篇关于使用Python PIL库将具有透明背景的图像垂直淡化为透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆