saim1309 commited on
Commit
29ac506
·
verified ·
1 Parent(s): d92f87f

Upload 9 files

Browse files
Files changed (10) hide show
  1. .gitattributes +3 -0
  2. BasePredictor.py +120 -0
  3. MEDIARFormer.py +102 -0
  4. Predictor.py +234 -0
  5. img1.png +3 -0
  6. img2.png +3 -0
  7. img3.png +3 -0
  8. requirements.txt +32 -0
  9. trained_model_200.pt +3 -0
  10. utils.py +429 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ img1.png filter=lfs diff=lfs merge=lfs -text
37
+ img2.png filter=lfs diff=lfs merge=lfs -text
38
+ img3.png filter=lfs diff=lfs merge=lfs -text
BasePredictor.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import time, os
4
+ import tifffile as tif
5
+
6
+ from datetime import datetime
7
+ from zipfile import ZipFile
8
+ from pytz import timezone
9
+
10
+ from train_tools.data_utils.transforms import get_pred_transforms
11
+
12
+
13
+ class BasePredictor:
14
+ def __init__(
15
+ self,
16
+ model,
17
+ device,
18
+ input_path,
19
+ output_path,
20
+ make_submission=False,
21
+ exp_name=None,
22
+ algo_params=None,
23
+ ):
24
+ self.model = model
25
+ self.device = device
26
+ self.input_path = input_path
27
+ self.output_path = output_path
28
+ self.make_submission = make_submission
29
+ self.exp_name = exp_name
30
+
31
+ # Assign algoritm-specific arguments
32
+ if algo_params:
33
+ self.__dict__.update((k, v) for k, v in algo_params.items())
34
+
35
+ # Prepare inference environments
36
+ self._setups()
37
+
38
+ @torch.no_grad()
39
+ def conduct_prediction(self):
40
+ self.model.to(self.device)
41
+ self.model.eval()
42
+ total_time = 0
43
+ total_times = []
44
+
45
+ for img_name in self.img_names:
46
+ img_data = self._get_img_data(img_name)
47
+ img_data = img_data.to(self.device)
48
+
49
+ start = time.time()
50
+
51
+ pred_mask = self._inference(img_data)
52
+ pred_mask = self._post_process(pred_mask.squeeze(0).cpu().numpy())
53
+ self.write_pred_mask(
54
+ pred_mask, self.output_path, img_name, self.make_submission
55
+ )
56
+
57
+ end = time.time()
58
+
59
+ time_cost = end - start
60
+ total_times.append(time_cost)
61
+ total_time += time_cost
62
+ print(
63
+ f"Prediction finished: {img_name}; img size = {img_data.shape}; costing: {time_cost:.2f}s"
64
+ )
65
+
66
+ print(f"\n Total Time Cost: {total_time:.2f}s")
67
+
68
+ if self.make_submission:
69
+ fname = "%s.zip" % self.exp_name
70
+
71
+ os.makedirs("./submissions", exist_ok=True)
72
+ submission_path = os.path.join("./submissions", fname)
73
+
74
+ with ZipFile(submission_path, "w") as zipObj2:
75
+ pred_names = sorted(os.listdir(self.output_path))
76
+ for pred_name in pred_names:
77
+ pred_path = os.path.join(self.output_path, pred_name)
78
+ zipObj2.write(pred_path)
79
+
80
+ print("\n>>>>> Submission file is saved at: %s\n" % submission_path)
81
+
82
+ return time_cost
83
+
84
+ def write_pred_mask(self, pred_mask, output_dir, image_name, submission=False):
85
+
86
+ # All images should contain at least 5 cells
87
+ if submission:
88
+ if not (np.max(pred_mask) > 5):
89
+ print("[!Caution] Only %d Cells Detected!!!\n" % np.max(pred_mask))
90
+
91
+ file_name = image_name.split(".")[0]
92
+ file_name = file_name + "_label.tiff"
93
+ file_path = os.path.join(output_dir, file_name)
94
+
95
+ tif.imwrite(file_path, pred_mask, compression="zlib")
96
+
97
+ def _setups(self):
98
+ self.pred_transforms = get_pred_transforms()
99
+ os.makedirs(self.output_path, exist_ok=True)
100
+
101
+ now = datetime.now(timezone("Asia/Seoul"))
102
+ dt_string = now.strftime("%m%d_%H%M")
103
+ self.exp_name = (
104
+ self.exp_name + dt_string if self.exp_name is not None else dt_string
105
+ )
106
+
107
+ self.img_names = sorted(os.listdir(self.input_path))
108
+
109
+ def _get_img_data(self, img_name):
110
+ img_path = os.path.join(self.input_path, img_name)
111
+ img_data = self.pred_transforms(img_path)
112
+ img_data = img_data.unsqueeze(0)
113
+
114
+ return img_data
115
+
116
+ def _inference(self, img_data):
117
+ raise NotImplementedError
118
+
119
+ def _post_process(self, pred_mask):
120
+ raise NotImplementedError
MEDIARFormer.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from segmentation_models_pytorch import MAnet
5
+ from segmentation_models_pytorch.base.modules import Activation
6
+
7
+ __all__ = ["MEDIARFormer"]
8
+
9
+
10
+ class MEDIARFormer(MAnet):
11
+ """MEDIAR-Former Model"""
12
+
13
+ def __init__(
14
+ self,
15
+ encoder_name="mit_b5", # Default encoder
16
+ encoder_weights="imagenet", # Pre-trained weights
17
+ decoder_channels=(1024, 512, 256, 128, 64), # Decoder configuration
18
+ decoder_pab_channels=256, # Decoder Pyramid Attention Block channels
19
+ in_channels=3, # Number of input channels
20
+ classes=3, # Number of output classes
21
+ ):
22
+ # Initialize the MAnet model with provided parameters
23
+ super().__init__(
24
+ encoder_name=encoder_name,
25
+ encoder_weights=encoder_weights,
26
+ decoder_channels=decoder_channels,
27
+ decoder_pab_channels=decoder_pab_channels,
28
+ in_channels=in_channels,
29
+ classes=classes,
30
+ )
31
+
32
+ # Remove the default segmentation head as it's not used in this architecture
33
+ self.segmentation_head = None
34
+
35
+ # Modify all activation functions in the encoder and decoder from ReLU to Mish
36
+ _convert_activations(self.encoder, nn.ReLU, nn.Mish(inplace=True))
37
+ _convert_activations(self.decoder, nn.ReLU, nn.Mish(inplace=True))
38
+
39
+ # Add custom segmentation heads for different segmentation tasks
40
+ self.cellprob_head = DeepSegmentationHead(
41
+ in_channels=decoder_channels[-1], out_channels=1
42
+ )
43
+ self.gradflow_head = DeepSegmentationHead(
44
+ in_channels=decoder_channels[-1], out_channels=2
45
+ )
46
+
47
+ def forward(self, x):
48
+ """Forward pass through the network"""
49
+ # Ensure the input shape is correct
50
+ self.check_input_shape(x)
51
+
52
+ # Encode the input and then decode it
53
+ features = self.encoder(x)
54
+ decoder_output = self.decoder(*features)
55
+
56
+ # Generate masks for cell probability and gradient flows
57
+ cellprob_mask = self.cellprob_head(decoder_output)
58
+ gradflow_mask = self.gradflow_head(decoder_output)
59
+
60
+ # Concatenate the masks for output
61
+ masks = torch.cat([gradflow_mask, cellprob_mask], dim=1)
62
+
63
+ return masks
64
+
65
+
66
+ class DeepSegmentationHead(nn.Sequential):
67
+ """Custom segmentation head for generating specific masks"""
68
+
69
+ def __init__(
70
+ self, in_channels, out_channels, kernel_size=3, activation=None, upsampling=1
71
+ ):
72
+ # Define a sequence of layers for the segmentation head
73
+ layers = [
74
+ nn.Conv2d(
75
+ in_channels,
76
+ in_channels // 2,
77
+ kernel_size=kernel_size,
78
+ padding=kernel_size // 2,
79
+ ),
80
+ nn.Mish(inplace=True),
81
+ nn.BatchNorm2d(in_channels // 2),
82
+ nn.Conv2d(
83
+ in_channels // 2,
84
+ out_channels,
85
+ kernel_size=kernel_size,
86
+ padding=kernel_size // 2,
87
+ ),
88
+ nn.UpsamplingBilinear2d(scale_factor=upsampling)
89
+ if upsampling > 1
90
+ else nn.Identity(),
91
+ Activation(activation) if activation else nn.Identity(),
92
+ ]
93
+ super().__init__(*layers)
94
+
95
+
96
+ def _convert_activations(module, from_activation, to_activation):
97
+ """Recursively convert activation functions in a module"""
98
+ for name, child in module.named_children():
99
+ if isinstance(child, from_activation):
100
+ setattr(module, name, to_activation)
101
+ else:
102
+ _convert_activations(child, from_activation, to_activation)
Predictor.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import os, sys
4
+ from monai.inferers import sliding_window_inference
5
+
6
+ sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../")))
7
+
8
+ from BasePredictor import BasePredictor
9
+ from utils import compute_masks
10
+
11
+ __all__ = ["Predictor"]
12
+
13
+
14
+ class Predictor(BasePredictor):
15
+ def __init__(
16
+ self,
17
+ model,
18
+ device,
19
+ input_path,
20
+ output_path,
21
+ make_submission=False,
22
+ exp_name=None,
23
+ algo_params=None,
24
+ ):
25
+ super(Predictor, self).__init__(
26
+ model,
27
+ device,
28
+ input_path,
29
+ output_path,
30
+ make_submission,
31
+ exp_name,
32
+ algo_params,
33
+ )
34
+ self.hflip_tta = HorizontalFlip()
35
+ self.vflip_tta = VerticalFlip()
36
+
37
+ @torch.no_grad()
38
+ def _inference(self, img_data):
39
+ """Conduct model prediction"""
40
+
41
+ img_data = img_data.to(self.device)
42
+ img_base = img_data
43
+ outputs_base = self._window_inference(img_base)
44
+ outputs_base = outputs_base.cpu().squeeze()
45
+ img_base.cpu()
46
+
47
+ if not self.use_tta:
48
+ pred_mask = outputs_base
49
+ return pred_mask
50
+
51
+ else:
52
+ # HorizontalFlip TTA
53
+ img_hflip = self.hflip_tta.apply_aug_image(img_data, apply=True)
54
+ outputs_hflip = self._window_inference(img_hflip)
55
+ outputs_hflip = self.hflip_tta.apply_deaug_mask(outputs_hflip, apply=True)
56
+ outputs_hflip = outputs_hflip.cpu().squeeze()
57
+ img_hflip = img_hflip.cpu()
58
+
59
+ # VertricalFlip TTA
60
+ img_vflip = self.vflip_tta.apply_aug_image(img_data, apply=True)
61
+ outputs_vflip = self._window_inference(img_vflip)
62
+ outputs_vflip = self.vflip_tta.apply_deaug_mask(outputs_vflip, apply=True)
63
+ outputs_vflip = outputs_vflip.cpu().squeeze()
64
+ img_vflip = img_vflip.cpu()
65
+
66
+ # Merge Results
67
+ pred_mask = torch.zeros_like(outputs_base)
68
+ pred_mask[0] = (outputs_base[0] + outputs_hflip[0] - outputs_vflip[0]) / 3
69
+ pred_mask[1] = (outputs_base[1] - outputs_hflip[1] + outputs_vflip[1]) / 3
70
+ pred_mask[2] = (outputs_base[2] + outputs_hflip[2] + outputs_vflip[2]) / 3
71
+
72
+ return pred_mask
73
+
74
+ def _window_inference(self, img_data, aux=False):
75
+ """Inference on RoI-sized window"""
76
+ outputs = sliding_window_inference(
77
+ img_data,
78
+ roi_size=512,
79
+ sw_batch_size=4,
80
+ predictor=self.model if not aux else self.model_aux,
81
+ padding_mode="constant",
82
+ mode="gaussian",
83
+ overlap=0.6,
84
+ )
85
+
86
+ return outputs
87
+
88
+ def _post_process(self, pred_mask):
89
+ """Generate cell instance masks."""
90
+ dP, cellprob = pred_mask[:2], self._sigmoid(pred_mask[-1])
91
+ H, W = pred_mask.shape[-2], pred_mask.shape[-1]
92
+
93
+ if np.prod(H * W) < (5000 * 5000):
94
+ pred_mask = compute_masks(
95
+ dP,
96
+ cellprob,
97
+ use_gpu=True,
98
+ flow_threshold=0.4,
99
+ device=self.device,
100
+ cellprob_threshold=0.5,
101
+ )[0]
102
+
103
+ else:
104
+ print("\n[Whole Slide] Grid Prediction starting...")
105
+ roi_size = 2000
106
+
107
+ # Get patch grid by roi_size
108
+ if H % roi_size != 0:
109
+ n_H = H // roi_size + 1
110
+ new_H = roi_size * n_H
111
+ else:
112
+ n_H = H // roi_size
113
+ new_H = H
114
+
115
+ if W % roi_size != 0:
116
+ n_W = W // roi_size + 1
117
+ new_W = roi_size * n_W
118
+ else:
119
+ n_W = W // roi_size
120
+ new_W = W
121
+
122
+ # Allocate values on the grid
123
+ pred_pad = np.zeros((new_H, new_W), dtype=np.uint32)
124
+ dP_pad = np.zeros((2, new_H, new_W), dtype=np.float32)
125
+ cellprob_pad = np.zeros((new_H, new_W), dtype=np.float32)
126
+
127
+ dP_pad[:, :H, :W], cellprob_pad[:H, :W] = dP, cellprob
128
+
129
+ for i in range(n_H):
130
+ for j in range(n_W):
131
+ print("Pred on Grid (%d, %d) processing..." % (i, j))
132
+ dP_roi = dP_pad[
133
+ :,
134
+ roi_size * i : roi_size * (i + 1),
135
+ roi_size * j : roi_size * (j + 1),
136
+ ]
137
+ cellprob_roi = cellprob_pad[
138
+ roi_size * i : roi_size * (i + 1),
139
+ roi_size * j : roi_size * (j + 1),
140
+ ]
141
+
142
+ pred_mask = compute_masks(
143
+ dP_roi,
144
+ cellprob_roi,
145
+ use_gpu=True,
146
+ flow_threshold=0.4,
147
+ device=self.device,
148
+ cellprob_threshold=0.5,
149
+ )[0]
150
+
151
+ pred_pad[
152
+ roi_size * i : roi_size * (i + 1),
153
+ roi_size * j : roi_size * (j + 1),
154
+ ] = pred_mask
155
+
156
+ pred_mask = pred_pad[:H, :W]
157
+
158
+ return pred_mask
159
+
160
+ def _sigmoid(self, z):
161
+ return 1 / (1 + np.exp(-z))
162
+
163
+
164
+ """
165
+ Adapted from the following references:
166
+ [1] https://github.com/qubvel/ttach/blob/master/ttach/transforms.py
167
+
168
+ """
169
+
170
+
171
+ def hflip(x):
172
+ """flip batch of images horizontally"""
173
+ return x.flip(3)
174
+
175
+
176
+ def vflip(x):
177
+ """flip batch of images vertically"""
178
+ return x.flip(2)
179
+
180
+
181
+ class DualTransform:
182
+ identity_param = None
183
+
184
+ def __init__(
185
+ self, name: str, params,
186
+ ):
187
+ self.params = params
188
+ self.pname = name
189
+
190
+ def apply_aug_image(self, image, *args, **params):
191
+ raise NotImplementedError
192
+
193
+ def apply_deaug_mask(self, mask, *args, **params):
194
+ raise NotImplementedError
195
+
196
+
197
+ class HorizontalFlip(DualTransform):
198
+ """Flip images horizontally (left -> right)"""
199
+
200
+ identity_param = False
201
+
202
+ def __init__(self):
203
+ super().__init__("apply", [False, True])
204
+
205
+ def apply_aug_image(self, image, apply=False, **kwargs):
206
+ if apply:
207
+ image = hflip(image)
208
+ return image
209
+
210
+ def apply_deaug_mask(self, mask, apply=False, **kwargs):
211
+ if apply:
212
+ mask = hflip(mask)
213
+ return mask
214
+
215
+
216
+ class VerticalFlip(DualTransform):
217
+ """Flip images vertically (up -> down)"""
218
+
219
+ identity_param = False
220
+
221
+ def __init__(self):
222
+ super().__init__("apply", [False, True])
223
+
224
+ def apply_aug_image(self, image, apply=False, **kwargs):
225
+ if apply:
226
+ image = vflip(image)
227
+
228
+ return image
229
+
230
+ def apply_deaug_mask(self, mask, apply=False, **kwargs):
231
+ if apply:
232
+ mask = vflip(mask)
233
+
234
+ return mask
img1.png ADDED

Git LFS Details

  • SHA256: f23773b1dee29b732f96acc1f66556903707003c7b22380d446b5cde37b076f1
  • Pointer size: 132 Bytes
  • Size of remote file: 1.03 MB
img2.png ADDED

Git LFS Details

  • SHA256: 64184bd3e3c6dc73635d39ddde2683077ef86620fd6df3057fb8cd75f22c0ee1
  • Pointer size: 132 Bytes
  • Size of remote file: 1.82 MB
img3.png ADDED

Git LFS Details

  • SHA256: 34a7a7ccbf914fb4f784c43b2c13bbfaad6493dfd26766c05ed949489c57b60a
  • Pointer size: 131 Bytes
  • Size of remote file: 536 kB
requirements.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ datasets
3
+ torch
4
+ torchvision
5
+ accelerate
6
+ opencv-python
7
+ pillow
8
+ fastremap==1.14.1
9
+ monai==1.3.0
10
+ numba==0.57.1
11
+ numpy==1.24.3
12
+ pandas==2.0.3
13
+ pytz==2023.3.post1
14
+ scipy==1.12.0
15
+ segmentation_models_pytorch==0.3.3
16
+ tifffile==2023.4.12
17
+ torch==2.1.2
18
+ tqdm==4.65.0
19
+ wandb==0.16.2
20
+ scikit-image
21
+ matplotlib
22
+ segmentation-models-pytorch==0.3.1
23
+ TensorFlow
24
+ stardist
25
+ csbdeep
26
+ matplotlib
27
+ scikit-image
28
+ numpy
29
+ scipy
30
+ cellpose
31
+ natsort
32
+
trained_model_200.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a15e5c6dfecd0b01c900ed7951aefb66d0c646eccb4bc12bc2fecb78715fcf6
3
+ size 14952483
utils.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright © 2022 Howard Hughes Medical Institute,
3
+ Authored by Carsen Stringer and Marius Pachitariu.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of HHMI nor the names of its contributors may be used to
16
+ endorse or promote products derived from this software without specific
17
+ prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ --------------------------------------------------------------------------
32
+ MEDIAR Prediction uses CellPose's Gradient Flow Tracking.
33
+
34
+ This code is adapted from the following codes:
35
+ [1] https://github.com/MouseLand/cellpose/blob/main/cellpose/utils.py
36
+ [2] https://github.com/MouseLand/cellpose/blob/main/cellpose/dynamics.py
37
+ [3] https://github.com/MouseLand/cellpose/blob/main/cellpose/metrics.py
38
+ """
39
+
40
+ import torch
41
+ from torch.nn.functional import grid_sample
42
+ import numpy as np
43
+ import fastremap
44
+
45
+ from skimage import morphology
46
+ from scipy.ndimage import mean, find_objects
47
+ from scipy.ndimage.filters import maximum_filter1d
48
+
49
+ torch_GPU = torch.device("cuda")
50
+ torch_CPU = torch.device("cpu")
51
+
52
+
53
+ def labels_to_flows(labels, use_gpu=False, device=None, redo_flows=False):
54
+ """
55
+ Convert labels (list of masks or flows) to flows for training model
56
+ """
57
+
58
+ # Labels b x 1 x h x w
59
+ labels = labels.cpu().numpy().astype(np.int16)
60
+ nimg = len(labels)
61
+
62
+ if labels[0].ndim < 3:
63
+ labels = [labels[n][np.newaxis, :, :] for n in range(nimg)]
64
+
65
+ # Flows need to be recomputed
66
+ if labels[0].shape[0] == 1 or labels[0].ndim < 3 or redo_flows:
67
+ # compute flows; labels are fixed here to be unique, so they need to be passed back
68
+ # make sure labels are unique!
69
+ labels = [fastremap.renumber(label, in_place=True)[0] for label in labels]
70
+ veci = [
71
+ masks_to_flows(labels[n][0], use_gpu=use_gpu, device=device)
72
+ for n in range(nimg)
73
+ ]
74
+
75
+ # concatenate labels, distance transform, vector flows, heat (boundary and mask are computed in augmentations)
76
+ flows = [
77
+ np.concatenate((labels[n], labels[n] > 0.5, veci[n]), axis=0).astype(
78
+ np.float32
79
+ )
80
+ for n in range(nimg)
81
+ ]
82
+
83
+ return np.array(flows)
84
+
85
+
86
+ def compute_masks(
87
+ dP,
88
+ cellprob,
89
+ p=None,
90
+ niter=200,
91
+ cellprob_threshold=0.4,
92
+ flow_threshold=0.4,
93
+ interp=True,
94
+ resize=None,
95
+ use_gpu=False,
96
+ device=None,
97
+ ):
98
+ """compute masks using dynamics from dP, cellprob, and boundary"""
99
+
100
+ cp_mask = cellprob > cellprob_threshold
101
+ cp_mask = morphology.remove_small_holes(cp_mask, area_threshold=16)
102
+ cp_mask = morphology.remove_small_objects(cp_mask, min_size=16)
103
+
104
+ if np.any(cp_mask): # mask at this point is a cell cluster binary map, not labels
105
+ # follow flows
106
+ if p is None:
107
+ p, inds = follow_flows(
108
+ dP * cp_mask / 5.0,
109
+ niter=niter,
110
+ interp=interp,
111
+ use_gpu=use_gpu,
112
+ device=device,
113
+ )
114
+ if inds is None:
115
+ shape = resize if resize is not None else cellprob.shape
116
+ mask = np.zeros(shape, np.uint16)
117
+ p = np.zeros((len(shape), *shape), np.uint16)
118
+ return mask, p
119
+
120
+ # calculate masks
121
+ mask = get_masks(p, iscell=cp_mask)
122
+
123
+ # flow thresholding factored out of get_masks
124
+ shape0 = p.shape[1:]
125
+ if mask.max() > 0 and flow_threshold is not None and flow_threshold > 0:
126
+ # make sure labels are unique at output of get_masks
127
+ mask = remove_bad_flow_masks(
128
+ mask, dP, threshold=flow_threshold, use_gpu=use_gpu, device=device
129
+ )
130
+ else: # nothing to compute, just make it compatible
131
+ shape = resize if resize is not None else cellprob.shape
132
+ mask = np.zeros(shape, np.uint16)
133
+ p = np.zeros((len(shape), *shape), np.uint16)
134
+
135
+ return mask, p
136
+
137
+
138
+ def _extend_centers_gpu(
139
+ neighbors, centers, isneighbor, Ly, Lx, n_iter=200, device=torch.device("cuda")
140
+ ):
141
+ if device is not None:
142
+ device = device
143
+ nimg = neighbors.shape[0] // 9
144
+ pt = torch.from_numpy(neighbors).to(device)
145
+
146
+ T = torch.zeros((nimg, Ly, Lx), dtype=torch.double, device=device)
147
+ meds = torch.from_numpy(centers.astype(int)).to(device).long()
148
+ isneigh = torch.from_numpy(isneighbor).to(device)
149
+ for i in range(n_iter):
150
+ T[:, meds[:, 0], meds[:, 1]] += 1
151
+ Tneigh = T[:, pt[:, :, 0], pt[:, :, 1]]
152
+ Tneigh *= isneigh
153
+ T[:, pt[0, :, 0], pt[0, :, 1]] = Tneigh.mean(axis=1)
154
+ del meds, isneigh, Tneigh
155
+ T = torch.log(1.0 + T)
156
+ # gradient positions
157
+ grads = T[:, pt[[2, 1, 4, 3], :, 0], pt[[2, 1, 4, 3], :, 1]]
158
+ del pt
159
+ dy = grads[:, 0] - grads[:, 1]
160
+ dx = grads[:, 2] - grads[:, 3]
161
+ del grads
162
+ mu_torch = np.stack((dy.cpu().squeeze(), dx.cpu().squeeze()), axis=-2)
163
+ return mu_torch
164
+
165
+
166
+ def diameters(masks):
167
+ _, counts = np.unique(np.int32(masks), return_counts=True)
168
+ counts = counts[1:]
169
+ md = np.median(counts ** 0.5)
170
+ if np.isnan(md):
171
+ md = 0
172
+ md /= (np.pi ** 0.5) / 2
173
+ return md, counts ** 0.5
174
+
175
+
176
+ def masks_to_flows_gpu(masks, device=None):
177
+ if device is None:
178
+ device = torch.device("cuda")
179
+
180
+ Ly0, Lx0 = masks.shape
181
+ Ly, Lx = Ly0 + 2, Lx0 + 2
182
+
183
+ masks_padded = np.zeros((Ly, Lx), np.int64)
184
+ masks_padded[1:-1, 1:-1] = masks
185
+
186
+ # get mask pixel neighbors
187
+ y, x = np.nonzero(masks_padded)
188
+ neighborsY = np.stack((y, y - 1, y + 1, y, y, y - 1, y - 1, y + 1, y + 1), axis=0)
189
+ neighborsX = np.stack((x, x, x, x - 1, x + 1, x - 1, x + 1, x - 1, x + 1), axis=0)
190
+ neighbors = np.stack((neighborsY, neighborsX), axis=-1)
191
+
192
+ # get mask centers
193
+ slices = find_objects(masks)
194
+
195
+ centers = np.zeros((masks.max(), 2), "int")
196
+ for i, si in enumerate(slices):
197
+ if si is not None:
198
+ sr, sc = si
199
+
200
+ ly, lx = sr.stop - sr.start + 1, sc.stop - sc.start + 1
201
+ yi, xi = np.nonzero(masks[sr, sc] == (i + 1))
202
+ yi = yi.astype(np.int32) + 1 # add padding
203
+ xi = xi.astype(np.int32) + 1 # add padding
204
+ ymed = np.median(yi)
205
+ xmed = np.median(xi)
206
+ imin = np.argmin((xi - xmed) ** 2 + (yi - ymed) ** 2)
207
+ xmed = xi[imin]
208
+ ymed = yi[imin]
209
+ centers[i, 0] = ymed + sr.start
210
+ centers[i, 1] = xmed + sc.start
211
+
212
+ # get neighbor validator (not all neighbors are in same mask)
213
+ neighbor_masks = masks_padded[neighbors[:, :, 0], neighbors[:, :, 1]]
214
+ isneighbor = neighbor_masks == neighbor_masks[0]
215
+ ext = np.array(
216
+ [[sr.stop - sr.start + 1, sc.stop - sc.start + 1] for sr, sc in slices]
217
+ )
218
+ n_iter = 2 * (ext.sum(axis=1)).max()
219
+ # run diffusion
220
+ mu = _extend_centers_gpu(
221
+ neighbors, centers, isneighbor, Ly, Lx, n_iter=n_iter, device=device
222
+ )
223
+
224
+ # normalize
225
+ mu /= 1e-20 + (mu ** 2).sum(axis=0) ** 0.5
226
+
227
+ # put into original image
228
+ mu0 = np.zeros((2, Ly0, Lx0))
229
+ mu0[:, y - 1, x - 1] = mu
230
+ mu_c = np.zeros_like(mu0)
231
+ return mu0, mu_c
232
+
233
+
234
+ def masks_to_flows(masks, use_gpu=False, device=None):
235
+ if masks.max() == 0 or (masks != 0).sum() == 1:
236
+ # dynamics_logger.warning('empty masks!')
237
+ return np.zeros((2, *masks.shape), "float32")
238
+
239
+ if use_gpu:
240
+ if use_gpu and device is None:
241
+ device = torch_GPU
242
+ elif device is None:
243
+ device = torch_CPU
244
+ masks_to_flows_device = masks_to_flows_gpu
245
+
246
+ if masks.ndim == 3:
247
+ Lz, Ly, Lx = masks.shape
248
+ mu = np.zeros((3, Lz, Ly, Lx), np.float32)
249
+ for z in range(Lz):
250
+ mu0 = masks_to_flows_device(masks[z], device=device)[0]
251
+ mu[[1, 2], z] += mu0
252
+ for y in range(Ly):
253
+ mu0 = masks_to_flows_device(masks[:, y], device=device)[0]
254
+ mu[[0, 2], :, y] += mu0
255
+ for x in range(Lx):
256
+ mu0 = masks_to_flows_device(masks[:, :, x], device=device)[0]
257
+ mu[[0, 1], :, :, x] += mu0
258
+ return mu
259
+ elif masks.ndim == 2:
260
+ mu, mu_c = masks_to_flows_device(masks, device=device)
261
+ return mu
262
+
263
+ else:
264
+ raise ValueError("masks_to_flows only takes 2D or 3D arrays")
265
+
266
+
267
+ def steps2D_interp(p, dP, niter, use_gpu=False, device=None):
268
+ shape = dP.shape[1:]
269
+ if use_gpu:
270
+ if device is None:
271
+ device = torch_GPU
272
+ shape = (
273
+ np.array(shape)[[1, 0]].astype("float") - 1
274
+ ) # Y and X dimensions (dP is 2.Ly.Lx), flipped X-1, Y-1
275
+ pt = (
276
+ torch.from_numpy(p[[1, 0]].T).float().to(device).unsqueeze(0).unsqueeze(0)
277
+ ) # p is n_points by 2, so pt is [1 1 2 n_points]
278
+ im = (
279
+ torch.from_numpy(dP[[1, 0]]).float().to(device).unsqueeze(0)
280
+ ) # covert flow numpy array to tensor on GPU, add dimension
281
+ # normalize pt between 0 and 1, normalize the flow
282
+ for k in range(2):
283
+ im[:, k, :, :] *= 2.0 / shape[k]
284
+ pt[:, :, :, k] /= shape[k]
285
+
286
+ # normalize to between -1 and 1
287
+ pt = pt * 2 - 1
288
+
289
+ # here is where the stepping happens
290
+ for t in range(niter):
291
+ # align_corners default is False, just added to suppress warning
292
+ dPt = grid_sample(im, pt, align_corners=False)
293
+
294
+ for k in range(2): # clamp the final pixel locations
295
+ pt[:, :, :, k] = torch.clamp(
296
+ pt[:, :, :, k] + dPt[:, k, :, :], -1.0, 1.0
297
+ )
298
+
299
+ # undo the normalization from before, reverse order of operations
300
+ pt = (pt + 1) * 0.5
301
+ for k in range(2):
302
+ pt[:, :, :, k] *= shape[k]
303
+
304
+ p = pt[:, :, :, [1, 0]].cpu().numpy().squeeze().T
305
+ return p
306
+
307
+ else:
308
+ assert print("ho")
309
+
310
+
311
+ def follow_flows(dP, mask=None, niter=200, interp=True, use_gpu=True, device=None):
312
+ shape = np.array(dP.shape[1:]).astype(np.int32)
313
+ niter = np.uint32(niter)
314
+
315
+ p = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing="ij")
316
+ p = np.array(p).astype(np.float32)
317
+
318
+ inds = np.array(np.nonzero(np.abs(dP[0]) > 1e-3)).astype(np.int32).T
319
+
320
+ if inds.ndim < 2 or inds.shape[0] < 5:
321
+ return p, None
322
+
323
+ if not interp:
324
+ assert print("woo")
325
+
326
+ else:
327
+ p_interp = steps2D_interp(
328
+ p[:, inds[:, 0], inds[:, 1]], dP, niter, use_gpu=use_gpu, device=device
329
+ )
330
+ p[:, inds[:, 0], inds[:, 1]] = p_interp
331
+
332
+ return p, inds
333
+
334
+
335
+ def flow_error(maski, dP_net, use_gpu=False, device=None):
336
+ if dP_net.shape[1:] != maski.shape:
337
+ print("ERROR: net flow is not same size as predicted masks")
338
+ return
339
+
340
+ # flows predicted from estimated masks
341
+ dP_masks = masks_to_flows(maski, use_gpu=use_gpu, device=device)
342
+ # difference between predicted flows vs mask flows
343
+ flow_errors = np.zeros(maski.max())
344
+ for i in range(dP_masks.shape[0]):
345
+ flow_errors += mean(
346
+ (dP_masks[i] - dP_net[i] / 5.0) ** 2,
347
+ maski,
348
+ index=np.arange(1, maski.max() + 1),
349
+ )
350
+
351
+ return flow_errors, dP_masks
352
+
353
+
354
+ def remove_bad_flow_masks(masks, flows, threshold=0.4, use_gpu=False, device=None):
355
+ merrors, _ = flow_error(masks, flows, use_gpu, device)
356
+ badi = 1 + (merrors > threshold).nonzero()[0]
357
+ masks[np.isin(masks, badi)] = 0
358
+ return masks
359
+
360
+
361
+ def get_masks(p, iscell=None, rpad=20):
362
+ pflows = []
363
+ edges = []
364
+ shape0 = p.shape[1:]
365
+ dims = len(p)
366
+
367
+ for i in range(dims):
368
+ pflows.append(p[i].flatten().astype("int32"))
369
+ edges.append(np.arange(-0.5 - rpad, shape0[i] + 0.5 + rpad, 1))
370
+
371
+ h, _ = np.histogramdd(tuple(pflows), bins=edges)
372
+ hmax = h.copy()
373
+ for i in range(dims):
374
+ hmax = maximum_filter1d(hmax, 5, axis=i)
375
+
376
+ seeds = np.nonzero(np.logical_and(h - hmax > -1e-6, h > 10))
377
+ Nmax = h[seeds]
378
+ isort = np.argsort(Nmax)[::-1]
379
+ for s in seeds:
380
+ s = s[isort]
381
+
382
+ pix = list(np.array(seeds).T)
383
+
384
+ shape = h.shape
385
+ if dims == 3:
386
+ expand = np.nonzero(np.ones((3, 3, 3)))
387
+ else:
388
+ expand = np.nonzero(np.ones((3, 3)))
389
+ for e in expand:
390
+ e = np.expand_dims(e, 1)
391
+
392
+ for iter in range(5):
393
+ for k in range(len(pix)):
394
+ if iter == 0:
395
+ pix[k] = list(pix[k])
396
+ newpix = []
397
+ iin = []
398
+ for i, e in enumerate(expand):
399
+ epix = e[:, np.newaxis] + np.expand_dims(pix[k][i], 0) - 1
400
+ epix = epix.flatten()
401
+ iin.append(np.logical_and(epix >= 0, epix < shape[i]))
402
+ newpix.append(epix)
403
+ iin = np.all(tuple(iin), axis=0)
404
+ for p in newpix:
405
+ p = p[iin]
406
+ newpix = tuple(newpix)
407
+ igood = h[newpix] > 2
408
+ for i in range(dims):
409
+ pix[k][i] = newpix[i][igood]
410
+ if iter == 4:
411
+ pix[k] = tuple(pix[k])
412
+
413
+ M = np.zeros(h.shape, np.uint32)
414
+ for k in range(len(pix)):
415
+ M[pix[k]] = 1 + k
416
+
417
+ for i in range(dims):
418
+ pflows[i] = pflows[i] + rpad
419
+ M0 = M[tuple(pflows)]
420
+
421
+ # remove big masks
422
+ uniq, counts = fastremap.unique(M0, return_counts=True)
423
+ big = np.prod(shape0) * 0.9
424
+ bigc = uniq[counts > big]
425
+ if len(bigc) > 0 and (len(bigc) > 1 or bigc[0] != 0):
426
+ M0 = fastremap.mask(M0, bigc)
427
+ fastremap.renumber(M0, in_place=True) # convenient to guarantee non-skipped labels
428
+ M0 = np.reshape(M0, shape0)
429
+ return M0