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

sha*_*oga 4 core-image ios cifilter swift

我正在为iOS应用程序构建扫描仪组件到目前为止,我已经裁剪了结果图像,并且正确的视角.现在我需要将彩色图像变成黑白"扫描"文档.

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

我怎样才能做到这一点?谢谢

Leo*_*bus 12

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

Xcode 9•Swift 4

extension String {
    static let colorControls = "CIColorControls"
}
Run Code Online (Sandbox Code Playgroud)
extension UIImage {
    var coreImage: CIImage? { return CIImage(image: self) }
}
Run Code Online (Sandbox Code Playgroud)

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

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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ent 5

  1. 降低饱和度会将图像转换为灰度
  2. 增加对比度将把这些灰色调到极限,即黑白。

您可以CIColorControls

let ciImage = CIImage(image: image)!
let blackAndWhiteImage = ciImage.applyingFilter("CIColorControls", withInputParameters: ["inputSaturation": 0, "inputContrast": 5])
Run Code Online (Sandbox Code Playgroud)

原版的:

原版的

使用inputContrast = 1(默认):

inputContrast = 1

inputContrast = 5

inputContrast = 5