Given an image that has some actual content inside and usually some unwanted white or black or transparency around that, I would like to trim or crop the exterior parts using ImageMagick.
The following image has been drawn digitally on a computer (on the HTML <canvas>
):
The following ImageMagick command is what I tried:
$ convert canvas.png -trim +repage canvas_trimmed.png
And it worked perfectly:
So this is exactly what I want. But now I want this to work with scanned documents as well, which are not as "perfect" as computer-generated images, i.e. they have more shades of "white" and "black" and no transparency which would be easier to detect. Sometimes, they even have some black bars around the white background of the paper because the area of the scanner is larger than the paper:
With this image, I tried the following commands in the given order, each trying to be more aggressive, but none yielding any results – you can't see any difference between the original image and the "trimmed" images, i.e. the trimming or cropping does not work at all:
$ convert scan.jpg -trim +repage scan_trimmed.jpg
$ convert scan.jpg -fuzz 10% -trim +repage scan_trimmed.jpg
$ convert scan.jpg -fuzz 60% -trim +repage scan_trimmed.jpg
$ convert scan.jpg -fuzz 60% -bordercolor white -border 1x1 -trim +repage scan_trimmed.jpg
$ convert scan.jpg -fuzz 60% -bordercolor black -border 1x1 -trim +repage scan_trimmed.jpg
What am I doing wrong here? How can the ImageMagick command that reliably trims computer-generated images be modified so that it trims scanned documents of the style above just as reliably?
Best Answer
You can use -shave and simply shave off the edges and then use the logic you use afterwards to process accordingly.
Example Logic
Before
After
Further Resources