颜色变为透明-以编程方式 [英] Color to transparency - programmatically

查看:159
本文介绍了颜色变为透明-以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可能知道专业图像编辑程序(如Photoshop)的色彩到透明"效果.效果如何?我想使用Python以编程方式为我的图像添加一些透明度(并且为了测试PIL,因为我可以检查生成的图像)​​.这种效果将用于一些分形的事物,所以这是我当前的代码:

you might know the "Color to transparency" effect of professional image editing programs like Photoshop. How is this effect done? I want to add some transparency to my images programmatically with Python (and for testing PIL, because I can check with generated images). This effect is going to be used for some fractal things, so here's my current code:

i = "i.png"
o = "o.png"

key = (0, 0, 0, 255)

from PIL import Image as I

_i = I.open(i)
_ii = _i.load()

_o = I.new("RGBA", _i.size)
_oo = _o.load()

for x in range(0, _i.size[0]): 
    for y in range(0, _i.size[1]): 
        col = list(_ii[x, y])
        for i in range(0, 4): 
            col[i] = abs(col[i] - key[i])
        _oo[x, y] = tuple(col)

_o.save(o)

我曾想过将两种颜色都减去,但最终得到黑色图像(丢失所有alpha值). 另一个想法是将原始颜色加倍,然后检查键是否较低,例如将两种颜色反向混合.

I thought of subtracting the both colors, but i end up with black images (loses all alpha). Another thought was to double the original color and check if the key is lower, like reverse-mixing the two colors.

那么,您有什么想法吗?

So, do you have any ideas?

编辑

>

此效果是使用GIMP的从颜色到透明度"功能实现的.我选择#FFF为透明,然后GIMP以某种方式使白色变为透明,而不先忽略像素的颜色.这就是我实际上想要做的,使图像中的颜色透明,就像图像中一样.

This effect was done with GIMP using it's "Color to transparency" function. I selected #FFF to be transparent and GIMP somehow made white to transparent, without ignoring the color of the pixel at first. This is, what I actually want to do, make a color in an image transparent, like in the image.

(我在第二张图像中添加了黑色背景,所以您知道它是透明的.原始图像与第一张图像一样,白色背景,周围是绿色,黑色中心)

(I added a black background to the second image, so you know it's transparent. The original image was just like the first one, white background, slightly green surrounding, black center)

推荐答案

如果您要用透明"像素替换给定颜色的像素,则需要(1)测试给定像素是否具有所需的颜色( 2)通过将alpha设置为0来将其设置为透明".类似的方法可以解决问题:

If you want to replace the pixel of a given color by "transparent" pixels, you have (1) to test if a given pixel has the required color (2) set it "transparent" by setting alpha to 0. Something like that would do the trick:

for x in range(0, _i.size[0]): 
    for y in range(0, _i.size[1]): 
        col = list(_ii[x, y])
        if col[0:3] == my_key_color[0:3]:
            _oo[x,y] = col[0:3]+(0,) # keep RGB, set A to 0
        else:
            _oo[x,y] = col

请注意,这是一个非常基本的解决方案,其中像素要么完全透明-要么保持原样.如果您希望获得更多的专业"效果,则可以对此进行一些细化...

Please note this is a very basic solution where a pixel is either fully transparent -- or leaved as-is. If you looking for more "professional" effect, you will have te refine this a little...

这篇关于颜色变为透明-以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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