v9.1.1
Menu

Alpha Matte Compositing

mediumPROImage MattingMattingCV: Computational Photography

Implement alpha compositing for foreground/background blending, a key technique in image matting. This process involves combining a foreground image with a background image using a matte, which is a grayscale image defining the opacity of the foreground.

The matte, represented by α\alpha, is used to control the blending of the foreground and background colors. The compositing equation is based on the principle of linear blending, where the resulting color is a weighted sum of the foreground and background colors.

  1. Define the foreground, background, and matte images.
  2. Apply the compositing equation to each pixel.
C=αF+(1−α)BC = \alpha F + (1 - \alpha) B

Return the composited image with the same (H,W,3)(H, W, 3) shape, stored as 8-bit unsigned integers (uint8). Fractional values are truncated, not rounded: 127.5127.5 becomes 127127.

This technique is widely used in digital image editing.

Example

Input
foreground = person image
background = beach scene
alpha = person matte (1 inside, 0 outside)
Output
Person composited onto beach
Reasoning
  • Inputs: foreground and background are H×W×3H \times W \times 3 RGB images with values 0 to 255; alpha is an H×WH \times W matte, one opacity per pixel: 11 on the person, 00 on the beach, fractional along hair and soft edges.
  • Every pixel follows C=αF+(1−α)BC = \alpha F + (1-\alpha) B, with that pixel's single α\alpha weighting all three colour channels.
  • Take one edge pixel: red foreground F=(255,0,0)F = (255, 0, 0), green background B=(0,255,0)B = (0, 255, 0), α=0.5\alpha = 0.5. Then C=(127.5, 127.5, 0)C = (127.5,\ 127.5,\ 0), and stored as 8-bit integers with the fraction dropped it becomes (127,127,0)(127, 127, 0), a dark yellow halfway between.
  • With α=1\alpha = 1 that pixel is exactly FF, [255, 0, 0]; with α=0\alpha = 0 it is exactly BB.
  • Output: an H×W×3H \times W \times 3 image, the person composited onto beach: person pixels where the matte is 1, beach where it is 0, smooth blends in between. Notice α+(1−α)=1\alpha + (1-\alpha) = 1, so a blend never leaves the 0 to 255 range.

Constraints

  • foreground: Foreground image (H, W, 3)
  • background: Background image (H, W, 3)
  • alpha: Alpha matte (H, W) in [0, 1]
  • Return: Composited image

More from CV: Computational Photography

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.