如何在uiimage中找到特定的颜色并改变颜色

时间:2017-01-13 11:59:48

标签: ios objective-c core-image

我想在图像中找到特定的颜色,例如我有一个有很多颜色的图像。通过指定红色参数我想要更改除红色像素之外的其他颜色像素。请看下面的图片。在上面更新的图像中,只有模糊颜色突出显示所有其他颜色都被更改。

enter image description here 更新了Pic

enter image description here

1 个答案:

答案 0 :(得分:2)

好的,所以我很好奇实现这个反向色度键的难度,结果发现,给定example from Apple它很容易!

// Allocate memory
const unsigned int size = 32;
float *cubeData = (float *)malloc (size * size * size * sizeof (float) * 4);
float rgb[3], *c = cubeData;
CGFloat hue = CGFLOAT_MAX;

CGFloat minHueAngle = 210;
CGFloat maxHueAngle = 240;

// Populate cube with a simple gradient going from 0 to 1
for (int z = 0; z < size; z++){
    rgb[2] = ((double)z)/(size-1); // Blue value
    for (int y = 0; y < size; y++){
        rgb[1] = ((double)y)/(size-1); // Green value
        for (int x = 0; x < size; x ++){
            rgb[0] = ((double)x)/(size-1); // Red value
            // Convert RGB to HSV
            // You can find publicly available rgbToHSV functions on the Internet
            UIColor *color = [UIColor colorWithRed:rgb[0] green:rgb[1] blue:rgb[2] alpha:1];
            [color getHue:&hue saturation:nil brightness:nil alpha:nil];
            hue *= 360;

            // Use the hue value to determine which to make transparent
            // The minimum and maximum hue angle depends on
            // the color you want to remove
            float alpha = (hue > minHueAngle && hue < maxHueAngle) ? 1.0f: 0.0f;
            // Calculate premultiplied alpha values for the cube
            c[0] = rgb[0] * alpha;
            c[1] = rgb[1] * alpha;
            c[2] = rgb[2] * alpha;
            c[3] = alpha;
            c += 4; // advance our pointer into memory for the next color value
        }
    }
}
// Create memory with the cube data
NSData *data = [NSData dataWithBytesNoCopy:cubeData
                                    length:(size * size * size * sizeof (float) * 4)
                              freeWhenDone:YES];
CIFilter *colorCube = [CIFilter filterWithName:@"CIColorCube"];
[colorCube setValue:@(size) forKey:@"inputCubeDimension"];
[colorCube setValue:data forKey:@"inputCubeData"];

UIImage *originalImage = [UIImage imageNamed:@"yourImageName"];
CIImage *ciImage = [CIImage imageWithCGImage:originalImage.CGImage];
[colorCube setValue:ciImage forKey:kCIInputImageKey];


UIImage *result = [UIImage imageWithCIImage:[colorCube outputImage]];

这会从您的示例图片中生成此图片: enter image description here

我必须说它看起来相当不错,因为我只修改了一两分钟的值。当然,为了达到您想要的总体最终结果,您需要再使用两个过滤器 - 即CIPhotoEffectMonoCISourceOverCompositing来使您的原始图像变为黑色&amp;白色,然后将来自CubeMap过滤器的结果叠加在黑色&amp;白色图片。