Converting dicom to minc - CoBrALab/documentation GitHub Wiki

If you have a set of raw DICOMs (e.g., you had an MRI done of yourself), this script will help convert your DICOMs to MINCs, which can then be analyzed or visualized using minc-toolkit-v2.

You can copy the following into a script called dcm2mnc.sh:

#!/bin/bash
# Convert a directory of dicom files to minc

# USAGE: bash dcm2mnc.sh /path/to/dicom/dir /path/to/minc/dir

set -euo pipefail
module load minc-toolkit-v2


# Create dcm dir
dcm_dir=$1

# Create minc dir
minc_dir=$2
mkdir -p ${minc_dir}

# And mark down where we want the log file
log_file=${minc_dir}/dcm2mnc.log


# Create mincs from dicoms
# The || true makes dcm2mnc always "seem like" it evaluates properly. So script doesn't stop if we have some bad dcms, but we can
# keep everything else in strict mode (set -euo pipefail)
echo "Creating Mincs"
MINC_FORCE_V2=1 $(dcm2mnc -clobber -verbose -anon -usecoordinates -dname temp ${dcm_dir} ${minc_dir} > $log_file || true)

# Rename minc files to something more readable
echo "Renaming Mincs"
echo "===========FILE RENAMES===========" >> $log_file


# For each .mnc file
for file in $(ls ${minc_dir}/minc/*.mnc | sort -V)
do
    # Get scan date based on where file matches this pattern
    if [ $file =~ 20[0-9]{2}_[0-9]{1,2}_[0-9]{1,2} ](/CoBrALab/documentation/wiki/-$file-=~-20[0-9]{2}_[0-9]{1,2}_[0-9]{1,2}-)
        then date=$BASH_REMATCH
    fi

    # Get file name suffix (for if we have multiple files for the same sequence)
    suffix=1

    # Get info about the scan from the minc header
    acq_id=$(mincheader $file | grep  acquisition_id | grep -Eo '".*"' | sed 's/"//g' | sed 's/*//g' | tr -d ' ')
    series=$(mincheader $file | grep series_description | grep -Eo '".*"' | sed 's/"//g' | sed 's/*//g' | tr -d ' ')

    # Make a new file name
    new_file_name=${minc_dir}/${date}-${acq_id}-${series}_${suffix}.mnc

    # If we already have an mnc file (or files) for this sequence, iterate the suffix until we get a new file name
    while [ -e $new_file_name ]
    do
        let "suffix++"
        new_file_name=${minc_dir}/${date}-${acq_id}-${series}_${suffix}.mnc
    done

    # Rename file, and mark this down in the log file
    mv $file $new_file_name
    echo mv $file $new_file_name >> $log_file
    rm -r ${minc_dir}/temp
done

From the command line, execute the script with bash dcm2mnc.sh /path/to/dicom/dir /path/to/minc/dir.

This should create a directory of MINC files at /path/to/minc/dir, which can be visualized using Display from minc-toolkit-v2.