使用Python PIL库将图像垂直淡化为透明 [英] Vertically fade image to transparency using Python PIL library

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

问题描述

我看过教程,其他stackoverflow问题和PIL文档本身,但是我仍然不确定如何去做.

I have looked at tutorials, other stackoverflow questions and the PIL documentation itself, but I'm still still not sure how to do it.

我想在y轴下方大约55%处开始垂直淡入图像,并在大约75%处使图像完全透明.即使最后25%左右应该是完全透明的,我也必须保留图像的整个高度,这一点很重要.

I'd like to start fading an image vertically at approximately 55% down the y-axis, and have the image completely transparent at approximately 75%. It's important that I preserve the full height of the image, even though the last 25% or so should be completely transparent.

这可能与PIL有关吗?

Is this possible to do with PIL?

推荐答案

确定是可行的.

让我们假设您从一幅不透明的图像开始(否则,您的问题会模棱两可).

Let's assume that you're starting off with an image with no transparency (because otherwise, your question is ambiguous).

步骤1:添加Alpha平面.这只是 putalpha ,除非您要处理的是非平面图像,在这种情况下,您需要先将其转换为RGB或L.

Step 1: Add an alpha plane. That's just putalpha, unless you're dealing with a non-planar image, in which case you'll need to convert it to RGB or L first.

第2步:使用第3步:没有第3步.除非您算保存图像.在这种情况下,确定,第3步将保存图像.

Step 3: There is no step 3. Unless you count saving the image. In which case, OK, step 3 is saving the image.

from PIL import Image

im = Image.open('bird.jpg')
im.putalpha(255)
width, height = im.size
pixels = im.load()
for y in range(int(height*.55), int(height*.75)):
    alpha = 255-int((y - height*.55)/height/.20 * 255)
    for x in range(width):
        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,)
im.save('birdfade.png')

此处,alpha值从255线性下降到0;如果您希望它根据不同的曲线下降,或者您使用的是RGB16而不是RGB8,或者您使用的是L而不是RGB,那么您应该能够弄清楚如何更改它.

Here the alpha drops off linearly from 255 to 0; it you want it to drop off according to a different curve, or you're using RGB16 instead of RGB8, or you're using L instead of RGB, you should be able to figure out how to change it.

如果要更快地执行此操作,可以在步骤2中使用numpy而不是Python循环.或者可以反转步骤1和2-预先构造一个Alpha平面,并将其传递给putalpha而不是255.或者……由于这是我躺在的最大图像上不到半秒的时间,因此我不必太担心性能,除非您必须做一百万个并且想要一个更快的版本.

If you want to do this faster, you can use numpy instead of a Python loop for step 2. Or you can reverse steps 1 and 2—construct an alpha plane in advance, and apply it all at once by passing it to putalpha instead of 255. Or… Since this took under half a second on the biggest image I had lying around, I'm not too worried about performance, unless you have to do a million of them and you want a faster version.

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

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