-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunction.py
executable file
·191 lines (162 loc) · 6.42 KB
/
function.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import torch
import torch.nn as nn
import numpy as np
import scipy.ndimage as snd
from torch.autograd import Variable
from torchvision.transforms import ToPILImage, ToTensor
import torchvision.transforms.functional as PIL
from dataset import VolumeDataset, BlockDataset
from torch.utils.data import DataLoader
from model import UNet2d
import os, sys
import nibabel as nib
import pickle
import argparse
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write("error: %s\n" % message)
self.print_help()
self.exit(2)
def write_nifti(data, aff, shape, out_path):
data=data[0:shape[0],0:shape[1],0:shape[2]]
img=nib.Nifti1Image(data, aff)
img.to_filename(out_path)
def rotate_volume(vol):
tp_trans=ToPILImage()
tt_trans=ToTensor()
angle=np.array([1, 1, 1])
for i in range(3):
if i==0:
old_vol=vol
dim=old_vol.shape[i]
for j in range(dim):
if i==0:
one_slice=old_vol[j, :, :]
elif i==1:
one_slice=old_vol[:, j, :]
else: # i==2
one_slice=old_vol[:, :, j]
one_slice_pil=tp_trans(one_slice)
one_slice_pil=PIL.rotate(one_slice_pil, angle[i],
resample=PIL.Image.BILINEAR, expand=True)
one_slice=tt_trans(one_slice_pil)
if j==0: pass # Create New Vol
def estimate_dice(gt_msk, prt_msk):
intersection=gt_msk*prt_msk
dice=2*float(intersection.sum())/float(gt_msk.sum()+prt_msk.sum())
return dice
def extract_large_comp(prt_msk):
labs, num_lab=snd.label(prt_msk)
c_size=np.bincount(labs.reshape(-1))
c_size[0]=0
max_ind=c_size.argmax()
prt_msk=labs==max_ind
return prt_msk
def predict_volumes(model, rimg_in=None, cimg_in=None, bmsk_in=None, suffix="pre_mask",
save_dice=False, save_nii=False, nii_outdir=None, verbose=False,
rescale_dim=256, num_slice=3):
use_gpu=torch.cuda.is_available()
model_on_gpu=next(model.parameters()).is_cuda
use_bn=True
if use_gpu:
if not model_on_gpu:
model.cuda()
else:
if model_on_gpu:
model.cpu()
NoneType=type(None)
if isinstance(rimg_in, NoneType) and isinstance(cimg_in, NoneType):
print("Input rimg_in or cimg_in")
sys.exit(1)
if save_dice:
dice_dict=dict()
volume_dataset=VolumeDataset(rimg_in=rimg_in, cimg_in=cimg_in, bmsk_in=bmsk_in)
volume_loader=DataLoader(dataset=volume_dataset, batch_size=1)
for idx, vol in enumerate(volume_loader):
if len(vol)==1: # just img
ptype=1 # Predict
cimg=vol
bmsk=None
block_dataset=BlockDataset(rimg=cimg, bfld=None, bmsk=None, num_slice=num_slice, rescale_dim=rescale_dim)
elif len(vol)==2: # img & msk
ptype=2 # image test
cimg=vol[0]
bmsk=vol[1]
block_dataset=BlockDataset(rimg=cimg, bfld=None, bmsk=bmsk, num_slice=num_slice, rescale_dim=rescale_dim)
elif len(vol==3): # img bias_field & msk
ptype=3 # image bias correction test
cimg=vol[0]
bfld=vol[1]
bmsk=vol[2]
block_dataset=BlockDataset(rimg=cimg, bfld=bfld, bmsk=bmsk, num_slice=num_slice, rescale_dim=rescale_dim)
else:
print("Invalid Volume Dataset!")
sys.exit(2)
rescale_shape=block_dataset.get_rescale_shape()
raw_shape=block_dataset.get_raw_shape()
for od in range(3):
backard_ind=np.arange(3)
backard_ind=np.insert(np.delete(backard_ind, 0), od, 0)
block_data, slice_list, slice_weight=block_dataset.get_one_directory(axis=od)
pr_bmsk=torch.zeros([len(slice_weight), rescale_dim, rescale_dim])
if use_gpu:
pr_bmsk=pr_bmsk.cuda()
for (i, ind) in enumerate(slice_list):
if ptype==1:
rimg_blk=block_data[i]
if use_gpu:
rimg_blk=rimg_blk.cuda()
elif ptype==2:
rimg_blk, bmsk_blk=block_data[i]
if use_gpu:
rimg_blk=rimg_blk.cuda()
bmsk_blk=bmsk_blk.cuda()
else:
rimg_blk, bfld_blk, bmsk_blk=block_data[i]
if use_gpu:
rimg_blk=rimg_blk.cuda()
bfld_blk=bfld_blk.cuda()
bmsk_blk=bmsk_blk.cuda()
pr_bmsk_blk=model(torch.unsqueeze(Variable(rimg_blk), 0))
pr_bmsk[ind[1], :, :]=pr_bmsk_blk.data[0][1, :, :]
if use_gpu:
pr_bmsk=pr_bmsk.cpu()
pr_bmsk=pr_bmsk.permute(backard_ind[0], backard_ind[1], backard_ind[2])
pr_bmsk=pr_bmsk[:rescale_shape[0], :rescale_shape[1], :rescale_shape[2]]
uns_pr_bmsk=torch.unsqueeze(pr_bmsk, 0)
uns_pr_bmsk=torch.unsqueeze(uns_pr_bmsk, 0)
uns_pr_bmsk=nn.functional.interpolate(uns_pr_bmsk, size=raw_shape, mode="trilinear", align_corners=False)
pr_bmsk=torch.squeeze(uns_pr_bmsk)
if od==0:
pr_3_bmsk=torch.unsqueeze(pr_bmsk, 3)
else:
pr_3_bmsk=torch.cat((pr_3_bmsk, torch.unsqueeze(pr_bmsk, 3)), dim=3)
pr_bmsk=pr_3_bmsk.mean(dim=3)
pr_bmsk=pr_bmsk.numpy()
pr_bmsk_final=extract_large_comp(pr_bmsk>0.5)
if isinstance(bmsk, torch.Tensor):
bmsk=bmsk.data[0].numpy()
dice=estimate_dice(bmsk, pr_bmsk_final)
if verbose:
print(dice)
t1w_nii=volume_dataset.getCurCimgNii()
t1w_path=t1w_nii.get_filename()
t1w_dir, t1w_file=os.path.split(t1w_path)
t1w_name=os.path.splitext(t1w_file)[0]
t1w_name=os.path.splitext(t1w_name)[0]
if save_nii:
t1w_aff=t1w_nii.affine
t1w_shape=t1w_nii.shape
if isinstance(nii_outdir, NoneType):
nii_outdir=t1w_dir
if not os.path.exists(nii_outdir):
os.mkdir(nii_outdir)
out_path=os.path.join(nii_outdir, t1w_name+"_"+suffix+".nii.gz")
write_nifti(np.array(pr_bmsk_final, dtype=np.float32), t1w_aff, t1w_shape, out_path)
if save_dice:
dice_dict[t1w_name]=dice
if save_dice:
return dice_dict
# Unit test
if __name__=='__main__':
pass