Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple algorithm to crop empty borders from an image by code?

Currently I'm seeking for a rather fast and reasonably accurate algorithm in C#/.NET to do these steps in code:

  1. Load an image into memory.
  2. Starting from the color at position (0,0), find the unoccupied space.
  3. Crop away this unnecessary space.

I've illustrated what I want to achieve:

Example illustration

What I can imagine is to get the color of the pixel at (0,0) and then do some unsafe line-by-line/column-by-column walking through all pixels until I meet a pixel with another color, then cut away the border.

I just fear that this is really really slow.

So my question is:

Are you aware of any quick algorithmns (ideally without any 3rd party libraries) to cut away "empty" borders from an in-memory image/bitmap?

Side-note: The algorithm should be "reasonable accurate", not 100% accurate. Some tolerance like one line too much or too few cropped would be way OK.

Addition 1:

I've just finished implementing my brute force algorithm in the simplest possible manner. See the code over at Pastebin.com.

like image 979
Uwe Keim Avatar asked Aug 16 '11 19:08

Uwe Keim


2 Answers

If you know your image is centered, you might try walking diagonally ( ie (0,0), (1,1), ...(n,n) ) until you have a hit, then backtrack one line at a time checking until you find an "empty" line (in each dimension). For the image you posted, it would cut a lot of comparisons.

You should be able to do that from 2 opposing corners concurrently to get some multi-core action.

Of course, hopefully you dont it the pathelogical case of 1 pixel wide line in the center of the image :) Or the doubly pathological case of disconnected objects in your image such that the whole image is centered, but nothing crosses the diagonal.

One improvement you could make is to give your "hit color" some tolerance (adjustable maybe?)

like image 127
µBio Avatar answered Sep 17 '22 16:09

µBio


The algorithm you are suggesting is a brute force algorithm and will work all the time for all type of images.

but for special cases like, subject image is centered and is a continuous blob of colors (as you have displayed in your example), binary sort kind of algorithm can be applied.

start from center line (0,length/2) and start in one direction at a time, examine the lines as we do in binary search.

do it for all the sides.

this will reduce complexity to log n to the base 2

like image 37
Tarang Avatar answered Sep 18 '22 16:09

Tarang