preprocess.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import glob
  2. import nibabel as nib
  3. import numpy as np
  4. import random
  5. import torch
  6. from torch.utils.data import Dataset
  7. import torchvision.transforms as transforms
  8. import re
  9. '''
  10. Prepares CustomDatasets for training, validating, and testing CNN
  11. '''
  12. def prepare_datasets(mri_dir, val_split=0.2, seed=50):
  13. rndm = random.Random(seed)
  14. raw_data = glob.glob(mri_dir + "*")
  15. AD_list = []
  16. NL_list = []
  17. print("--- DATA INFO ---")
  18. print("Amount of images: " + str(len(raw_data)))
  19. # TODO Check that image is in CSV?
  20. for image in raw_data:
  21. if "NL" in image:
  22. NL_list.append(image)
  23. elif "AD" in image:
  24. AD_list.append(image)
  25. print("Total AD: " + str(len(AD_list)))
  26. print("Total NL: " + str(len(NL_list)))
  27. rndm.shuffle(AD_list)
  28. rndm.shuffle(NL_list)
  29. train_list, val_list, test_list = get_train_val_test(AD_list, NL_list, val_split)
  30. rndm.shuffle(train_list)
  31. rndm.shuffle(val_list)
  32. rndm.shuffle(test_list)
  33. print(f"DATA INITIALIZATION")
  34. print(f"Training size: {len(train_list)}")
  35. print(f"Validation size: {len(val_list)}")
  36. print(f"Test size: {len(test_list)}")
  37. # # TRANSFORM
  38. # transform = transforms.Compose([
  39. # transforms.Grayscale(num_output_channels=1)
  40. # ])
  41. train_dataset = CustomDataset(train_list)
  42. val_dataset = CustomDataset(val_list)
  43. test_dataset = CustomDataset(test_list)
  44. return train_dataset, val_dataset, test_dataset
  45. # TODO Normalize data? Later add / Extract clinical data? Which data?
  46. def prepare_predict(mri_dir, IDs):
  47. raw_data = glob.glob(mri_dir + "*")
  48. image_list = []
  49. # Gets all images and prepares them for Dataset
  50. for ID in IDs:
  51. pattern = re.compile(ID)
  52. matches = [item for item in raw_data if pattern.search(item)]
  53. if (len(matches) != 1): print("No image found, or more than one")
  54. for match in matches:
  55. if "NL" in match: image_list.append((match, 0))
  56. if "AD" in match: image_list.append((match, 1))
  57. return CustomDataset(image_list)
  58. '''
  59. Returns train_list, val_list and test_list in format [(image, id), ...] each
  60. '''
  61. def get_train_val_test(AD_list, NL_list, val_split):
  62. train_list, val_list, test_list = [], [], []
  63. num_test_ad = int(len(AD_list) * val_split)
  64. num_test_nl = int(len(NL_list) * val_split)
  65. num_val_ad = int((len(AD_list) - num_test_ad) * val_split)
  66. num_val_nl = int((len(NL_list) - num_test_nl) * val_split)
  67. # Sets up ADs
  68. for image in AD_list[0:num_val_ad]:
  69. val_list.append((image, 1))
  70. for image in AD_list[num_val_ad:num_test_ad]:
  71. test_list.append((image, 1))
  72. for image in AD_list[num_test_ad:]:
  73. train_list.append((image, 1))
  74. # Sets up NLs
  75. for image in NL_list[0:num_val_nl]:
  76. val_list.append((image, 0))
  77. for image in NL_list[num_val_nl:num_test_nl]:
  78. test_list.append((image, 0))
  79. for image in NL_list[num_test_nl:]:
  80. train_list.append((image, 0))
  81. return train_list, val_list, test_list
  82. class CustomDataset(Dataset):
  83. def __init__(self, list):
  84. self.data = list # DATA IS A LIST WITH TUPLES (image_dir, class_id)
  85. def __len__(self):
  86. return len(self.data)
  87. def __getitem__(self, idx): # RETURNS TUPLE WITH IMAGE AND CLASS_ID, BASED ON INDEX IDX
  88. mri_path, class_id = self.data[idx]
  89. mri = nib.load(mri_path)
  90. image = np.asarray(mri.dataobj)
  91. mri_data = np.asarray(np.expand_dims(image, axis=0))
  92. # mri_data = mri.get_fdata()
  93. # mri_array = np.array(mri)
  94. # mri_tensor = torch.from_numpy(mri_array)
  95. # class_id = torch.tensor([class_id]) TODO return tensor or just id (0, 1)??
  96. return mri_data, class_id