v9.1.1
Menu

Alpha Compositing

easyFREEImage MattingMattingCV: Computational Photography

Composite a foreground image over a background using an alpha matte.

Alpha compositing is the fundamental operation for combining images with transparency. The compositing equation blends foreground and background based on the alpha (opacity) value:

C=α⋅F+(1−α)⋅BC = \alpha \cdot F + (1 - \alpha) \cdot B

where:

  • CC is the composited output color
  • FF is the foreground color
  • BB is the background color
  • α\alpha is the alpha/opacity value in [0, 1]

For each RGB channel:

  • α=1\alpha = 1: fully foreground (opaque)
  • α=0\alpha = 0: fully background (transparent)
  • α=0.5\alpha = 0.5: 50% blend of both

This operation is applied independently to each color channel.

Example

Input
composite((255, 0, 0), (0, 0, 255), 0.5)
Output
(128, 0, 128)
Reasoning
  • Inputs: foreground is pure red (255,0,0)(255, 0, 0), background is pure blue (0,0,255)(0, 0, 255), and alpha =0.5= 0.5 means the foreground is half opaque, so each colour gets equal weight: α=0.5\alpha = 0.5 and 1−α=0.51 - \alpha = 0.5.
  • Red: CR=0.5⋅255+0.5⋅0=127.5C_R = 0.5 \cdot 255 + 0.5 \cdot 0 = 127.5, which rounds to the nearest integer 128128.
  • Green: neither colour has any green, so CG=0.5⋅0+0.5⋅0=0C_G = 0.5 \cdot 0 + 0.5 \cdot 0 = 0.
  • Blue: CB=0.5⋅0+0.5⋅255=127.5C_B = 0.5 \cdot 0 + 0.5 \cdot 255 = 127.5, which rounds to 128128.
  • Output: the three channels together give (128, 0, 128), a medium purple: half red, half blue, as integers in [0,255][0, 255].
  • Notice that each channel is blended on its own, and the two weights always sum to 11, so the result stays inside the range of the inputs. With alpha =1= 1 you get the foreground back unchanged; with alpha =0= 0 you get the background.

Constraints

  • foreground: RGB tuple of integers [0, 255]
  • background: RGB tuple of integers [0, 255]
  • alpha: float in range [0, 1]
  • Return composited RGB as tuple of integers (rounded)

Learn this in

More from CV: Computational Photography

solution.py

Test results

Sign in to run your code against the test cases.