3

How can I detect dominant color on an image/cam and print its name?

eg: in image there can be, very light blue, light blue, blue, dark blue just because of lightning on that object or image when I analyze that image I want to make that I know dominant color is blue, and print "Blue" on screen. If I need to work with RGB I think I will need color ranges right?

ps: there can be also red, yellow etc on image but I want to detect dominant color.

turushan
  • 690
  • 7
  • 25

1 Answers1

2
- (UIColor *)averageColor {

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char rgba[4];
    CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), self.CGImage);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);  

    if(rgba[3] > 0) {
        CGFloat alpha = ((CGFloat)rgba[3])/255.0;
        CGFloat multiplier = alpha/255.0;
        return [UIColor colorWithRed:((CGFloat)rgba[0])*multiplier
                               green:((CGFloat)rgba[1])*multiplier
                                blue:((CGFloat)rgba[2])*multiplier
                               alpha:alpha];
    }
    else {
        return [UIColor colorWithRed:((CGFloat)rgba[0])/255.0
                               green:((CGFloat)rgba[1])/255.0
                                blue:((CGFloat)rgba[2])/255.0
                               alpha:((CGFloat)rgba[3])/255.0];
    }
}

from Objective-c - Getting least used and most used color in a image

which is from http://www.bobbygeorgescu.com/2011/08/finding-average-color-of-uiimage/

Community
  • 1
  • 1
Schemetrical
  • 5,506
  • 2
  • 26
  • 43
  • Hi! Your code is excelent. But I keep getting the error: Property 'CGImage' not found on object of type 'MyClass*' What can be done? Please! =) – gbossa Jul 08 '20 at 13:16
  • You are not calling this on the correct object, your image needs to be an UIImage and this extension will allow you to call [image averageColor]. – Schemetrical Jul 09 '20 at 17:01