1

I have images that have a white border around them. I'd like to get rid of that border at runtime.

A simple but slow algorithm to do that would be like this:

  1. Scan every row from the top down, stopping if a pixel in the row is non-white.
  2. Do the same for all 4 sides.

That way, I learn the width of the white border on each side, and can trim it accordingly.

The above method is rather slow, I suppose. Is there a more efficient way to accomplish this? I.e, does iOS offer any functions that help with this task?

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
  • You might be able to pair up a thresholding operation (to remove everything that wasn't white), an opening or closing operation (to remove small features that weren't from your border), and Harris corner detection: http://stackoverflow.com/questions/10530846/determine-the-corners-of-a-sheet-of-paper-with-ios-5-av-foundation-and-core-imag/10623563#10623563 . I have operations for all of these in GPUImage, like I show in the linked answer, but results might depend on the specifics of your images. – Brad Larson Feb 27 '14 at 21:48

2 Answers2

1

It might not be the best solution but as you said you can check the color, then trim. Here is a method for getting a color of the pixel in the image:

- (UIColor)colorOfPixelAtLocation:(CGPoint)position inImage:(UIImage *)image
{
    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int pixelInfo = ((image.size.width  * position.y) + position.x ) * 4; // PNG

    UInt8 red = data[pixelInfo];
    UInt8 green = data[(pixelInfo + 1)];
    UInt8 blue = data[pixelInfo + 2];

    CFRelease(pixelData);

    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f]; 
}

And code that trims:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);

// Use the image

CGImageRelease(imageRef);

I hope it helps.

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
  • 1
    Yeah, well. That's the part I already knew and which I described as the bad alternative. I also just found a similar answer here: http://stackoverflow.com/questions/20056870/trim-uiimage-border – Thomas Tempelmann Feb 27 '14 at 20:58
-1

I would just cheat. Say your image has a 10px white boarder around it, and the image is 200x 200, display it in a UIImageView with size 180x180 and centre it without any scaling :P

Sam Jarman
  • 7,277
  • 15
  • 55
  • 100
  • I can't do this because I don't know the dimensions of the borders of the images I am going to present. That's why I need to detect them at runtime. – Thomas Tempelmann Feb 27 '14 at 20:54