MotionCorrection_rsfmri.m 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. % Input folder path containing fMRI data
  2. input_folder = "C:\Users\aswen\Desktop\TestingData\Aswendt_qc_data\proc_data";
  3. % Get all rsfMRI files in the input folder
  4. searchpath = fullfile(input_folder, '**', 'func', '*nii.gz');
  5. rsfmri_files = dir(searchpath);
  6. rsfmri_files = fullfile({rsfmri_files.folder}, {rsfmri_files.name});
  7. % Parameters for motion correction
  8. transformType = 'translation'; % Type of transformation (e.g., translation)
  9. [optimizer,metric] = imregconfig("multimodal")
  10. % Loop through each rsfMRI file for motion correction
  11. for i = 1:numel(rsfmri_files)
  12. % Read file
  13. file = rsfmri_files{i};
  14. % Load the 4D rsfMRI image and its info
  15. Im = niftiread(file);
  16. info = niftiinfo(file);
  17. % Drop the first 10 volumes
  18. Im = Im(:,:,:,11:end);
  19. info.ImageSize(4) = size(Im, 4); % Adjust header info to the new size
  20. % Reference image for registration (using the first volume)
  21. fixed = Im(:,:,:,1);
  22. % Perform motion correction for each volume
  23. for t = 2:size(Im, 4)
  24. % Register the current volume to the reference volume
  25. moving = Im(:,:,:,t);
  26. moving_reg = imregister(moving, fixed, transformType, optimizer, metric);
  27. % Replace the original volume with the registered volume
  28. Im(:,:,:,t) = moving_reg;
  29. end
  30. % Save the motion-corrected 4D rsfMRI image
  31. [filepath, filename, ext] = fileparts(file);
  32. output_filename = [filename '_mc' ext]; % Appending '_mc' to the filename
  33. output_path = fullfile(filepath, output_filename);
  34. niftiwrite(Im, output_path, info, 'Compressed', true);
  35. end