How do I tell a CIKernel to produce an output image without an alpha channel?

616 Views Asked by At

I've written a custom kernel in Core Image:

outputImage = kernel.apply(extent: extent,
                           roiCallback: roiCallback,
                           arguments: [inputImage])!

static let kernel = CIKernel(source:"""
kernel vec4 process(sampler src) {
  vec4 pixel = sample(src, samplerTransform(destCoord()));
  return pixel;
}   
""")!

(This is a simple no-op kernel for illustration, not the actual one.)

The input is BGRA, but I want the output CIImage to be BGR (or RGB or any other order). Is this possible?

The reason I want to do this is that all alpha values in the input image are 1, so I don't want to waste memory (and processing time) storing millions of 1's in the output image as well, if I could skip it. My code is performance-sensitive, and doesn't work fast enough, so I'm looking for ways to optimise it.

In case it matters, I'm targeting iOS 11 and above.


I tried changing the code to:

kernel vec3 process(sampler src) {
  vec3 pixel = sample(src, samplerTransform(destCoord())).xyz;
  return pixel;
}

but I got an error:

invalid kernel return type; valid types are 'vec2' and 'vec4' 

As I-I pointed out in an answer, vec3 is not a valid return type, so this idea doesn't work. What does, then?

1

There are 1 best solutions below

1
On

According to Apple documentation the return type must be a vec 4, but it doesn't have to be an BGRA pixel or even a pixel:

A kernel routine gets called once for each pixel for the destination image. The routine must return a vec4 data type. Although this four-element vector typically contains pixel data, the vector is not required to represent a pixel

from: Writing Kernels