Search code examples
objective-ccifilterciimage

How to combine the color channels and alpha channel from two CIImage?


I have a CIImage from YUV data without alpha plane, and a gray scaled CIImage. I want to use the second image as the alpha plane. Currently, gpt tells me to use CISourceOverCompositing filter, but it seems that this filter will blend the color of the second image's color. If I convert the gray scaled image into a black mask (0, 0, 0, alpha), then this filter will use black as "background color". However, I just want to replace the color instead of blend it with another color.


Solution

  • You can blend your color image with a transparent image, using the grayscale image as a mask:

    CIImage* clearBackground = [[CIImage clearImage] imageByCroppingToRect:colorImage.extent];
    
    CIFilter* blendFilter = [CIFilter filterWithName:@"CIBlendWithMask"];
    [blendFilter setValue:colorImage forKey:kCIInputImageKey];
    [blendFilter setValue:clearBackground forKey:kCIInputBackgroundImageKey];
    [blendFilter setValue:grayscaleImage forKey:kCIInputMaskImageKey];
    
    CIImage* output = [blendFilter outputImage];