gpt4 book ai didi

ios - 如何在 iOS 中检查图像是否黑白

转载 作者:行者123 更新时间:2023-11-29 04:06:16 26 4
gpt4 key购买 nike

我有一个 UIImage,显示从网上下载的照片。我想知道如何以编程方式发现图像是黑白还是彩色。

最佳答案

如果您不介意计算密集型任务并且希望完成工作,请检查图像的每个像素。

这个想法是检查每个单个像素的所有 RGB channel 是否相似,例如 RGB 45-45-45 的像素是灰色,也是 43-42-44,因为所有 channel 都彼此接近。我发现每个 channel 都有相似的值(我使用的阈值是 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);

关于ios - 如何在 iOS 中检查图像是否黑白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147311/

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