gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:23 26 4
gpt4 key购买 nike

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

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

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

最佳答案

您可以使用 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: "/image/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: "/image/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)
}

关于ios - 如何使用 CIFilter 在 Swift 中将 UIImage 转换为灰度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com