开发者

Need help understanding Alpha Channels

开发者 https://www.devze.com 2023-02-07 06:00 出处:网络
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.开发者_如何转开发

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消