The problem with page-010 is that there is a black speck in the middle of the right margin, which prevents the trim from removing all the right white space and thus skewing the location of the middle. The middle should be the only place that is totally white, otherwise it will crop wrong.
So I put in a shave option too trim once, then shave a few pixels off the image all around, and then trim again. This allows this page to work.
The argument shaving="10x10" means shave off 10 pixels at the left and right and 10 pixels at the top and bottom. You can adjust that to whatever makes things work. But it could be image dependent. If you have dark specks in the original or that appear from specks on the scanner, then you will likely have trouble. Also the page number at the bottom center is right in the area that needs to be totally white. It is fortunate that this seems to work anyway. But there is no guarantees. You may have to shave that off. That is more on the top and bottom and less on the sides. If you need to cut differently on all four sides, I can modify this script to use -chop rather than -shave.
If you want a few pixels of white margin put onto the left and right image, that can be done also.
Here is the code.
Code: Select all
infile="page-010.png"
shaving="10x10"
inname=`convert -ping "$infile" -format "%t" info:`
suffix=`convert -ping "$infile" -format "%e" info:`
convert "$infile" -auto-level -morphology smooth diamond:1 \
-background white -deskew 40% +repage \
-fuzz 10% -trim +repage -shave $shaving -trim +repage tmp.png
OIFS=$IFS
IFS=$'\n'
white_arr=(`convert tmp.png -auto-level -threshold 75% -scale x1! txt: |\
tail -n +2 | tr -cs "0-9\n" " " | grep -e '.* .* 255'`)
#echo "${white_arr[*]}"
num=${#white_arr[*]}
IFS=$OIFS
middle=`convert xc: -format "%[fx:round($num/2)]" info:`
#echo "middle=$middle"
xcrop=`echo "${white_arr[$middle]}" | cut -d' ' -f1`
#echo "xcrop=$xcrop"
ww=`convert -ping tmp.png -format "%w" info:`
hh=`convert -ping tmp.png -format "%h" info:`
ww1=$((xcrop+1))
dim1="${ww1}x${hh}+0+0"
ww2=`convert xc: -format "%[fx:$ww-$xcrop-1]" info:`
xoff2=$ww1
dim2="${ww2}x${hh}+${xoff2}+0"
#echo "dim1=$dim1; dim2=$dim2;"
convert tmp.png -write show: \
\( -clone 0 -crop $dim1 +repage -fuzz 10% -trim +repage -write ${inname}_left.$suffix \) \
\( -clone 0 -crop $dim2 +repage -fuzz 10% -trim +repage -write ${inname}_right.$suffix \) \
null:
rm -f tmp.png