簡體   English   中英

如何在UIImage / CIImage中隔離單一顏色?

[英]How can I isolate a single color in a UIImage / CIImage?

我想在UIImage隔離某種顏色的元素,以便隨后可以在其他工具中處理該圖像。

假設我有以下圖像,並且我想隔離所有紅色元素。

輸入:

在此處輸入圖片說明

所需的輸出:所有紅色元素

在此處輸入圖片說明

我可以采取哪些步驟來完成此任務? 我認為這會在CIFilter但尚未找到合適的過濾器。 有沒有簡單的方法可以實現這一目標?

好了,得到了一些幫助並整理了! 這樣做的方法如下:

// First, turn our UIImage into a CIImage
let ciImage = CIImage(image: image)!

// Next, let's make a CIVector for the color we want.
let colorToIsolate = CIVector(x: 0.239, y: 0.951, z: 0.937) // normalized RGB

// OK, here's where it gets interesting. 
// We're going to write a CIColorKernel that maps every pixel in the image. 
// If it's the color we want, then we turn it white, otherwise, black.
// This is iOS-10 friendly; in iOS 11 there's a non-string-based way,
// which helps with compiler type-checking and non-runtime error detection.
// NOTE: The 0.5 value is a tolerance; adjust and adapt it to your needs for your task. 
// I was surprised that we needed it that large to get the desired effect; 
// had hoped that I could use a tighter value like 0.01

let kernelString = "kernel vec4 filterColorMatch(sampler image, vec3 match) {" +
        "vec2 dc = destCoord();" +
        "vec3 color = sample(image, samplerTransform(image, dc)).rgb; " +
        "return distance(color, match) < 0.5 ? vec4(1,1,1,1) : vec4(0,0,0,1); }"

let colorIsolate = CIColorKernel(string: kernelString)

// Now we can run our kernel, and extract the image!
let after = colorIsolate?.apply(
  withExtent: ciImage.extent, 
  arguments: [ciImage, colorToIsolate]
)

let result = UIImage(ciImage: after)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM