How to scan an image and automatically crop it to the scanned content with a linux command line tool?

5,456

Solution 1

What you need is convert from imagemagick. First install imagemagick for your distribution. On debian derived systems run this command:

sudo apt-get install imagemagick

Now, if you just want to remove whitespace do this:

for image in $(find . -name "*png" | sed 's/.png//'); do convert -trim $image.png $image_trimmed.png; done

This assumes your images are PNGs, if not change the above line accordingly.

If you need fancier resizing, have a look at the imagemagick documentation, you can do just about anything you can imagine with it.

So, your actual workflow would be:

  1. Scan your images and save them in the same folder.
  2. Run the command I gave above in that folder.

Solution 2

Try adding -fuzz:

-fuzz *distance*

Colors within that distance are considered equal.

for image in $(find . -name "*png" | sed 's/.png//');
do convert -fuzz 255 -trim $image.png $image_trimmed.png; done
Share:
5,456

Related videos on Youtube

hennr
Author by

hennr

Software developer from Berlin, Germany

Updated on September 18, 2022

Comments

  • hennr
    hennr almost 2 years

    I need to scan lots of small items with quite similar, but not the exact same, size.

    What I thought I'd like to do is:

    Run a linux command line tool with the file name as a parameter which runs the scanner until about 10% of the whole scanner size and crops the image to the content that is not white (a square would be fine).

    Does anybody know if this is possible and when how? Thanks in advance!

  • hennr
    hennr over 11 years
    This doesn't work for my test image. No white pixel gets removed.
  • hennr
    hennr over 11 years
    @terdon I already ran the correct command whith the output file, but trim doesn't work with my scanned image. Note that a color scan doesn't provide perfectly clean white pixels.
  • hennr
    hennr over 11 years
    Well, you can play around with the -white-threshold parameter to convert almost white pixels to completely white pixels. This just works for dark scanned content though.
  • terdon
    terdon over 11 years
    Ah, i see what you mean @hennr. Sorry, i did not take the scan into account, I have used this command succesfully but on perfectly white images. I don't have time to write an answer now, but try gimp scripting, it might work for you.
  • terdon
    terdon over 11 years
    @hennr, You did say "white" in your question mind you :)