-
Notifications
You must be signed in to change notification settings - Fork 2
/
createPriors.py
65 lines (49 loc) · 2.26 KB
/
createPriors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
### Average all of the tissue classication images in the group template space
### to create tissue class priors (divide by sum of the voxels if they are all
### non-zero, and do nothing otherwise)
###
### Ellyn Butler
### November 17, 2020 - February 4, 2021
import re
import glob
import numpy as np
import pandas as pd
import nibabel as nib
# Path to masks dir
maskDir= '/data/output/masks/'
tissues_dict = {
'Brainstem':[], 'CSF':[], 'Cerebellum':[],
'GMCortical':[], 'GMDeep':[], 'WMCortical':[]}
# Declare an empty array in shape of tissue mask images.
maskFile = glob.glob(maskDir + "*-clean_WarpedTo*Template.nii.gz")[0]
img = nib.load(maskFile)
img_array = img.get_fdata()
sum_all_tissues = np.zeros(img_array.shape)
# Get project name from maskFile name
pattern = "WarpedTo(.*?)Template"
projectName = re.search(pattern, maskFile).group(1)
# For each tissue type, sum mask arrays and story in dict.
for tissue in tissues_dict.keys():
# Get all cleaned, normalized masks of current tissue type
masks = glob.glob(maskDir + "*" + tissue + "-clean_WarpedTo*Template.nii.gz")
mask_arrays = []
for mask in masks:
img = nib.load(mask)
img_array = img.get_fdata()
mask_arrays.append(img_array)
# Sum values across all masks of given tissue type.
tissues_dict[tissue] = np.sum(mask_arrays, axis=0)
# Add sum for current tissue type to overall tissues sum
sum_all_tissues = sum_all_tissues + tissues_dict[tissue]
# For each tissue type, get weighted (scaled?) avg by
# dividing sum for given tissue type by sum of all tissues @ each voxel.
for tissue in tissues_dict.keys():
# Get weighted average mask for tissue type
tissues_dict[tissue] = np.true_divide(tissues_dict[tissue], sum_all_tissues)
# Convert all NaN to 0
tissues_dict[tissue][np.isnan(tissues_dict[tissue])] = 0
# Output average tissue mask to priors subdirectory.
avg_mask = nib.Nifti1Image(tissues_dict[tissue], affine=img.affine)
avg_mask.to_filename('/data/output/priors/' + projectName + 'Template_' + tissue + '-prior.nii.gz')
#This should just be 0s and 1s:
#np.unique(tissues_dict['Brainstem'] + tissues_dict['CSF'] + tissues_dict['Cerebellum'] + tissues_dict['GMCortical'] + tissues_dict['GMDeep'] + tissues_dict['WMCortical'])