mcflirt_2stage 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/bin/bash
  2. # Author: Michael Hanke <michael.hanke@gmail.com>
  3. # License: MIT
  4. set -e
  5. set -u
  6. if [ $# -ne 3 ]; then
  7. cat << EOT
  8. This script implements MCFLIRT-based motion correction using an dedicated
  9. target image. The difference to using MCFLIRT's --reffile option is that
  10. an initial alignment to the target image can be performed with more
  11. flexibility. The actual motion correction is performed using the mean
  12. volume as a reference and a constant subsequent transformation to the
  13. final target is applied in addition. Each volume is transformed separately
  14. with a single interpolation/reslicing step that applies the combined
  15. transformations.
  16. Call this script with at least three arguments
  17. 1. Input bold time series image
  18. 2. Skull-stripped reference image
  19. 3. Output filename for the motion-corrected time series image.
  20. (4) Options to FLIRT for the alignment to the target image. Default: "-dof 6"
  21. Examples:
  22. $0 bold.nii.gz subjtmpl.nii.gz bold_mc.nii.gz "-dof 6 -cost normcorr"
  23. $0 bold.nii.gz subjtmpl.nii.gz bold_mc.nii.gz "-dof 6 -cost normcorr"
  24. EOT
  25. exit 1
  26. fi
  27. # fake test for FSL
  28. ignore=$FSLDIR
  29. inbold=$(readlink -f $1) || true
  30. ref=$(readlink -f $2) || true
  31. outbold=$(readlink -m $3)
  32. initflirtopts=${4:--dof 6}
  33. if [ -z "$inbold" ]; then
  34. echo "File not found '$1'"
  35. exit 1
  36. fi
  37. if [ -z "$ref" ]; then
  38. echo "File not found '$2'"
  39. exit 1
  40. fi
  41. outbolddir=$(dirname "${outbold}")
  42. mkdir -p "$outbolddir"
  43. wdir=$(mktemp -d --suffix=2stagemc)
  44. trap "rm -rf $wdir" SIGINT SIGTERM
  45. cd "$wdir"
  46. $FSLDIR/bin/fslmaths "$inbold" -Tmean meanbold -odt input
  47. $FSLDIR/bin/bet meanbold.nii.gz meanbold_brain -F
  48. $FSLDIR/bin/flirt ${initflirtopts} -in meanbold_brain -ref "$ref" -omat meanbold2brain.mat
  49. $FSLDIR/bin/mcflirt -in "$inbold" -reffile meanbold_brain -mats -plots -out mc
  50. cp mc.par "$($FSLDIR/bin/remove_ext "$outbold")_mcparams.txt"
  51. for i in mc.mat/MAT*; do convert_xfm -omat mc.mat/tmpl_$(basename $i) -concat meanbold2brain.mat $i; done
  52. mkdir bold
  53. $FSLDIR/bin/fslsplit "$inbold" bold/
  54. mkdir mc
  55. for i in bold/*.nii*; do
  56. bname=$(basename $i)
  57. idx=${bname%.nii*}
  58. $FSLDIR/bin/flirt -in "$i" -ref "$ref" -applyxfm -init mc.mat/tmpl_MAT_${idx} -out mc/${idx} -interp sinc; done
  59. $FSLDIR/bin/fslmerge -tr "$outbold" mc/* $(fslval "$inbold" pixdim4)
  60. cd -
  61. rm -rf "$wdir"