1

I was wondering if it is possible to binarize an image (convert to black and white only) with Core Image?

I made it with OpenCV and GPUImage, but would prefer it to use Apple Core Image, if that's possible

1
  • 2
    (Forgive me. I posted this comment as an answer. Oops.) Yes. Check for CIPhotoEffectMono (developer.apple.com/library/content/documentation/…). I also wrote a custom CIColorKernel (GLSL code) that "fades" to black and white. I'll post both as an answer in a few minutes.
    – user7014451
    Feb 15, 2017 at 15:56

5 Answers 5

6

You can use MetalPerformanceShaders for that. And the CIImageProcessingKernel. https://developer.apple.com/documentation/coreimage/ciimageprocessorkernel

Here is the code of the class needed.

 class ThresholdImageProcessorKernel: CIImageProcessorKernel {
    static let device = MTLCreateSystemDefaultDevice()
    override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String : Any]?, output: CIImageProcessorOutput) throws {
        guard
            let device = device,
            let commandBuffer = output.metalCommandBuffer,
            let input = inputs?.first,
            let sourceTexture = input.metalTexture,
            let destinationTexture = output.metalTexture,
            let thresholdValue = arguments?["thresholdValue"] as? Float else  {
                return
        }

        let threshold = MPSImageThresholdBinary(
            device: device,
            thresholdValue: thresholdValue,
            maximumValue: 1.0,
            linearGrayColorTransform: nil)

        threshold.encode(
            commandBuffer: commandBuffer,
            sourceTexture: sourceTexture,
            destinationTexture: destinationTexture)
    }
}

And this is how you can use it:

    let context = CIContext(options: nil)

            if let binaryCIImage = try? ThresholdImageProcessorKernel.apply(
                withExtent: croppedCIImage.extent,
                inputs: [croppedCIImage],
                arguments: ["thresholdValue": Float(0.2)]) {
                if let cgImage = context.createCGImage(binaryCIImage, from: binary.extent) {
                    DispatchQueue.main.async {
                        let resultingImage = UIImage(cgImage: cgImage)
                        if resultingImage.size.width > 100 {
                            print("Received an image \(resultingImage.size)")
                        }
                    }
                }
            }
2
  • Worked great for me although I needed to change binary.extent to binaryCIImage.extent- hope this is correct? Also, seems insane that not one developer at Apple has thought to include a thresholding filter like this, despite there being literally hundreds of filters for everything else you could ever need :/
    – bcl
    Jun 25, 2020 at 18:17
  • Work great for me. Thank you
    – Tuan Do
    Nov 16, 2020 at 1:32
5

Yes. You have at least two options, CIPhotoEffectMono or a small custom CIColorKernel.

CIPhotoEffectMono:

func createMonoImage(image:UIImage) -> UIImage {
    let filter = CIFilter(name: "CIPhotoEffectMono")
    filter!.setValue(CIImage(image: image), forKey: "inputImage")
    let outputImage = filter!.outputImage
    let cgimg = ciCtx.createCGImage(outputImage!, from: (outputImage?.extent)!)
    return UIImage(cgImage: cgimg!)
}

Note, I'm writing this quickly, you may need to tighten up things for nil returns.

CIColorKernel:

The FadeToBW GLSL (0.0 factor full color, 1.0 factor is no color):

kernel vec4 fadeToBW(__sample s, float factor) {
    vec3 lum = vec3(0.299,0.587,0.114);
    vec3 bw = vec3(dot(s.rgb,lum));
    vec3 pixel = s.rgb + (bw - s.rgb) * factor;
    return vec4(pixel,s.a);
}

The code below opens this as a file called FadeToBW.cikernel. You can also post this as a String directly into the openKernelFile call.

The Swift code:

func createMonoImage(image:UIImage, inputColorFade:NSNumber) -> UIImage {
    let ciKernel = CIColorKernel(string: openKernelFile("FadeToBW"))
    let extent = image.extent
    let arguments = [image, inputColorFade]        
    let outputImage = ciKernel.applyWithExtent(extent, arguments: arguments)
    let cgimg = ciCtx.createCGImage(outputImage!, from: (outputImage?.extent)!)
    return UIImage(cgImage: cgimg!)
}

Again, add some guards, etc.

3
  • Hi dfd, thanks a lot for you quick response! When trying the custom-kernel-solution, I get "fatal error: unexpectedly found nil while unwrapping an Optional value" after applying the kernel - do you have an idea, why?
    – Pascal
    Feb 15, 2017 at 17:05
  • I used the following code: let ciKernel = CIColorKernel(string: "...")! let image = CIImage.init(image: inputImage)! let extent = image.extent let arguments = [inputImage, inputColorFade] let outputImage = ciKernel.apply(withExtent: extent, arguments: arguments)! let context = CIContext(options:nil) let cgimg = context.createCGImage(outputImage, from: (outputImage.extent)) return UIImage(cgImage: cgimg!)
    – Pascal
    Feb 15, 2017 at 17:08
  • 2
    Ah. My fault. Untested code copied from a working app. It's not inputImage but image. I'm editing my answer. For testing purposes, put a break point on the apply(withExtent:arguments) and check that nothing else is nil.
    – user7014451
    Feb 15, 2017 at 17:44
1

I have had success by converting it to greyscale using CIPhotoEffectMono or equivalent, and then using CIColorControls with a ridiculously high inputContrast number (I used 10000). This effectively makes it black and white and thus binarized. Useful for those who don't want to mess with custom kernels.

Also, you can use an example like Apple's "Chroma Key" filter which uses Hue to filter, but instead of looking at Hue you just give the rules for binarizing the data (ie: when to set RGB all to 1.0 and when to set to 0.0).

https://developer.apple.com/documentation/coreimage/applying_a_chroma_key_effect

1

Found this thread from a Google search, and thought I'd mention that as of iOS 14 and OSX 11.0, CoreImage includes CIColorThreshold and CIColorThresholdOtsu filters (the latter using Otsu's method to calculate the threshold value from the image histogram)

See:

https://cifilter.io/CIColorThreshold/

https://cifilter.io/CIColorThresholdOtsu/

1
let outputImage = inputImage.applyingFilter("CIColorMonochrome",
                            parameters: [kCIInputColorKey: CIColor.white])

In you want to play with every out of 250 CIFilters please check this app out: https://apps.apple.com/us/app/filter-magic/id1594986951

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.