Dalton
Dalton

Reputation: 23

How to determine the presence of a color in a picture from iPhone Camera

I have been asked to write an iOS application that can check for the presence of the color red in a picture. I have a little experience with objective C and XCode but not very much.

If anyone can get me pointed in the right direction I would really appreciate it.

Upvotes: 0

Views: 122

Answers (1)

Usama
Usama

Reputation: 1965

/**
 * Structure to keep one pixel in RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA format
 */

struct pixel {
    unsigned char r, g, b, a;
};

/**
 * Process the image and return the number of pixels in it.
 */

- (NSUInteger) processImage: (UIImage*) image withRed:(NSUInteger)r green:(NSUInteger)g blue:(NSUInteger)b
{
    NSUInteger numberOfPixels = 0;

    // Allocate a buffer big enough to hold all the pixels

    struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
    if (pixels != nil)
    {
        // Create a new bitmap

        CGContextRef context = CGBitmapContextCreate(
            (void*) pixels,
            image.size.width,
            image.size.height,
            8,
            image.size.width * 4,
            CGImageGetColorSpace(image.CGImage),
            kCGImageAlphaPremultipliedLast
        );

        if (context != NULL)
        {
            // Draw the image in the bitmap

            CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);

            // Now that we have the image drawn in our own buffer, we can loop over the pixels to
            // process it. This simple case simply counts all pixels that have a pure red component.

            // There are probably more efficient and interesting ways to do this. But the important
            // part is that the pixels buffer can be read directly.

            NSUInteger p = image.size.width * image.size.height;

            while (p > 0) {
                if (pixels->r == r && pixels->g == g && pixels->b == b) {
                    numberOfPixels++;
                }
                pixels++;
                p--;
            }

            CGContextRelease(context);
        }

        free(pixels);
    }

    return numberOfPixels;
}

Use:

NSUInteger numberOfSpecificColorPixels = [self processImage: [UIImage imageNamed: @"testImage.png" withRed:232 green:212 blue:192]];

this will give you number of pixels for specific color, which you can then use as per your requirement

Upvotes: 1

Related Questions