adding_noising_example.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. import glob
  3. import nibabel as nib
  4. from skimage.restoration import denoise_tv_chambolle
  5. from skimage.util import random_noise
  6. from tqdm import tqdm
  7. from concurrent.futures import ProcessPoolExecutor
  8. init_path = r"C:\Users\aswen\Desktop\TestingData\Aswendt_qc_data\proc_data"
  9. # Define the search paths for noisy files and all files
  10. searchpath_delete = os.path.join(init_path, "**", "anat", "*ois*.nii.gz")
  11. searchpath = os.path.join(init_path, "**", "anat", "*.nii.gz")
  12. # Delete all noisy files matching the pattern before proceeding
  13. noisy_files = glob.glob(searchpath_delete, recursive=True)
  14. for file in noisy_files:
  15. os.remove(file)
  16. # Get the list of all files
  17. T2files = glob.glob(searchpath, recursive=True)
  18. def process_file(file):
  19. Im = nib.load(file)
  20. data = Im.get_fdata() # Getting image data from the nibabel object
  21. # Perform denoising using total variation denoising from scikit-image
  22. Im_denoised = denoise_tv_chambolle(data, weight=0.1, multichannel=False)
  23. # Add random noise to the original image
  24. Im_random_noisy = random_noise(data, mode='gaussian', mean=0, var=0.01) # Adjust the variance for noise
  25. # Add salt and pepper noise to the original image
  26. Im_salt_pepper_noisy = random_noise(data, mode='s&p', amount=0.05) # Adjust the amount for noise density
  27. # Add speckle noise to the original image
  28. Im_speckle_noisy = random_noise(data, mode='speckle', mean=0, var=0.01) # Adjust the variance for noise
  29. # Creating new file names for denoised and noisy images
  30. denoised_filename = os.path.splitext(file)[0] + "_denoised.nii"
  31. random_noisy_filename = os.path.splitext(file)[0] + "_randomNoisy.nii.gz"
  32. salt_pepper_noisy_filename = os.path.splitext(file)[0] + "_saltPepperNoisy.nii.gz"
  33. speckle_noisy_filename = os.path.splitext(file)[0] + "_speckleNoisy.nii.gz"
  34. # Save the denoised image
  35. nib.save(nib.Nifti1Image(Im_denoised, Im.affine), denoised_filename)
  36. # Save the randomly noisy image
  37. nib.save(nib.Nifti1Image(Im_random_noisy, Im.affine), random_noisy_filename)
  38. # Save the salt and pepper noisy image
  39. nib.save(nib.Nifti1Image(Im_salt_pepper_noisy, Im.affine), salt_pepper_noisy_filename)
  40. # Save the speckle noisy image
  41. nib.save(nib.Nifti1Image(Im_speckle_noisy, Im.affine), speckle_noisy_filename)
  42. if __name__ == '__main__':
  43. # Use ProcessPoolExecutor for parallel processing with 10 cores
  44. with ProcessPoolExecutor(max_workers=10) as executor:
  45. list(tqdm(executor.map(process_file, T2files), total=len(T2files), desc="Processing", unit="file"))