Skip to content

Instantly share code, notes, and snippets.

@bitsgalore
Last active March 6, 2018 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitsgalore/121398e0710d0edb7cab7a19050b0151 to your computer and use it in GitHub Desktop.
Save bitsgalore/121398e0710d0edb7cab7a19050b0151 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Convert directory with JP2 images to TIFF
# Requires Kakadu (kdu_expand) and ExifTool
# Display usage message if command line does not contain expected
# number of arguments
if [ "$#" -ne 2 ] ; then
echo "Usage: JP2ToTiff.sh dirIn dirOut" >&2
exit 1
fi
# Input and output directories
dirIn="$1"
dirOut="$2"
if ! [ -d "$dirIn" ] ; then
echo "input directory does not exist" >&2
exit 1
fi
if ! [ -d "$dirOut" ] ; then
mkdir "$dirOut"
fi
# Location of Kakadu binaries
kduPath=~/kakadu
# Add Kakadu path to LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$kduPath
# Files to store Kakadu stdout, stderr
stdoutKakadu="kdu_out.txt"
stderrKakadu="kdu_err.txt"
# Remove these files if they exist already (writing to them will be done in append mode!)
if [ -f $stdoutKakadu ] ; then
rm $stdoutKakadu
fi
if [ -f $stderrKakadu ] ; then
rm $stderrKakadu
fi
while IFS= read -d $'\0' -r file ; do
# File basename, extension removed
bName=$(basename "$file" | cut -f 1 -d '.')
# Output name
outName=$bName.tiff
# Full output path
tiffOut="$dirOut/$outName"
# Kakadu command line
kduCmd="$kduPath/kdu_expand -i "$file"
-o "$tiffOut""
# Convert to TIFF
$kduCmd >>$stdoutKakadu 2>>$stderrKakadu
# Remove XMP tags, except xmp-tiff ones
# Skipping this step results in not well-formed XML
# in round-trip JP2 generation with Kakadu (uuidbox)
exiftool -xmp:all= "-all:all<xmp-tiff:all" "$tiffOut"
done < <(find $dirIn -maxdepth 1 -type f -regex '.*\.\(jp2\|JP2\)' -print0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment