How to make pictures wider in LaTeX? - pdf

I have tried to make a several pictures in one big figure. However, they are placed very close to each other. I need to add more space between them (between pictures in horizontal and in vertical).
Code:
\documentclass{article}
\usepackage{subcaption}
\usepackage{graphicx}
\begin{document}
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{figs/solutions/transaction_solution.png}
\caption{Transaction level isolation}
\label{fig:subim1}
\end{subfigure}
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{figs/solutions/locking_solution.png}
\caption{Record locking}
\label{fig:subim2}
\end{subfigure}
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{figs/solutions/cache_solution.png}
\caption{Shared cache synchronization}
\label{fig:subim3}
\end{subfigure}
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{figs/solutions/message_broker_solution.png}
\caption{Message broker sequentializing}
\label{fig:subim4}
\end{subfigure}
\captionsetup{justification=centering,margin=1cm}
\caption{\label{fig:knng} Existing synchronization approaches for multiple server applications}
\end{figure}
\end{document}

Depending on what you want, you can have either images sticking to margins on both sides with some space in the middle or have them uniformly distributed over page. In both cases use \hspace{\hfill} in the middle as a filler. The former case does not require anything else. However, in the latter case, you would also need to add \hspace{\hfill} at both sides; this is the case in the example.
I also use a custom length since images seem to have the same size so you wouldn't need to repeat yourself each time you make a change.
Unfortunately, I can't post images this time.
The code
\documentclass[12pt]{article}
\usepackage{graphicx}
\usepackage{subcaption}
\captionsetup{format=hang} % <--- added
\usepackage{showframe} % Draws frames around a page
\renewcommand*{\ShowFrameLinethickness}{0.2pt}
\renewcommand*{\ShowFrameColor}{\color{blue}}
\newlength\sfigwidth
\begin{document}
\setlength\sfigwidth{0.37\textwidth}
\begin{figure}[h]
\hspace{\fill}% % <--- cases uniform redistribution
\begin{subfigure}[t]{\sfigwidth}
\includegraphics[width=\linewidth]{example-image}
\caption{Transaction level isolation -- extra wording for demo}
\label{fig:subim1}
\end{subfigure}%
\hspace{\fill}%
\begin{subfigure}[t]{\sfigwidth}
\includegraphics[width=\linewidth]{example-image}
\caption{Record locking}
\label{fig:subim2}
\end{subfigure}%
\hspace{\fill} % <--- cases uniform redistribution
\vspace{3ex}
\hspace{\fill}%
\begin{subfigure}[t]{\sfigwidth}
\includegraphics[width=\linewidth]{example-image}
\caption{Shared cache synchronization}
\label{fig:subim3}
\end{subfigure}%
\hspace{\fill}%
\begin{subfigure}[t]{\sfigwidth}
\includegraphics[width=\linewidth]{example-image}
\caption{Message broker sequentializing}
\label{fig:subim4}
\end{subfigure}%
\hspace{\fill}
\captionsetup{justification=centering,margin=1cm}
\caption{\label{fig:knng} Existing synchronization approaches for multiple server applications}
\end{figure}
\end{document}

