0

I have a posterized image with CIColorPosterize CIFilter. The image contains a few number of colors. At this point I would like to extract an UIColor's array with the n-colors from this image. There is a function that does something like this? Otherwise, which could be an effective approach to realize this?

Thank you experts!

Ferran T.
  • 242
  • 3
  • 12
  • See http://stackoverflow.com/questions/16416380/iphone-how-to-get-colour-of-each-pixel-of-an-image for an inspiration (haha could not add it as a comment as I have not enough reputation, but the system did it for me ;)) – Janos Jan 25 '14 at 11:50

1 Answers1

2

You can try this..

CGImageRef imageRef = [yourImage CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));

// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
for (int i = 0 ; i < count ; byteIndex += 4,++i)
{
    CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
    CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
    CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
    CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;    
    UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    [result addObject:acolor];
}

free(rawData);
NSLog(@"Extracted colors count %d",result.count);
Mani
  • 17,549
  • 13
  • 79
  • 100