目标 c - 如何在 iOS 中检查图像是否为黑白



我有一个UIImage显示从网上下载的照片。我想知道如何以编程方式发现图像是否在B&W或颜色。

如果你不介意一个计算密集型的任务,并且你想要完成这项工作,请逐个像素检查图像。

这个想法是检查每个像素的所有RGB通道是否相似,例如RGB 45-45-45的像素是灰色的,也是43-42-44,因为所有通道彼此接近。我正在寻找每个通道都有类似的值(我使用10的阈值,但它只是随机的,你必须做一些测试)

一旦你有足够的像素超过你的阈值,你就可以打破循环并将图像标记为彩色

代码没有经过测试,只是一个想法,希望没有泄漏。

// load image 
CGImageRef imageRef = yourUIImage.CGImage
CFDataRef cfData = CGDataProviderCopyData(CGImageGetDataProvider(imageRef));
NSData * data = (NSData *) cfData;
char *pixels = (char *)[data bytes];
const int threshold = 10; //define a gray threshold
for(int i = 0; i < [data length]; i += 4)
{
    Byte red = pixels[i];
    Byte green = pixels[i+1];
    Byte blue = pixels[i+2];
    //check if a single channel is too far from the average value. 
    //greys have RGB values very close to each other
    int average = (red+green+blue)/3; 
    if( abs(average - red) >= threshold ||
        abs(average - green) >= threshold ||
        abs(average - blue) >= threshold )
    { 
        //possibly its a colored pixel.. !! 
    }
}
CFRelease(cfData);

最新更新