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

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

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

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

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

Xcode 9•Swift 4

 extension UIImage { func applying(contrast value: NSNumber) -> UIImage? { guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", parameters: [kCIInputContrastKey: value]) else { return nil } // Swift 3 uses withInputParameters instead of parameters UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size)) return UIGraphicsGetImageFromCurrentImageContext() } } 

 let link = "https://i.stack.imgur.com/Xs4RX.jpg" let image = UIImage(data: try! Data(contentsOf: URL(string: link)!)) if let contrastIncreased = image?.applying(contrast: 1.5) { // use contrastIncreased image here } 

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

 extension CIImage { var image: UIImage? { let image = UIImage(ciImage: self) UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) defer { UIGraphicsEndImageContext() } image.draw(in: CGRect(origin: .zero, size: image.size)) return UIGraphicsGetImageFromCurrentImageContext() } } extension UIImage { func applying(saturation value: NSNumber) -> UIImage? { return CIImage(image: self)? .applyingFilter("CIColorControls", parameters: [kCIInputSaturationKey: value]) .image } // Swift 3 uses withInputParameters instead of parameters var grayscale: UIImage? { return applying(saturation: 0) } } 

 let link = "https://i.stack.imgur.com/Xs4RX.jpg" let image = UIImage(data: try! Data(contentsOf: URL(string: link)!)) if let grayscale = image?.grayscale { // use grayscale image here } 
  1. Desaturate会将您的图像转换为灰度
  2. 增加对比度会将这些灰色推向极端,即黑色和白色。

你可以CIColorControls

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

原版的:

原版的

使用inputContrast = 1 (默认值):

inputContrast = 1

使用inputContrast = 5

inputContrast = 5

Interesting Posts