ColorMask

The ColorMask kernel applies a color mask to an input image. It has red, green, and blue parameters as well as a uniform parameter and options to disable each one.

// Copyright (c) 2024 The Foundry Visionmongers Ltd.  All Rights Reserved.

// ColourMask kernel. Masks each color channel of the source image with the specified red, green, and blue intensity values.
kernel ColorMaskKernel : ImageComputationKernel<ePixelWise> {
  Image<eRead, eAccessPoint, eEdgeClamped> src;  // Input for the current point in the iteration space with edge clamping.
  Image<eWrite, eAccessPoint> dst;  // Output for the current point in the iteration space.

  // Parameters that are made available as knobs.
  param:
    float red;  // The red mask.
    float green;  // The green mask.
    float blue;  // The blue mask.
    float alpha;  // The alpha mask.
    float uniform;  // Uniform mask for all masks.
    bool enableRed;  // Enable red masking.
    bool enableGreen;  // Enable green masking.
    bool enableBlue;  // Enable blue masking.
    bool enableAlpha;  // Enable alpha masking.
    bool enableUniform;  // Enable uniform masking.

  // Local variables that are initialised in init() and used for all pixels.
  local:
    float4 maskColors;  // The computed mask values.

  // Parameters are initialised and given values and labels.
  void define() {
    defineParam(red, "Red Mask", 1.0f);
    defineParam(green, "Green Mask", 1.0f);
    defineParam(blue, "Blue Mask", 1.0f);
    defineParam(alpha, "Alpha Mask", 1.0f);
    defineParam(uniform, "Uniform Mask", 1.0f);
    defineParam(enableRed, "Enable Red Mask", true);
    defineParam(enableGreen, "Enable Green Mask", true);
    defineParam(enableBlue, "Enable Blue Mask", true);
    defineParam(enableAlpha, "Enable Alpha Mask", true);
    defineParam(enableUniform, "Enable Uniform Mask", true);
  }

  // Run once before any calls to process().
  void init() {
    // Initialize the mask colors to 1.0f (no masking).
    maskColors = float4(1.0f, 1.0f, 1.0f, 1.0f);

    // Apply the mask values based on the boolean parameters.
    if (enableRed) {
      maskColors.x = red;
    }
    if (enableGreen) {
      maskColors.y = green;
    }
    if (enableBlue) {
      maskColors.z = blue;
    }
    if (enableAlpha) {
      maskColors.w = alpha;
    }

    // Apply uniform masking if enabled.
    if (enableUniform) {
      maskColors *= uniform;
    }
  }

  // Runs over all the pixel positions of the input image.
  void process() {
    // Read the input image.
    const float4 input = src();

    // Mask the pixel based on the parameters and output the result.
    dst() = input * maskColors;
  }
};