Automatic crop and rotate scans?

Automatic crop and rotate scans?

Nadav Har'El nyh at math.technion.ac.il
Wed May 4 22:40:33 IDT 2011


On Tue, May 03, 2011, Nadav Har'El wrote about "Automatic crop and rotate scans?":
> I have a flatbed scanner (by HP) attached to my Linux machine, and I often
> need to scan rectangular items such as photographs, CD inserts, and the
> occasional piece of paper.
>...
> automatically: The program would recognize (using a relatively simple algorithm)
> the foreground rectangle in the image, rotate it to be perfectly horizontal,
> and then crop the image to it.

I still haven't been able to find a perfect, or anything close to perfect,
solution for this problem. So I've designed my own algorithm to do it (oh,
this reminded me of my fun Math days...), but before I actually implement
it, I found a partial solution with existing tools:

Apparently, the netpbm package includes a tool "pamtilt", which doesn't
quite look for a rectangular scanned object (which is my use case), but
quite often does happen to find the right angle to rotate by. So a
command like this scans a CD insert or whatever I want to scan, and
automatically rotates it in the right angle:

	scanimage --resolution 200 --mode color >/tmp/crooked.pnm
	a=`pamtilt -hstep 1 -angle=20 </tmp/crooked.pnm`
	case $a in
	00.00) echo FAILED >&2; exit 1;;
	esac
	echo found angle $a >&2
	pnmrotate $a </tmp/crooked.pnm | pnmtopng -compression=9

Sometimes this finds the wrong angle, and simply rotating the scanned
object and trying again works.
The Imagemagick tool also has a similar tool, which again sometimes works,
and sometimes doesn't... Its command is much shorter:

	scanimage --resolution 200 --mode color >/tmp/crooked.pnm
	convert -deskew 10% /tmp/crooked.pnm out.png

Neither of these commands *crops* the picture to the rectangle, unfortunately,
and I haven't found any command that consistantly manages to do that after the
rotation. Surpisingly, the "auto crop" tool of "xv" (an obscure image viewer
from the early 1990s) seems to work best, but also fails often; So I just use
xv's manual crop.

I wonder if anyone else can come up with something better with existing
tools - before I (or anyone else) creates a new special tool for this use
case.

-- 
Nadav Har'El                        |     Wednesday, May  4 2011, 1 Iyyar 5771
nyh at math.technion.ac.il             |-----------------------------------------
Phone +972-523-790466, ICQ 13349191 |The message above is just this
http://nadav.harel.org.il           |signature's way of propagating itself.



More information about the Linux-il mailing list