Use \hspace and \vspace between the subfigures.
\documentclass{article}
\usepackage{subcaption}
\usepackage{graphicx}
\begin{document}
\begin{figure}[h]
\centering
\begin{subfigure}{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{placeholder_1.png}
\caption{Transaction level isolation}
\label{fig:subim1}
\end{subfigure}%
\hspace{3em}%
\vspace{1em}
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{placeholder_1.png}
\caption{Record locking}
\label{fig:subim2}
\end{subfigure}%
\vspace{1em}
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{placeholder_1.png}
\caption{Shared cache synchronization}
\label{fig:subim3}
\end{subfigure}%
\hspace{3em}%
\begin{subfigure}[b]{0.4\textwidth}
\centering
\includegraphics[scale=0.6]{placeholder_1.png}
\caption{Message broker sequentializing}
\label{fig:subim4}
\end{subfigure}
\captionsetup{justification=centering,margin=1cm}
\caption{\label{fig:knng} Existing synchronization approaches for multiple server applications}
\end{figure}
\end{document}

Related

gnuplot 'set title' with sprintf : representing angle in terms of fractions of pi

I'd like to run a gnuplot .inp file so all the angles in the script show up automatically in the title as fractions based on the Greek letter pi - instead of a decimal form for the angle. I already know how to use {/Symbol p}, but that is a manual intervention that is impractical in this case.
I have an example sprintf line in a gnuplot input file which can produce nice title information :
angle=( (3*pi) /4 )
set title sprintf ("the angle is %g radians", angle)
plot sin(x)
... the output file (e.g. svg) or terminal (e.g. wxt) shows "2.35619", which is correct, however ; it would be nice to see the Greek letter for pi and the fraction itself, as is typically read off of a polar plot, e.g " 3/4 pi". Likewise for more complex or interesting representations of pi, such as "square root of two over two".
I already know I can manually go into the file and type in by hand "3{/Symbol p}/4", but this needs to be done automatically, because the actual title I am working with has numerous instances of pi showing up as a result of a setting of an angle.
I tried searching for examples of gnuplot being used with sprintf to produce the format of the angle I am interested in, and could not find anything. I am not aware of sprintf being capable of this. So if this is in fact impossible with gnuplot and sprintf, it will be helpful to know. Any tips on what to try next appreciated.
UPDATE: not a solution, but very interesting, might help :
use sprintf after the 'plot' to set the title that appears in the key (but not the overall title):
gnuplot setting line titles by variables
so for example here, the idea would be :
foo=20
plot sin(x)+foo t sprintf ("The angle is set to %g", foo)```
Here is an attempt to define a function to find fractions of Pi.
Basically, sum (check help sum) is used to find suitable multiples/fractions of Pi within a certain tolerance (here: 0.0001). It is "tested" until a denominator of 32. If no integer number is found, the number itself is returned.
In principle, the function could be extended to find multiples or fractions of roots, sqrt(2) or sqrt(3), etc.
This approach can certainly be improved, maybe there are smarter solutions.
Script:
### format number as multiple of pi
reset session
$Data <<EOD
1.5707963267949
-1.5707963267949
6.28318530717959
2.35619449019234
2.0943951023932
-0.98174770424681
2.24399475256414
1.0
1.04
1.047
1.0471
1.04719
EOD
set xrange[-10:10]
set yrange[:] reverse
set offset 0.25,0.25,0.25,0.25
set key noautotitle
dx = 0.0001
fPi(x) = (_x=x/pi, _p=sprintf("%g",x), _d=NaN, sum [_i=1:32] \
(_d!=_d && (abs(_x*_i - floor(_x*_i+dx)) < dx) ? \
(_n=floor(_x*_i+dx),_d=_i, \
_p=sprintf("%sπ%s",abs(_n)==1?_n<0?'-':'':sprintf("%d",_n),\
abs(_d)==1 ? '' : sprintf("/%d",_d)),0) : 0 ), _p)
plot $Data u (0):0:(fPi($1)) w labels font "Times New Roman, 16"
### end of script
Result:
I have [1] a workaround below that might be feasible, and [2] apparently what I was looking for below that (I am writing this in haste). I will mark the question "answered" anyway. To avoid reproducing theozh's script, I offer :
[1]:
add three lines to theozh's script - ideally, immediately before the 'plot' command :
set title sprintf ("Test: %g $\\sqrt{\\pi \\pi \\pi \\pi}$", pi)
set terminal tikz standalone
set output 'gnuplot_test.tex'
one can observe a little testing going on with nonsensical expressions of pi - it is just to see the vinculum extend, and this is a hasty thing - and the double-escapes - they appear to have made it to Stack Overflow correctly.
change the 'plot' line to remove the Times Roman part, but this might not be necessary :
plot $Data u (0):0:(fPi($1)) w labels
importantly, edit gnuplot_test.tex so an \end{document} is on the last line.
run 'pdflatex gnuplot_test.tex'.
This should help move things along - it appears the best approach is to go into the LaTeX world for this - thanks. I tried cairolatex pdf and eps but I was very confused with the LaTeX output. the tikz works almost perfectly.
[2]: What I was looking for : put this below the fPi(x) expression in gnuplot :
set title sprintf ("Testing : \n wxt terminal : \
%g %s %s %s \n tikz output : $\\sqrt{\\pi \\pi \\pi \\pi}$", \
pi, fPi(myAngle01), fPi(myAngle02), fPi(myAngle03) )
# set terminal tikz standalone
# set output 'gnuplot_test.tex'
plot $Data u (0):0:(fPi($1)) w labels t sprintf ("{/Symbol p}= %g, %s, %s, %s, %s", \
pi, fPi(pi), fPi(myAngle01), fPi(myAngle02), fPi(myAngle03) )
... the wxt terminal displays the angles as fractions of pi. I didn't test the output in the LaTeX pipeline - remove if undesired. I think the gnuplot script has to be written for the terminal or output desired - but at least the values can be computed - instead of writing them in "manually".

How can I get the \rhead superiorly to the top and \chead down?

MWE
\documentclass[12pt,a4paper]{article}
\usepackage{enumitem}
\usepackage{fancyhdr}
\usepackage[margin=3cm]{geometry}
\usepackage{pgfplots}
\newlength{\tabcont}
\setlength{\parindent}{0.0in}
\setlength{\parskip}{0.05in}
\title{Assignment 4}
\newcommand{\course}{lipsum}
\newcommand{\coursen}{lipsum}
\newcommand{\semester}{lipsum}
\newcommand{\TDAG}{lipsum}
\newcommand{\campus}{lipsum}
\newcommand{\dept}{lipsum}
\pagestyle{fancyplain}
\headheight 56.2pt
\chead{\campus \\ \dept \\ \course \\ \coursen }
\lhead{\TDAG}
\rfoot{\thepage}
\begin{document}
\maketitle
Submit the following problems which are given in the tutorial 4 as your Assignment 4.
\begin{enumerate}
\item In question 19 ,part (d).
\end{enumerate}
\end{document}
The solution I want
After compiling the above document, the \rhead and \chead are similar in position of height. I want the \rhead to be up and \chead to be down/after \rhead.
I have reviewed a post that included something like \header[C], but that did not work. I am using Miktex + texMaker. But do provide an example if you know how to do it with \header[C] :)
Screenshots
Current one
What I get when I compile the above code
The solution that I need
I need code to get this look
You could just wrap the central header in a minipage:
\documentclass[12pt,a4paper]{article}
\usepackage{enumitem}
\usepackage{fancyhdr}
\usepackage[margin=3cm]{geometry}
\usepackage{pgfplots}
\newlength{\tabcont}
\setlength{\parindent}{0.0in}
\setlength{\parskip}{0.05in}
\title{Assignment 4}
\newcommand{\course}{lipsum}
\newcommand{\coursen}{lipsum}
\newcommand{\semester}{lipsum}
\newcommand{\TDAG}{lipsum}
\newcommand{\campus}{lipsum}
\newcommand{\dept}{lipsum}
\pagestyle{fancyplain}
\headheight 56.2pt
\chead{\begin{minipage}[t]{.3\textwidth}
\centering
\campus \\ \dept \\ \course \\ \coursen
\end{minipage}}
\lhead{\TDAG}
\rfoot{\thepage}
\begin{document}
\maketitle
Submit the following problems which are given in the tutorial 4 as your Assignment 4.
\begin{enumerate}
\item In question 19 ,part (d).
\end{enumerate}
\end{document}

Is there an Awk- or Lisp-like programming language that can process a stream of s-expressions?

I have been creating some PCB footprints in KiCad recently, which are stored in s-expression files with data that looks like this:
(fp_text user %R (at 0 5.08) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_line (start -27.04996 -3.986) (end -27.24996 -3.786) (layer F.Fab) (width 0.1))
(pad "" np_thru_hole circle (at 35.56 0) (size 3.175 3.175) (drill 3.175) (layers *.Cu *.Mask)
(clearance 1.5875))
(pad 96 smd rect (at 1.25 3.08473) (size 0.29972 1.45034) (layers F.Cu F.Paste F.Mask)
(clearance 0.09906))
I would like to be able to write shell one-liners to efficiently edit multiple parameters. I would normally use Awk for something like this, but the recursive nature of s-expressions makes it ill-suited for the task. I would like to know if there is a programming language with an interpreter designed to handle piped data and can process s-expressions natively. Perhaps a data-driven dialect of Lisp would do this, but I'm not sure where to look.
In summary, I would like to be able to make quick edits to an s-expression file in a similar manner to the way Awk lets me process columns of data line-by-line; only in the case of s-expressions the processing would be performed level-by-level.
Example: find all of the pad expressions of type smd with (size 0.29972 1.45034), and renumber each one based its position.
Simple script
Here is an example in Common Lisp, assuming your input is in file "/tmp/ex.cad" (it could also be obtained by reading the output stream of a process).
The main processing loop consists in opening the file in order to obtain an input stream in (which is automatically closed at the end of with-open-file), loop over all forms in the file, process them and possibly output them to standard output. You could complexify the process as much as you want, but the following is good enough:
(with-open-file (in #"/tmp/ex.cad")
(let ((*read-eval* nil))
(ignore-errors
(loop (process-form (read in))))))
Suppose you want to increase the width of fp_line entries, ignore fp_text and otherwise print the form unmodified, you could define process-form as follows:
(defun process-form (form)
(destructuring-bind (header . args) form
(print
(case header
(fp_line (let ((width (assoc 'width args)))
(when width (incf (second width) 3)))
form)
(fp_text (return-from process-form))
(t form)))))
Running the previous loop would then output:
(FP_LINE (START -27.04996 -3.986) (END -27.24996 -3.786) (LAYER F.FAB) (WIDTH 3.1))
(PAD "" NP_THRU_HOLE CIRCLE (AT 35.56 0) (SIZE 3.175 3.175) (DRILL 3.175) (LAYERS *.CU *.MASK) (CLEARANCE 1.5875))
(PAD 96 SMD RECT (AT 1.25 3.08473) (SIZE 0.29972 1.45034) (LAYERS F.CU F.PASTE F.MASK) (CLEARANCE 0.09906))
More safety
From there, you can build more elaborate pipelines, with the help of pattern matching or macros if you want. You have to take into account some safety measures, like binding *read-eval* to nil, using with-standard-io-syntax
and binding *print-circte* to T as suggested by tfb, disallowing fully qualified symbols (by having #\: signal an error), etc. Ultimately, like Shell scripts one-liners, the amount of precautions you add is based on how much you trust your inputs:
;; Load libraries
(ql:quickload '(:alexandria :optima))
;; Import symbols in current package
(use-package :optima)
(use-package :alexandria)
;; Transform source into a stream
(defgeneric ensure-stream (source)
(:method ((source pathname)) (open source))
(:method ((source string)) (make-string-input-stream source))
(:method ((source stream)) source))
;; make reader stop on illegal characters
(defun abort-reader (&rest values)
(error "Aborting reader: ~s" values))
Dedicated package for KiCad symbols (exporting is optional):
(defpackage :kicad
(:use)
(:export #:fp_text
#:fp_line
#:pad
#:size))
Loop over forms:
(defmacro do-forms ((form source &optional result) &body body)
"Loop over forms from source, eventually return result"
(with-gensyms (in form%)
`(with-open-stream (,in (ensure-stream ,source))
(with-standard-io-syntax
(let ((*read-eval* nil)
(*print-circle* t)
(*package* (find-package :kicad))
(*readtable* (copy-readtable)))
(set-macro-character #\: #'abort-reader nil)
(loop
:for ,form% := (read ,in nil ,in)
:until (eq ,form% ,in)
:do (let ((,form ,form%)) ,#body)
:finally (return ,result)))))))
Example:
;; Print lines at which there is a size parameter, and its value
(let ((line 0))
(labels ((size (alist) (second (assoc 'kicad:size alist)))
(emit (size) (when size (print `(:line ,line :size ,size))))
(process (options) (emit (size options))))
(do-forms (form #P"/tmp/ex.cad")
(match form
((list* 'kicad:fp_text _ _ options) (process options))
((list* 'kicad:fp_line options) (process options))
((list* 'kicad:pad _ _ _ options) (process options)))
(incf line))))
Output
(:LINE 2 :SIZE 3.175)
(:LINE 3 :SIZE 0.29972)
Just write a simple Lisp or Scheme script which loops on reading and processes recursively your s-expr as required. On Linux I would recommend using Guile (a good Scheme interpreter) or perhaps Clisp (a simple Common Lisp implementation) or even SBCL (a very powerful Common Lisp).
(You might consider DSSSL, but in your case it is overkill)
Notice that your sample input is not an S-expression, because (layer F.Fab) is not one (since after the dot you should have another s-expression, not an atom like Fab). I guess it is a typo and should be (layer "F.Fab"); or maybe your KiCad software don't process S-expressions, but some other input language (which should be specified, probably in EBNF notation) inspired by S-expressions.
Notice also that KiCad is a free software and has a community with forums and a mailing list. Perhaps you should ask your actual problem there?
PS. We don't know what transformation you have in mind, but Scheme and Common Lisp are really fit for such tasks. In most cases they are extremely simple to code (probably a few lines only).

festival 2.4: why do some voices not work with singing mode?

voice_kal_diphone and voice_ral_diphone work correctly in singing mode (there's vocal output and the pitches are correct for the specified notes).
voice_cmu_us_ahw_cg and the other CMU voices do not work correctly--there's vocal output but the pitch is not changed according to the specified notes.
Is it possible to get correct output with the higher quality CMU voices?
The command line for working (pitch-affected) output is:
text2wave -mode singing -eval "(voice_kal_diphone)" -o song.wav song.xml
The command line for non-working (pitch-unaffected) output is:
text2wave -mode singing -eval "(voice_cmu_us_ahw_cg)" -o song.wav song.xml
Here's song.xml:
<?xml version="1.0"?>
<!DOCTYPE SINGING PUBLIC "-//SINGING//DTD SINGING mark up//EN" "Singing.v0_1.dtd" []>
<SINGING BPM="60">
<PITCH NOTE="A4,C4,C4"><DURATION BEATS="0.3,0.3,0.3">nationwide</DURATION></PITCH>
<PITCH NOTE="C4"><DURATION BEATS="0.3">is</DURATION></PITCH>
<PITCH NOTE="D4"><DURATION BEATS="0.3">on</DURATION></PITCH>
<PITCH NOTE="F4"><DURATION BEATS="0.3">your</DURATION></PITCH>
<PITCH NOTE="F4"><DURATION BEATS="0.3">side</DURATION></PITCH>
</SINGING>
You may also need this patch to singing-mode.scm:
## -339,7 +339,9 ##
(defvar singing-max-short-vowel-length 0.11)
(define (singing_do_initial utt token)
- (if (equal? (item.name token) "")
+ (if (and
+ (not (equal? nil token))
+ (equal? (item.name token) ""))
(let ((restlen (car (item.feat token 'rest))))
(if singing-debug
(format t "restlen %l\n" restlen))
To set up my environment I used the festvox fest_build script. You can also download voice_cmu_us_ahw_cg separately.
It seems that the problem is in phones generation.
voice_kal_diphone uses UniSyn synthesis model, while voice_cmu_us_ahw_cg uses ClusterGen model. The last one has own intonation and duration model (state-based) instead of phone intonation/duration: possibly you noticed that duration didn't changed too in generated 'song'.
singing-mode.scm tries to extract each syllable and modify its frequency. In case of ClusterGen model wave generator simply ignores syllables frequencies and durations set in Target due to different modelling.
As a result we have better voice quality (based on statistic model), but can't change frequency directly.
Very good description of generation pipeline can be found here.

High-res images from PDFS

I'm working on a project in which I need to extract a TIFF per page from multi-page PDFs. The PDFs contain images only and there is one image per page (I believe they were made on some kind of photocopier/scanner, but haven't confirmed this). The TIFFs are then used to create several other derivative versions of the document so the higher the resolution the better.
I've found two recipes, both with helpful aspects, but neither is ideal. Hoping someone can help me tune one of them, or offer a third option.
Recipe 1, pdfimages and ImageMagick:
First do:
$ pdfimages $MY_PDF.pdf foo"
Which results in several .pbm files (named foo-000.pbm, foo-001.pbm), etc.
Then for each *.pbm do:
$ convert $each -resize 3200x3200\> -quality 100 $new_name.tif
Pro: The resultant TIFFs are a healthy 3300+ pixels on the long dimension, (-resize just serves to normalize everything)
Con: The orientation of the pages is lost, and they come out rotated different directions (they follow logical patterns, so probably they are the orientation in which they were fed to the scanner??).
Recipe 2 Imagemagick solo:
convert +adjoin $MY_PDF.pdf pages.tif
This gives me a TIFF per page (pages-0.tif, pages-1.tif, etc.).
Pro: Orientation stays!
Con: The long dimension of the resultant file is < 800 px, which is too small to be useful, and it looks as though there is some compression applied.
How can I ditch the scaling of the image stream in the PDF, but retain the orientation? Is there some more magick in ImageMagick that I'm missing? Something else entirely?
Sorry for the noise on this old topic, but google took me here as one of the top results and it might take others, so I thought I'd post the solution for the TO's question that I found here: http://robfelty.com/2008/03/11/convert-pdf-to-png-with-imagemagick
In Short: You have to tell ImageMagick at which density it should scan the PDF.
so convert -density 600x600 foo.pdf foo.png will tell ImageMagick to treat the PDF as if it had a 600dpi resolution and thus output much larger PNGs. In my case, the resulting foo.png was sized 5000x6600px. You can optionally add -resize 3000x3000 or whatever size you require and it will be scaled down.
Note that as long as you only have vector images or text in your PDF-files, density might be set as high as needed. If the PDF contains rasterized images, it won't look good if you set it higher than those images' dpi, surprise! :)
Chris
I wanted to share my solution...it may not work for everyone, but since nothing else has come around maybe it will help someone else. I wound up going with the first option in my question, which was to use pdfimages to get large images that were rotated every which way. I then found a way to use OCR and word counts to guess at the orientation, which got me from (estimated) 25% rotated accurately to above 90%.
The flow is as follows:
Use pdfimages (apt-get install poppler-utils) to get a set of pbm
files (not shown below).
For each file:
Make four versions, rotated 0, 90, 180, and 270 degrees (I refer to them as "north", "east", "south", and "west" in my code).
OCR each. The two with the lowest word count are likely the right-side up and upside down versions. This was over 99% accurate in my set of images processed to date.
From the two with the lowest word count, run the OCR output through a spell check. The file with the least spelling errors (i.e. most recognizable words) is likely to be correct. For my set this was about 93% (up from 25%) accurate based on a sample of 500.
YMMV. My files are bitonal and highly textual. The source images are an average of 3300 px on the long side. I can't speak to greyscale or color, or files with a lot of images. Most of my source PDFs are bad scans of old photocopies, so the accuracy might be even better with cleaner files. Using -despeckle during the rotation made no difference and slowed things down considerably (~5×). I chose ocrad for speed and not accuracy since I only need rough numbers and am throwing away the OCR. Re: performance, my nothing-special Linux desktop machine can run the whole script over about 2-3 files/per second.
Here's the implementation in a simple bash script:
#!/bin/bash
# Rotates a pbm file in place.
# Pass a .pbm as the only arg.
file=$1
TMP="/tmp/rotation-calc"
mkdir $TMP
# Dependencies:
# convert: apt-get install imagemagick
# ocrad: sudo apt-get install ocrad
ASPELL="/usr/bin/aspell"
AWK="/usr/bin/awk"
BASENAME="/usr/bin/basename"
CONVERT="/usr/bin/convert"
DIRNAME="/usr/bin/dirname"
HEAD="/usr/bin/head"
OCRAD="/usr/bin/ocrad"
SORT="/usr/bin/sort"
WC="/usr/bin/wc"
# Make copies in all four orientations (the src file is north; copy it to make
# things less confusing)
file_name=$(basename $file)
north_file="$TMP/$file_name-north"
east_file="$TMP/$file_name-east"
south_file="$TMP/$file_name-south"
west_file="$TMP/$file_name-west"
cp $file $north_file
$CONVERT -rotate 90 $file $east_file
$CONVERT -rotate 180 $file $south_file
$CONVERT -rotate 270 $file $west_file
# OCR each (just append ".txt" to the path/name of the image)
north_text="$north_file.txt"
east_text="$east_file.txt"
south_text="$south_file.txt"
west_text="$west_file.txt"
$OCRAD -f -F utf8 $north_file -o $north_text
$OCRAD -f -F utf8 $east_file -o $east_text
$OCRAD -f -F utf8 $south_file -o $south_text
$OCRAD -f -F utf8 $west_file -o $west_text
# Get the word count for each txt file (least 'words' == least whitespace junk
# resulting from vertical lines of text that should be horizontal.)
wc_table="$TMP/wc_table"
echo "$($WC -w $north_text) $north_file" > $wc_table
echo "$($WC -w $east_text) $east_file" >> $wc_table
echo "$($WC -w $south_text) $south_file" >> $wc_table
echo "$($WC -w $west_text) $west_file" >> $wc_table
# Take the bottom two; these are likely right side up and upside down, but
# generally too close to call beyond that.
bottom_two_wc_table="$TMP/bottom_two_wc_table"
$SORT -n $wc_table | $HEAD -2 > $bottom_two_wc_table
# Spellcheck. The lowest number of misspelled words is most likely the
# correct orientation.
misspelled_words_table="$TMP/misspelled_words_table"
while read record; do
txt=$(echo $record | $AWK '{ print $2 }')
misspelled_word_count=$(cat $txt | $ASPELL -l en list | wc -w)
echo "$misspelled_word_count $record" >> $misspelled_words_table
done < $bottom_two_wc_table
# Do the sort, overwrite the input file, save out the text
winner=$($SORT -n $misspelled_words_table | $HEAD -1)
rotated_file=$(echo $winner | $AWK '{ print $4 }')
mv $rotated_file $file
# Clean up.
if [ -d $TMP ]; then
rm -r $TMP
fi