3

I'm doing an image processing iOS app, where we have a large image (eg:size will be 2000x2000). Assume that image is completely black, except one part of the image is a different color (lets say the size of that region is 200x200).

SI want to calculate the start and end position of that differently coloured region. How can I achieve this?

Brad Larson
  • 168,330
  • 45
  • 388
  • 563

1 Answers1

0

Here's a simple way to allow the CPU to get pixel values from a UIImage. The steps are

  • allocate a buffer for the pixels
  • create a bitmap memory context using the buffer as the backing store
  • draw the image into the context (writes the pixels into the buffer)
  • examine the pixels in the buffer
  • free the buffer and associated resources

- (void)processImage:(UIImage *)input
{
    int width  = input.size.width;
    int height = input.size.height;

    // allocate the pixel buffer
    uint32_t *pixelBuffer = calloc( width * height, sizeof(uint32_t) );

    // create a context with RGBA pixels
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate( pixelBuffer, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast );

    // invert the y-axis, so that increasing y is down
    CGContextScaleCTM( context, 1.0, -1.0 );
    CGContextTranslateCTM( context, 0, -height );

    // draw the image into the pixel buffer
    UIGraphicsPushContext( context );
    [input drawAtPoint:CGPointZero];
    UIGraphicsPopContext();

    // scan the image
    int x, y;
    uint8_t r, g, b, a;
    uint8_t *pixel = (uint8_t *)pixelBuffer;

    for ( y = 0; y < height; y++ )
        for ( x = 0; x < height; x++ )
        {
            r = pixel[0];
            g = pixel[1];
            b = pixel[2];
            a = pixel[3];

            // do something with the pixel value here

            pixel += 4;
        }

    // release the resources
    CGContextRelease( context );
    CGColorSpaceRelease( colorSpace );
    free( pixelBuffer );
}
user3386109
  • 32,020
  • 7
  • 41
  • 62