-
Notifications
You must be signed in to change notification settings - Fork 0
/
patchwise_inference.py
145 lines (120 loc) · 4.25 KB
/
patchwise_inference.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
import torch
import numpy as np
from DLBio.process_image_patchwise import whole_image_segmentation
# rm?
from DLBio.pytorch_helpers import cuda_to_numpy, image_batch_to_tensor
import torchvision.transforms as transforms
import torch.nn.functional as F
class CellSegmentationObject():
"""segmenting images
with already trained models (eg. for evaluation)
"""
def __init__(self,
device,
model,
in_shape,
num_classes,
normalization=None
):
"""constructor
Parameters
----------
device : torch device
model : pytorch model
the model to predict the images
in_shape : list
the height/width of the trained models input
num_classes: int
the number of classes to predict
normalization: function
normalization function that may be applied to the input
"""
self.device = device
self.model = model
self.in_shape = in_shape
self.num_classes = num_classes
self.norm = normalization
def do_task(self, image):
""" prepares the image for prediction
if image is larger than model input dlbio's process_image_patchwise is used
Parameters
----------
image : numpy ndarray
the image to predic
Returns
-------
numpy ndarray
the predicted output
with 1 Dimension for each class [image_y, image_x, class_n]
"""
if image.shape[0] > self.in_shape[0] or image.shape[1] > self.in_shape[1]:
# use process_image_patchwise if image is larger than model input
pred = whole_image_segmentation(self, image)
else:
# otherwise pad image to net size and predict
image = self.pad_image(image)
pred = self._predict(image)
return pred
def _predict(self, input, do_pre_proc=False, predict_patch=False):
"""the actual prediction
Parameters
----------
input : numpy ndarray
the input to predict
do_pre_proc : bool, optional
not used right now but necessary for process_image_patchwise
predict_patch : bool, optional
not used right now but necessary for process_image_patchwise
Returns
-------
numpy ndarray
the predicted model output
"""
to_tensor = transforms.ToTensor()
do_unsqueeze = False
if input.ndim == 3:
do_unsqueeze = True
input = to_tensor(input)
input = input.to(self.device).unsqueeze(0)
else:
input = image_batch_to_tensor(input).to(self.device)
if self.norm is not None:
input = [
self.norm(input[i, ...]) for i in range(input.shape[0])
]
input = torch.stack(input, 0)
# actual prediction
with torch.no_grad():
net_out = self.model(input)
out_seg = F.softmax(net_out, dim=1)
output = cuda_to_numpy(out_seg)
if do_unsqueeze:
output = output.squeeze(0)
return output
def pad_image(self, image):
target_x = self.in_shape[1]
target_y = self.in_shape[0]
if image.ndim == 2:
image = image[:, :, np.newaxis]
print('image dim changed')
h, w, _ = image.shape
x_pad = target_x - w
y_pad = target_y - h
padded_image = np.pad(
image, [(0, y_pad), (0, x_pad), (0, 0)], mode='constant')
return padded_image
# ------------------------------------------------
# methods necessary for whole_image_segmentation
# ------------------------------------------------
def get_input_shape(self):
# whole image segmentation expects list with 'x': list[2], 'y': list[1]
inpt = [-1]
inpt.extend(self.in_shape)
return inpt
def get_output_shape_for_patchwise_processing(self):
# whole image segmentation expects list with 'x': list[2], 'y': list[1]
inpt = [-1]
inpt.extend(self.in_shape)
return inpt
def get_num_classes(self):
return self.num_classes