Need help understanding Alpha Channels

人走茶凉 提交于 2019-12-24 17:15:09

问题


I have the RGB tuple of a pixel we'll call P.

(255, 0, 0) is the color of P with the alpha channel at 1.0.

With the alpha channel at 0.8, P's color becomes (255, 51, 51).

How can I get the color of the pixel that is influencing P's color?


回答1:


Let's start from the beginning. A pixel with alpha only makes sense when it is blended with something else. If you have an upper layer U with alpha and a lower layer L that is totally opaque, the equation is:

P = (alpha * U) + ((1.0 - alpha) * L)

Rearranging the formula, you obtain:

L = (P - (alpha * U)) / (1.0 - alpha)

Obviously the equation doesn't make sense when the alpha is 1.0, as you'd be dividing by zero.

Plugging your numbers in reveals that R=255, G=255, and B=255 for the pixel L.

It is almost universal that the lowest layer in an image will be all white (255,255,255) by convention.




回答2:


Just looking at the numbers you provided:

(1.0-0.8)*255 ~= 50.9 = 51

Where:

  • 1.0 is the maximum alpha intensity
  • 0.8 is the currently set alpha intensity
  • 255 is the maximum intensity of each of the RGB channels (the color of the background)

This fits the B and G channels of your example.

So, in the general case, it seems to be a simple weighted average between the channel value (either of RGB) and the background color (in your case, white -- 255). Alpha is being used as the weight.

Here's some Python code:

MIN_ALPHA=0.0
MAX_ALPHA=1.0
MIN_CH=0
MAX_CH=255
BG_VAL=255

def apply_alpha(old, alpha, bg=255):
    assert alpha >= MIN_ALPHA
    assert alpha <= MAX_ALPHA
    assert old >= MIN_CH
    assert old <= MAX_CH

    new = old*alpha + (MAX_ALPHA - alpha)*bg
    return new

if __name__ == '__main__':
    import sys
    old, alpha = map(float, sys.argv[1:])
    print apply_alpha(old, alpha)

And some output:

misha@misha-K42Jr:~/Desktop/stackoverflow$ python alpha.py 255 0.8
255.0
misha@misha-K42Jr:~/Desktop/stackoverflow$ python alpha.py 0 0.8
51.0

Try this for other examples (in particular, non-white backgrounds) -- it's probably that simple. If not, edit your answer with new examples, and I'll have another look.



来源:https://stackoverflow.com/questions/4840653/need-help-understanding-alpha-channels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!