Megan
Megan

Reputation: 107

iOS : Get top colors from every pixels of an image

In my project I need to show the top three colours for an image given (look at the sample image below) . The functionality requirement is I have to get the top three colours in every pixel of an image individually then those have to be calculated for all pixels. finally top three presented colours in given image have to be listed as output . (had a look at GPUImage but i could't found any code for my requirement) . Thanks ..

enter image description here

Upvotes: 0

Views: 544

Answers (1)

El Tomato
El Tomato

Reputation: 6707

Try the following function with double for-loops. I picked up some code somebody posted here and then made some changes, I think. I don't develop iOS any more. So I cannot answer detailed questions. But you should be able to get some idea out of this function.

- (UIColor *)getRGBAsFromImage:(UIImage *)image atX:(CGFloat)xx atY:(CGFloat)yy {
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                                         kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0,0,width,height),imageRef);
    CGContextRelease(context);

    int index = 4*((width*yy)+xx);
    int R = rawData[index];
    int G = rawData[index+1];
    int B = rawData[index+2];
    UIColor *aColor;
    aColor = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0];
    rValue = R; gValue = G; bValue = B;
    free(rawData);
    return aColor;
}

// Updated //

Example

UIColor *c = [self getRGBAsFromImage:colorImage1.image atX:0 atY:0]; // colorImage1 is UIImageView

Get image dimensions, first. Then use double for-loop to iterate x and y values. Then store the color value in an array for your objective.

Upvotes: 1

Related Questions