Page 1 of 1

Unable to trim borders of a scanned document

Posted: 2019-09-16T23:25:48-07:00
by njw
Hi everyone,

New user here. I have been trying to trim the border of a scanned invoice document(with removed info) with the following command:

convert -trim -transparent white -fuzz 50% input.png output.png

However it seems that the borders still remain there. Please help me take a look.

Image url: https://photos.app.goo.gl/RmGbcagPv9yXCdjZ6

Edit: i am using ImageMagick-7.0.8-64-portable-Q16-x64

Re: Unable to trim borders of a scanned document

Posted: 2019-09-17T03:01:29-07:00
by snibgo
The order is wrong. You need to read the image before you can input it. "-fuzz" modifies "-trim", so should come before it, not afterwards. The image is noisy. This works:

Code: Select all

convert invoice.png -despeckle -despeckle -fuzz 90% -trim +repage out.png

Re: Unable to trim borders of a scanned document

Posted: 2019-09-17T09:07:31-07:00
by fmw42
For ImageMagick 7, use magick in place of convert. ImageMagick 7 is more strict about syntax than ImageMagick 6. Both need the following syntax for raster images:

For IM 6:
convert inputimage <settings> <operator> outputimage

For IM 7:
magick inputimage <settings> <operator> outputimage

Re: Unable to trim borders of a scanned document

Posted: 2019-09-17T20:53:56-07:00
by njw
Hi everyone,

I have tried to do the same for another file but it has failed to convert with the following error:
convert: geometry does not contain image `test3.png' @ warning/attribute.c/GetImageBoundingBox/501.

Image link: https://photos.app.goo.gl/N4TwqMBEEM4x55Uz7

I have tried reducing the fuzz to 50% and it runs without error but the image remains the same.

Re: Unable to trim borders of a scanned document

Posted: 2019-09-17T21:19:20-07:00
by fmw42
50% would be way too much. You have trimmed it all away to zero dimensions that is why you get that message. The issue with your image is that if you look at full resolution, it has a few dark spots near the top. That prevents a normal trim from working. You need to remove those spots, before you can trim the image.

One way would be to filter out the small black spots using connected components and then trim the image.

This works for me (Unix syntax). I use connected components first to remove the small black spots (<=10 pixels in area), then get the crop values from a virtual trim using %@. See https://imagemagick.org/script/escape.php

Code: Select all

cropvals=`convert test.png +repage -alpha off -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:area-threshold=10 \
-connected-components 4 \
-format "%@" info:`
echo "$cropvals"
convert test.png +repage -alpha off -crop $cropvals result.png