Skip to content

Instantly share code, notes, and snippets.

@njvack
Created October 11, 2017 23:02
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 njvack/3d6ad631352a1323a574897766c6287c to your computer and use it in GitHub Desktop.
Save njvack/3d6ad631352a1323a574897766c6287c to your computer and use it in GitHub Desktop.
Convert tarfile of dicoms
#!/bin/bash
# Written by Jonah Chaiken and Nate Vack
# Support: bit_help@lists.wisc.edu
help=" Usage: convert_dcm2niix.sh <in_file> <out_file>
This program will individually convert a dicom archive file to a NIfTI file.
The input can be either a .tar file containing bzip2'd dicom slices, or a
compressed tarfile containing uncompressed slices.
Creates a temporary directory in the same directory as <out_file>, and should
clean it up afterwards.
<out_file> can be either a .nii or .nii.gz file. dcm2niix will create a .json
file suitable for BIDS along with the NIfTI data.
For help, contact bit_help@lists.wisc.edu
"
if [[ "$1" == "-h" ]]; then
echo "${help}"
exit 1
fi
if [[ $# != 2 ]]; then
echo "Usage: convert_dcm2niix <in_file> <out_file>"
exit 1
fi
in_file=$1
in_extension=${in_file##*.}
out_path=$2 # Example: /study/foo/output.nii.gz
out_dir=$( dirname ${out_path} ) # /study/foo
out_filename=$( basename ${out_path} ) # output.nii.gz
out_base=${out_filename%%.*} # output
out_extension=${out_filename##*.} # gz
# Also get the gzip status into a variable, fill it with "-z" if we want a .nii.gz
gzip_cmd="-z n"
if [[ ${out_extension} == gz ]]; then
gzip_cmd="-z i"
fi
temp_dicom_dir=$( mktemp -p "${out_dir}" -d )
if [[ $? != 0 ]]; then
echo "Could not create temporary directory in ${out_dir}! Exiting."
exit 2
fi
echo "Extracting ${in_file} to ${temp_dicom_dir}"
tar -xf $in_file -C $temp_dicom_dir
if [[ "${in_extension}" == "tar" ]]; then
echo "Decompressing dicom slices"
bunzip2 ${temp_dicom_dir}/*.bz2
fi
echo "Creating ${out_file}"
/apps/x86_64_sci7/current/bin/dcm2niix -b y -o ${out_dir} -f ${out_base} ${gzip_cmd} ${temp_dicom_dir}
echo "Cleaning up"
rm -rf $temp_dicom_dir
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment