我正在使用 CIImage 对象,试图获得饱和值。但我找不到获得图像饱和度的方法,至少使用 OS X 中可用的 CIFilters。
是否可以使用标准 CIFilters 获得 CIImage 的饱和度?
3 回答
看看CIColorControls
过滤器。使用此滤镜可以调整图像的饱和度、亮度和对比度。
为了计算饱和度,该滤波器在灰度图像(饱和度 = 0.0)和原始图像(饱和度 = 1.0)之间进行线性插值。过滤器支持外推:对于大于 1.0 的值,它会增加饱和度。
例子:
CIFilter *colorControlsFilter = [CIFilter filterWithName:@"CIColorControls"];
[colorControlsFilter setDefaults];
[colorControlsFilter setValue:sourceImage forKey:@"inputImage"];
[colorControlsFilter setValue:[NSNumber numberWithFloat:1.0] forKey:@"inputSaturation"];
[colorControlsFilter setValue:[NSNumber numberWithFloat:0.2] forKey:@"inputBrightness"];
[colorControlsFilter setValue:[NSNumber numberWithFloat:1.0] forKey:@"inputContrast"];
CIImage *outputImage = [colorControlsFilter valueForKey:@"outputImage"];
You cannot do it using built-in CIFilter but you can code it quite simply. I won't give you full implementation but I can give you the cikernel that'll do the work :
vec4 rgbToHsv(vec4 rgb) {
float x = min(rgb.r, min(rgb.g, rgb.b));
float v = max(rgb.r, max(rgb.g, rgb.b));
float f = (rgb.r == x) ? rgb.g - rgb.b : ((rgb.g == x) ? rgb.b - rgb.r : rgb.r - rgb.g);
float i = (rgb.r == x) ? 3.0 : ((rgb.g == x) ? 5.0 : 1.0);
float h = i - (f / (v - x));
float s = (v - x) / v;
return (v == x) ? vec4(-1, 0, v, rgb.a) : vec4(h, s, v, rgb.a);
}
kernel vec4 saturationToGrayscale(sampler image) {
vec4 color = sample(image, samplerCoord(image));
vec4 hsv = rgbToHsv(color);
return premultiply(vec4(vec3(hsv.g), color.a));
}
rgbToHsv function comes from Andy Finnell's blog
Output result is a grayscale image where white means sat == 1.0 and black means sat == 0.0. You can revert this by using "1.0-hsv.g" instead of "hsv.g" in the return argument. You can also retrieve hue and value by using respectively hsv.r and rsv.b.
Making it a CIFilter is left to you. Take a Look at Apple's Creating Custom Filters to do this. The code above takes place in the .cikernel file.