tools.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. import shutil
  3. import nibabel as nib
  4. from PIL import Image
  5. import numpy as np
  6. from sklearn.metrics import mutual_info_score
  7. from preprocess import mask_foreground
  8. from pprint import pprint
  9. def save_slice(template, filename, index, affine=np.eye(4), header=None):
  10. _slice = nib.load(str(template))
  11. _slice_data = _slice.get_data()
  12. newimg = nib.Nifti1Image(_slice_data[:, index, :], affine, header)
  13. newimg.header['pixdim'] = header['pixdim']
  14. if header is None:
  15. newimg.header['pixdim'][1:3] = _slice.header['pixdim'][1], _slice.header['pixdim'][3]
  16. newimg.to_filename(str(filename))
  17. return filename
  18. def create_dir(name):
  19. if not os.path.exists(name):
  20. os.mkdir(name)
  21. def mutual_info_mask(slice1,slice2, bins=32):
  22. slice1_masked = mask_foreground(slice1)
  23. slice2_masked = mask_foreground(slice2)
  24. common = np.logical_and(slice1_masked, slice2_masked)
  25. slice1, slice2 = np.where(common, slice1, 0), np.where(common, slice2, 0)
  26. hist = np.histogram2d(slice1.ravel(), slice2.ravel(), bins=bins)[0]
  27. return mutual_info_score(None, None, contingency=hist)
  28. def dice_coef(slice1, slice2):
  29. mask_1 = mask_foreground(slice1).astype(np.bool)
  30. mask_2 = mask_foreground(slice2).astype(np.bool)
  31. intersection = np.logical_and(mask_1, mask_2)
  32. return 2. * intersection.sum() / (mask_1.sum() + mask_2.sum())
  33. def resize_im(image_data, image_with_dimensions):
  34. dimensions = (image_with_dimensions.shape[1], image_with_dimensions.shape[0])
  35. resized = np.array(Image.fromarray(image_data).resize(dimensions))
  36. return resized
  37. def bregma_to_slice_index(bregma):
  38. return round(27.908*bregma + 116.831)