我正在尝试检索主要包含特定颜色的图像。 但我的方法并不总能找到具有特定颜色的图像,有时也会找到白色图像。
- (UIColor *)getAvgColorFromUIImage:(UIImage *)image
{
NSUInteger redP = 0;
NSUInteger greenP = 0;
NSUInteger blueP = 0;
struct pixel* pixels = (struct pixel*) calloc(1,
image.size.width * image.size.height * sizeof(struct pixel));
if (pixels != nil)
{
CGContextRef context = CGBitmapContextCreate((void *) pixels,
image.size.width,
image.size.height,
8, image.size.width * 4,
CGImageGetColorSpace(image.CGImage),
(CGBitmapInfo)kCGImageAlphaPremultipliedLast);
if (context != NULL)
{
CGContextDrawImage(context,
CGRectMake(0, 0, image.size.width, image.size.height),
image.CGImage);
NSUInteger numberOfPixels = image.size.width * image.size.height;
struct pixel* ptr = pixels;
while (numberOfPixels > 0)
{
if (ptr->r > 125) redP++;
if (ptr->g > 125) greenP++;
if (ptr->b > 125) blueP++;
ptr++;
numberOfPixels--;
}
CGContextRelease(context);
}
free(pixels);
}
return [UIColor colorWithRed:redP/(image.size.width * image.size.height)
green:greenP/(image.size.width * image.size.height)
blue:blueP/(image.size.width * image.size.height)
alpha:1.0f];
}
以下是用户给定颜色的相似性检查:
- (BOOL)compareUIColor:(UIColor *)a to:(UIColor *)b
{
CGColorRef iref = [a CGColor];
CGColorRef irefb = [b CGColor];
if (CGColorGetColorSpace(iref) != CGColorGetColorSpace(irefb)) return FALSE;
size_t componentCount = CGColorGetNumberOfComponents(iref);
const double *comp = CGColorGetComponents(iref);
const double *compb = CGColorGetComponents(irefb);
for (int i = 0; i < componentCount; i++)
{
float difference = comp[i] / compb[i];
if (fabs(difference - 1) > self.tolerance)
return FALSE;
}
return TRUE;
}
你能建议我如何改善这个吗?
此致 WA
答案 0 :(得分:0)
如果您尝试按亮度阈值并且仅尝试高于特定亮度的平均颜色,则可以执行以下操作:
NSUInteger weight = 0;
while (numberOfPixels > 0)
{
uint8_t luminance = (uint8_t)((float)ptr->r * 0.2125 + (float)ptr->g * 0.7152 + (float)ptr->b * 0.0722);
if (luminance > 125)
{
redP += ptr->r;
greenP += ptr->g;
blueP += ptr->b;
weight++;
}
ptr++;
numberOfPixels--;
}
struct pixel average = {redP / weight, greenP / weight, blueP / weight };