tools.py 1.6 KB

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