Merge remote branch 'remotes/origin/ocropus'
[dja/scandal.git] / scan2pages.sh
1 #!/bin/bash
2
3 function usage {
4 cat >&2 << __EOF__ 
5 Usage: $0 [-vfpsmutb] [-D DPI] [-d depth] [-F format] pdffile outdir
6 Convert pdffile - a pdf of scanned facing pages - to a set of images in outdir,
7 each with only one page.
8 OPTIONS:
9         -v: Be verbose.
10         -d depth: Use given depth. Default is 1 for black and white, 8 for colour/gray.
11                 Unpaper can only handle up to 8.
12         -D dpi: Use given DPI. Colour scans on library scanners are usually 300, bw 400.
13         -e extension: use the output format signified by the extension. Default is png
14         -b: Optimize for BeBook One.
15         -1: each physical page contains one logical page
16         -2: each physical page contains two logical pages
17                 (neither specified: try to figure it out)
18 __EOF__
19 }
20
21
22 ## Setup and utilities ##
23 source $(dirname $0)/my_seq.sh
24
25 ## Process flags ##
26 convertflags=
27 unpaperflags=
28 depthset=
29 depth=
30 dpi=
31 skipmask=
32 verbose=
33 extension="png"
34 bebook=
35 logperphys=
36 while getopts 'vd:D:e:b12' OPTION
37 do
38         case $OPTION in
39         v)      verbose=1
40                 convertflags="$convertflags -verbose"
41                 unpaperflags="$unpaperflags -v --time"
42                 ;;
43         d)      depth="$OPTARG"
44                 ;;
45         D)      dpi=$OPTARG
46                 ;;
47         e)      extension="$OPTARG"
48                 ;;
49         b)      bebook=1
50                 ;;
51         1)      logperphys=1
52                 ;;
53         2)      logperphys=2
54                 ;;
55         ?)      usage
56                 exit 2
57                 ;;
58         esac
59 done
60 shift $(($OPTIND - 1))
61
62 # check we have an input and output!
63 if [[ $# != 2 ]]; then
64         echo "Wrong number of parameters (2 required, $# given: [$@])" >&2
65         usage
66         exit 2
67 fi
68
69 scanfile=$1
70 outdir=$2
71
72 filedir=$(dirname $1)
73 base=$(basename $1 .pdf)
74
75 # make the output dir
76 mkdir -p $outdir
77
78
79 # guess at DPI, unless it's been set
80 # the scans do not seem to accurately reflect their resolution.
81 if [[ "$dpi" = "" ]]; then
82         # %k gives the number of colours/shades in the image.
83         # 2 for b/w, and the scanner seems to default to 400 dpi for that
84         # 256 for greyscale, which has to be selected manually (so I'm assuming 300 for no good reason)
85         # 31564 for colour, which defaults to 300
86         if [[ $( convert $scanfile[0] -format "%k" info: || exit 1 ) == 2 ]]; then
87                 dpi=400;
88         else
89                 dpi=300
90         fi
91         if [[ $verbose == 1 ]]; then
92                 echo "DPI guessed at $dpi."
93         fi
94 fi
95
96 # guess at depth, unless it's been set
97 if [[ "$depth" = "" ]]; then
98         if [[ $( convert $scanfile[0] -format "%k" info: || exit 1 ) == 2 ]]; then
99                 depth=1;
100         else
101                 depth=8
102         fi
103         if [[ $verbose == 1 ]]; then
104                 echo "Depth guessed at $depth."
105         fi
106 fi
107
108 # figure out the number of pages
109 dscname=$outdir/${base}.dsc
110 pdf2dsc $scanfile $dscname || exit 1
111 pages=$(awk '$1 ~ "%%Pages" {print $2}' $dscname)
112 echo "Got $pages page(s)."
113 rm $dscname
114
115 # process pages 1 by 1 to avoid convert gobbling all the memory
116 for scanpgnum in `$my_seq 1 $pages`; do
117         echo "Processing page $scanpgnum."
118         
119         scanpgnum=$(printf '%03d' $scanpgnum)
120         
121         # convert from pdf
122         scanpg=$outdir/scanpg-${scanpgnum}.png
123         if [ ! -e $scanpg ]; then
124                 convert $convertflags -depth $depth -density $dpi $scanfile[$(expr $scanpgnum - 1)] \
125                         $scanpg || exit 1
126         fi;
127         
128 done;
129
130 # do ocr binarise
131 if [ -e $outdir/scanpgs ]; then
132         #assume (for the sake of speed in repeated runs) that
133         # if the last file exists, the process completed successfully
134         if [ -e $outdir/scanpgs/$(printf '%04d' $pages).bin.png ]; then
135                 [[ $verbose ]] && echo Binarisation already complete
136         else
137                 rm -r $outdir/scanpgs
138         fi
139 fi
140 [ -e $outdir/scanpgs ] || ocropus book2pages $outdir/scanpgs $outdir/scanpg-*.png || exit 1
141
142 # process each binarised scan page
143 for scanpgnum in  `$my_seq 1 $pages`; do
144
145         binscanpg=$outdir/scanpgs/$(printf '%04d' $scanpgnum).bin.png
146         scanpgnum=$(printf '%03d' $scanpgnum)
147         scanpg=$outdir/scanpg-${scanpgnum}.png
148
149         # preprocess scanned page
150         cleanscanpg=$outdir/scanpg-clean-${scanpgnum}.pnm
151         if [ ! -e $cleanscanpg ]; then
152                 # create mask: 
153                 # ... downscale, blur,
154                 convert $convertflags -resize 10% -depth 8 -blur 10 -median 2 $scanpg $outdir/scanpg-mask-${scanpgnum}.png ||exit 1
155
156                 # ... get crop co-ords. They're off by ~2 as I don't know how to
157                 # properly correct for the border.
158                 cropcords=$(convert -border 1x1 -bordercolor '#000' -resize 1000% -trim -fuzz 90% -format "%wx%h%O" $outdir/scanpg-mask-${scanpgnum}.png info: || exit 1)
159
160                 # ... crop and despeckle? the final pre-prepared image
161                 convert $convertflags -crop $cropcords $binscanpg  $cleanscanpg || exit 1
162         fi;
163         
164         # check it hasn't mostly disappeared - e.g. if the scan was all black
165         # (e.g. forgot to put the book down when you first hit scan)
166         if [[ $(convert  $cleanscanpg -format '%[fx:s.w*s.h>1000]' info:) = "0" ]]; then
167                 [[ $verbose == 1 ]] && echo "Discarding pg ${scanpgnum}: not enough remains after masking."
168                 continue; 
169         fi;
170         
171         #unpaper it
172         physpgbase=$outdir/physpg-${scanpgnum}
173         if [ ! -e ${physpgbase}-1.pnm ] || [ ! -e ${physpgbase}-2.pnm ]; then
174                 # most of unpaper's processing is redundant given ocropus, and somewhat too agressive
175                 unpaper $unpaperflags --layout double --overwrite -op 2 \
176                         --no-processing \
177                         $cleanscanpg ${physpgbase}-%01d.pnm || exit 1
178
179         fi;
180         
181         for physpgnum in $($my_seq 1 2); do
182                 echo Processing physical page ${physpgnum}.
183                 
184                 physpg=${physpgbase}-${physpgnum}.pnm #$physpgbase has $outdir/ already
185                 
186                 cleanphyspg=$outdir/physpg-clean-${scanpgnum}-${physpgnum}.pnm
187                 
188                 if [ ! -e $cleanphyspg ]; then
189                         # remask and retrim. FIXME: may throw off 2page detection
190                         convert $convertflags -resize 10% -depth 8 -gamma 0.01 -median 2 $physpg $outdir/physpg-mask-${scanpgnum}-${physpgnum}.png ||exit 1
191
192                         # Trim #-border 1x1 -bordercolor '#fff' -trim -fuzz 30% 
193                         # binarise is so effective, try something << 90%
194                         cropcords=$(convert -trim -fuzz 50%\
195                          -resize 1000% -format "%wx%h%O" $outdir/physpg-mask-${scanpgnum}-${physpgnum}.png info: || exit 1)
196                 
197                         [[ $verbose ]] && echo Crop co-ords: $cropcords
198
199                         # ... crop and despeckle? the final pre-prepared image
200                         convert $convertflags -crop $cropcords $physpg $cleanphyspg || exit 1
201                 fi;
202
203                 # check it hasn't mostly disappeared, warn viciously if it has!
204                 if [[ $(convert  $cleanphyspg -format '%[fx:s.w*s.h>1000]' info:) = "0" ]]; then
205                         echo "Warning: discarding physical pg ${scanpgnum}-${physpgnum}: not enough remains after masking."
206                         continue;
207                 fi;
208
209                 #detect if the page is 2-up
210
211                 if [[ $logperphys == 2 ]] || ( [[ $logperphys != 1 ]] && $(dirname $0)/detect2pages.sh ${cleanphyspg} ${scanpgnum} ${physpgnum} ); then
212                         if [[ $verbose == 1 ]]; then
213                                 echo "Resplitting physical page ${physpgnum}."
214                         fi
215                         unpaper $unpaperflags --pre-rotate 90 --layout double --overwrite \
216                          -op 2 --no-blackfilter --no-grayfilter --no-noisefilter \
217                          --no-blurfilter $cleanphyspg $outdir/logpg-${scanpgnum}-${physpgnum}-%01d.pnm || exit 1
218                 else
219                         cp $cleanphyspg $outdir/logpg-${scanpgnum}-${physpgnum}-1.pnm
220                 fi;
221
222                 #prepare for ocr
223                 convert $convertflags $outdir/logpg-${scanpgnum}-${physpgnum}-?.pnm $outdir/logpg-${scanpgnum}-${physpgnum}-%01d.png || exit 1
224
225                 #final convert and clean w/ bebook optimisation
226                 if [[ $bebook ]]; then #1200x1600
227                         convert $convertflags $outdir/logpg-${scanpgnum}-${physpgnum}-?.pnm -trim $outdir/final-${scanpgnum}-${physpgnum}-%01d.${extension} || exit 1
228                 else
229                         convert $convertflags $outdir/logpg-${scanpgnum}-${physpgnum}-?.pnm $outdir/final-${scanpgnum}-${physpgnum}-%01d.${extension} || exit 1
230                 fi
231
232         done;
233
234 done
235
236 #don't try full ocr, it's a waste of time.
237 #rm -rf $outdir/logpgs
238 #ocropus book2pages $outdir/logpgs $outdir/logpg-*.png
239 #ocropus pages2lines $outdir/logpgs
240 #ocropus lines2fsts $outdir/logpgs
241 #ocropus fsts2bestpaths $outdir/logpgs
242 #ocropus buildhtml $outdir/logpgs > $outdir/out.html
243
244 mkdir -p $outdir/pages
245 mv $outdir/final-*.${extension} $outdir/pages
246         

UCC git Repository :: git.ucc.asn.au