過濾顏色

圖片中RGB < 0.2的顏色改變為黑色
剩餘顏色改為白色

kernel vec4 thresholdFilter(__sample textureColor) {
    if (textureColor.r < 0.2 && textureColor.g < 0.2 && textureColor.b < 0.2) {
        textureColor.rgb = vec3(0.0, 0.0, 0.0);
    } else {
        textureColor.rgb = vec3(1.0, 1.0, 1.0);
    }
    return textureColor;
}

Extension+UIImage

extension UIImage {
    /// 顏色過濾取黑色
    func applyCustomCIFilter() -> UIImage{
        let testImageView = UIImageView()
        testImageView.image = self
        guard let inputImage = testImageView.image else { return UIImage()}
        guard let ciInputImage = CIImage(image: inputImage) else { return UIImage() }
        let replaceGrayKernel = CIColorKernel( source:
                                                """
                                                    kernel vec4 thresholdFilter(__sample textureColor) {

                                                        if (textureColor.r < 0.2 && textureColor.g < 0.2 && textureColor.b < 0.2) {
                                                            textureColor.rgb = vec3(0.0, 0.0, 0.0);
                                                        } else {
                                                            textureColor.rgb = vec3(1.0, 1.0, 1.0);
                                                        }

                                                        return textureColor;
                                                    }
                                                    """
        )
        let ciImageFiltered = replaceGrayKernel!.apply(
            extent: ciInputImage.extent,
            arguments: [ciInputImage])

        let filteredImage = UIImage(ciImage: ciImageFiltered!)
        return filteredImage
    }
}

證件過濾

方便OCR等自動識別用

其他


Categorized in: