一尘不染

如何使用CIFilter在Swift中将UIImage转换为灰度?

swift

到目前为止,我正在为iOS应用程序构建扫描仪组件,并且将结果图像裁剪为正确的角度。现在,我需要将彩色图像转换为黑白“扫描”文档。

我尝试使用-“ CIPhotoEffectNoir”,但它的灰度更高,然后完全是黑白。我希望获得100%黑色和100%白色的全对比度图像。

我该如何实现?谢谢


阅读 367

收藏
2020-07-07

共1个答案

一尘不染

您可以使用CIColorControls并设置Contrast Key kCIInputContrastKey来增加黑白对比度,如下所示:

Xcode 9•Swift 4

extension String {
    static let colorControls = "CIColorControls"
}

extension UIImage {
    var coreImage: CIImage? { return CIImage(image: self) }
}

extension CIImage {
    var uiImage: UIImage? { return UIImage(ciImage: self) }
    func applying(contrast value: NSNumber) -> CIImage? {
        return applyingFilter(.colorControls, parameters: [kCIInputContrastKey: value])
    }
    func renderedImage() -> UIImage? {
        guard let image = uiImage else { return nil }
        return UIGraphicsImageRenderer(size: image.size,
                                       format: image.imageRendererFormat).image { _ in
            image.draw(in: CGRect(origin: .zero, size: image.size))
        }
    }
}

let url = URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!
do {
    if let coreImage = UIImage(data: try Data(contentsOf: url))?.coreImage,
        let increasedContrast = coreImage.applying(contrast: 1.5) {
        imageView.image = increasedContrast.uiImage
        // if you need to convert your image to data (JPEG/PNG) you would need to render the ciimage using renderedImage method on CIImage   
    }
} catch {
    print(error)
}

要将颜色转换为灰度,可以将饱和度键kCIInputSaturationKey设置为零:

extension CIImage {
    func applying(saturation value: NSNumber) -> CIImage? {
        return applyingFilter(.colorControls, parameters: [kCIInputSaturationKey: value])
    }
    var grayscale: CIImage? { return applying(saturation: 0) }
}

let url = URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!
do {
    if let coreImage = UIImage(data: try Data(contentsOf: url))?.coreImage, 
        let grayscale = coreImage.grayscale {
        // use  grayscale image here
        imageView.image = grayscale.uiImage
    }
} catch { 
    print(error) 
}
2020-07-07