DouDou commited on
Commit
4eea8c2
·
verified ·
1 Parent(s): 65e7c0a

Upload data/dataset_Organoid.csv with huggingface_hub

Browse files
Files changed (1) hide show
  1. data/dataset_Organoid.csv +1750 -0
data/dataset_Organoid.csv ADDED
@@ -0,0 +1,1750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "keyword","repo_name","file_path","file_extension","file_size","line_count","content","language"
2
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/settings.py",".py","2277","56","from pathlib import Path
3
+
4
+ def init():
5
+
6
+ global MODELS
7
+ MODELS = {
8
+ ""faster r-cnn"": {""filename"": ""faster-rcnn_r50_fpn_organoid_best_coco_bbox_mAP_epoch_68.pth"",
9
+ ""source"": ""https://zenodo.org/records/11388549/files/faster-rcnn_r50_fpn_organoid_best_coco_bbox_mAP_epoch_68.pth""
10
+ },
11
+ ""ssd"": {""filename"": ""ssd_organoid_best_coco_bbox_mAP_epoch_86.pth"",
12
+ ""source"": ""https://zenodo.org/records/11388549/files/ssd_organoid_best_coco_bbox_mAP_epoch_86.pth""
13
+ },
14
+ ""yolov3"": {""filename"": ""yolov3_416_organoid_best_coco_bbox_mAP_epoch_27.pth"",
15
+ ""source"": ""https://zenodo.org/records/11388549/files/yolov3_416_organoid_best_coco_bbox_mAP_epoch_27.pth""
16
+ },
17
+ ""rtmdet"": {""filename"": ""rtmdet_l_organoid_best_coco_bbox_mAP_epoch_323.pth"",
18
+ ""source"": ""https://zenodo.org/records/11388549/files/rtmdet_l_organoid_best_coco_bbox_mAP_epoch_323.pth""
19
+ },
20
+ }
21
+
22
+ global MODELS_DIR
23
+ MODELS_DIR = Path.home() / "".cache/napari-organoid-counter/models""
24
+
25
+ global MODEL_TYPE
26
+ MODEL_TYPE = '.pth'
27
+
28
+ global CONFIGS
29
+ CONFIGS = {
30
+ ""faster r-cnn"": {""source"": ""https://zenodo.org/records/11388549/files/faster-rcnn_r50_fpn_organoid.py"",
31
+ ""destination"": "".mim/configs/faster_rcnn/faster-rcnn_r50_fpn_organoid.py""
32
+ },
33
+ ""ssd"": {""source"": ""https://zenodo.org/records/11388549/files/ssd_organoid.py"",
34
+ ""destination"": "".mim/configs/ssd/ssd_organoid.py""
35
+ },
36
+ ""yolov3"": {""source"": ""https://zenodo.org/records/11388549/files/yolov3_416_organoid.py"",
37
+ ""destination"": "".mim/configs/yolo/yolov3_416_organoid.py""
38
+ },
39
+ ""rtmdet"": {""source"": ""https://zenodo.org/records/11388549/files/rtmdet_l_organoid.py"",
40
+ ""destination"": "".mim/configs/rtmdet/rtmdet_l_organoid.py""
41
+ }
42
+
43
+ }
44
+
45
+ # Add color definitions
46
+ global COLOR_CLASS_1
47
+ COLOR_CLASS_1 = [85 / 255, 1.0, 0, 1.0] # Green
48
+
49
+ global COLOR_CLASS_2
50
+ COLOR_CLASS_2 = [0, 29 / 255, 1.0, 1.0] # Blue
51
+
52
+ global COLOR_DEFAULT
53
+ COLOR_DEFAULT = [1., 0, 1., 1.] # Magenta
54
+
55
+
56
+
57
+ ","Python"
58
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_utils.py",".py","8253","197","from contextlib import contextmanager
59
+ import os
60
+ from pathlib import Path
61
+ import pkgutil
62
+
63
+ import numpy as np
64
+ import math
65
+ import json
66
+ import csv
67
+ from skimage.transform import rescale
68
+ from skimage.color import gray2rgb
69
+
70
+ import torch
71
+ from torchvision.ops import nms
72
+
73
+ from napari_organoid_counter import settings
74
+
75
+
76
+ def add_local_models():
77
+ """""" Checks the models directory for any local models previously added by the user.
78
+ If some are found then these are added to the model dictionary (see settings). """"""
79
+ if not os.path.exists(settings.MODELS_DIR): return
80
+ model_names_in_dir = [file for file in os.listdir(settings.MODELS_DIR)]
81
+ model_names_in_dict = [settings.MODELS[key][""filename""] for key in settings.MODELS.keys()]
82
+ for model_name in model_names_in_dir:
83
+ if model_name not in model_names_in_dict and model_name.endswith(settings.MODEL_TYPE):
84
+ _ = add_to_dict(model_name)
85
+
86
+ def add_to_dict(filepath):
87
+ """""" Given the full path and name of a model in filepath the model is added to the models dict (see settings)""""""
88
+ filepath = Path(filepath)
89
+ name = filepath.name
90
+ stem_name = filepath.stem
91
+ settings.MODELS[stem_name] = {""filename"": name, ""source"": ""local""}
92
+ return stem_name
93
+
94
+ def return_is_file(path, filename):
95
+ """""" Return True if the file exists in path and False otherwise """"""
96
+ full_path = join_paths(path, filename)
97
+ return os.path.isfile(full_path)
98
+
99
+ def join_paths(path1, path2):
100
+ """""" Returns output of os.path.join """"""
101
+ return os.path.join(path1, path2)
102
+
103
+ @contextmanager
104
+ def set_dict_key(dictionary, key, value):
105
+ """""" Used to set a new value in the napari layer metadata """"""
106
+ dictionary[key] = value
107
+ yield
108
+ del dictionary[key]
109
+
110
+ def get_diams(bbox):
111
+ """""" Get the lengths of the bounding boxes """"""
112
+ x1_real, y1_real, x2_real, y2_real = bbox
113
+ dx = abs(x1_real - x2_real)
114
+ dy = abs(y1_real - y2_real)
115
+ return dx, dy
116
+
117
+ def write_to_json(name, data):
118
+ """""" Write data to a json file. Here data is a dict """"""
119
+ with open(name, 'w') as outfile:
120
+ json.dump(data, outfile)
121
+
122
+ def get_bboxes_as_dict(bboxes, bbox_ids, scores, scales, labels):
123
+ """""" Write all data, boxes, ids and scores, scale and class label, to a dict so we can later save as a json """"""
124
+ data_json = {}
125
+ for idx, bbox in enumerate(bboxes):
126
+ x1, y1 = bbox[0]
127
+ x2, y2 = bbox[2]
128
+
129
+ data_json.update({str(bbox_ids[idx]): {'box_id': str(bbox_ids[idx]),
130
+ 'x1': str(x1),
131
+ 'x2': str(x2),
132
+ 'y1': str(y1),
133
+ 'y2': str(y2),
134
+ 'confidence': str(scores[idx]),
135
+ 'scale_x': str(scales[0]),
136
+ 'scale_y': str(scales[1]),
137
+ 'class': labels[idx]
138
+ }
139
+ })
140
+ return data_json
141
+
142
+ def write_to_csv(name, data):
143
+ """""" Write data to a csv file. Here data is a list of lists, where each item represents a row in the csv file. """"""
144
+ with open(name, 'w') as f:
145
+ write = csv.writer(f, delimiter=';')
146
+ write.writerow(['OrganoidID', 'D1[um]','D2[um]', 'Area [um^2]'])
147
+ write.writerows(data)
148
+
149
+ def get_bbox_diameters(bboxes, bbox_ids, scales):
150
+ """""" Write all data, box diameters and area, ids and scale, to a list so we can later save as a csv """"""
151
+ data_csv = []
152
+ # save diameters and area of organoids (approximated as ellipses)
153
+ for idx, bbox in enumerate(bboxes):
154
+ d1 = abs(bbox[0][0] - bbox[2][0]) * scales[0]
155
+ d2 = abs(bbox[0][1] - bbox[2][1]) * scales[1]
156
+ area = math.pi * d1 * d2
157
+ data_csv.append([bbox_ids[idx], round(d1,3), round(d2,3), round(area,3)])
158
+ return data_csv
159
+
160
+ def squeeze_img(img):
161
+ """""" Squeeze image - all dims that have size one will be removed """"""
162
+ return np.squeeze(img)
163
+
164
+ def prepare_img(test_img, step, window_size, rescale_factor):
165
+ """""" The original image is prepared for running model inference """"""
166
+ # squeeze and resize image
167
+ test_img = squeeze_img(test_img)
168
+ test_img = rescale(test_img, rescale_factor, preserve_range=True)
169
+ img_height, img_width = test_img.shape
170
+ # pad image
171
+ pad_x = (img_height//step)*step + window_size - img_height
172
+ pad_y = (img_width//step)*step + window_size - img_width
173
+ test_img = np.pad(test_img, ((0, int(pad_x)), (0, int(pad_y))), mode='edge')
174
+ # normalise and convert to RGB - model input has size 3
175
+ test_img = (test_img-np.min(test_img))/(np.max(test_img)-np.min(test_img))
176
+ test_img = (255*test_img).astype(np.uint8)
177
+ test_img = gray2rgb(test_img) #[H,W,C]
178
+
179
+ # convert from RGB to GBR - expected from DetInferencer
180
+ test_img = test_img[..., ::-1]
181
+
182
+ return test_img, img_height, img_width
183
+
184
+ def apply_nms(bbox_preds, scores_preds, iou_thresh=0.5):
185
+ """""" Function applies non max suppression to iteratively remove lower scoring boxes which have an IoU greater than iou_threshold
186
+ with another (higher scoring) box. The boxes and corresponding scores whihc remain are returned. """"""
187
+ # torchvision returns the indices of the bboxes to keep
188
+ keep = nms(bbox_preds, scores_preds, iou_thresh)
189
+ # filter existing boxes and scores and return
190
+ bbox_preds_kept = bbox_preds[keep]
191
+ scores_preds = scores_preds[keep]
192
+ return bbox_preds_kept, scores_preds
193
+
194
+ def convert_boxes_to_napari_view(pred_bboxes):
195
+ """""" The bboxes are converted from tensors in model output form to a form which can be visualised in the napari viewer """"""
196
+ if pred_bboxes is None: return []
197
+ new_boxes = []
198
+ for idx in range(pred_bboxes.size(0)):
199
+ # convert to numpy and take coordinates
200
+ x1_real, y1_real, x2_real, y2_real = pred_bboxes[idx].numpy()
201
+ # append to a list in form napari exects
202
+ new_boxes.append(np.array([[x1_real, y1_real],
203
+ [x1_real, y2_real],
204
+ [x2_real, y2_real],
205
+ [x2_real, y1_real]]))
206
+ return new_boxes
207
+
208
+ def convert_boxes_from_napari_view(pred_bboxes):
209
+ """""" The bboxes are converted from the form they were in the napari viewer to tensors that correspond to the model output form """"""
210
+ new_boxes = []
211
+ for idx in range(len(pred_bboxes)):
212
+ # read coordinates
213
+ x1 = pred_bboxes[idx][0][0]
214
+ x2 = pred_bboxes[idx][2][0]
215
+ y1 = pred_bboxes[idx][0][1]
216
+ y2 = pred_bboxes[idx][2][1]
217
+ # convert to tensor and append to list
218
+ new_boxes.append(torch.Tensor([x1, y1, x2, y2]))
219
+ if len(new_boxes) > 0: new_boxes = torch.stack(new_boxes)
220
+ return new_boxes
221
+
222
+ def apply_normalization(img):
223
+ """""" Normalize image""""""
224
+ # squeeze and change dtype
225
+ img = squeeze_img(img)
226
+ img = img.astype(np.float64)
227
+ # adapt img to range 0-255
228
+ img_min = np.min(img) # 31.3125 png 0
229
+ img_max = np.max(img) # 2899.25 png 178
230
+ img_norm = (255 * (img - img_min) / (img_max - img_min)).astype(np.uint8)
231
+ return img_norm
232
+
233
+ def get_package_init_file(package_name):
234
+ loader = pkgutil.get_loader(package_name)
235
+ if loader is None or not hasattr(loader, 'get_filename'):
236
+ raise ImportError(f""Cannot find package {package_name}"")
237
+ package_path = loader.get_filename(package_name)
238
+ # Determine the path to the __init__.py file
239
+ if os.path.isdir(package_path):
240
+ init_file_path = os.path.join(package_path, '__init__.py')
241
+ else:
242
+ init_file_path = package_path
243
+ if not os.path.isfile(init_file_path):
244
+ raise FileNotFoundError(f""__init__.py file not found for package {package_name}"")
245
+ return init_file_path
246
+
247
+ def update_version_in_mmdet_init_file(package_name, old_version, new_version):
248
+ init_file_path = get_package_init_file(package_name)
249
+ with open(init_file_path, 'r') as file:
250
+ lines = file.readlines()
251
+ with open(init_file_path, 'w') as file:
252
+ for line in lines:
253
+ if f""mmcv_maximum_version = '{old_version}'"" in line:
254
+ file.write(line.replace(old_version, new_version))","Python"
255
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_reader.py",".py","2407","60","import json
256
+ import numpy as np
257
+ from napari import layers
258
+ from pathlib import Path
259
+
260
+ readable_extensions = '.json'
261
+
262
+ def get_reader(path):
263
+ """""" A basic implementation of the napari_get_reader hook specification """"""
264
+ # if we know we cannot read the file, we immediately return None.
265
+ if not path.endswith(readable_extensions):
266
+ return None
267
+ # otherwise we return the *function* that can read ``path``.
268
+ return reader_function
269
+
270
+ def reader_function(path: str) -> layers.Shapes:
271
+ """""" Reads the labels in the json file and adds a shapes layer to the napari viewer """"""
272
+ # laod json
273
+ f = open(path)
274
+ annot = json.load(f)
275
+ # initialise empty lists for boxes, ids and scores
276
+ bboxes = []
277
+ ids = []
278
+ scores = []
279
+ # for each box
280
+ for key in annot.keys():
281
+ # read coordinates
282
+ x1 = round(int(float(annot[key]['x1'])))
283
+ y1 = round(int(float(annot[key]['y1'])))
284
+ x2 = round(int(float(annot[key]['x2'])))
285
+ y2 = round(int(float(annot[key]['y2'])))
286
+ # append in style readable by napari viewer
287
+ bboxes.append(np.array([[x1, y1],
288
+ [x1, y2],
289
+ [x2, y2],
290
+ [x2, y1]]))
291
+ # and append scores and ids whihc will be used to display as text
292
+ ids.append(int(annot[key]['box_id']))
293
+ scores.append(float(annot[key]['confidence']))
294
+
295
+ # scale will adjust boxes according to physical resolution of image
296
+ scale = (float(annot[key]['scale_x']), float(annot[key]['scale_y'])) # do only once
297
+ # name of layer which will be created
298
+ labels_name = 'Labels-'+Path(path).stem
299
+ # properties used for dusplaying text
300
+ properties = {'box_id': ids,'scores': scores}
301
+ text_params = {'string': 'ID: {box_id}\nConf.: {scores:.2f}',
302
+ 'size': 12,
303
+ 'anchor': 'upper_left',}
304
+ layer_attributes = {'name': labels_name,
305
+ 'scale': scale,
306
+ 'properties': properties,
307
+ 'text': text_params,
308
+ 'face_color': 'transparent',
309
+ 'edge_color': 'magenta',
310
+ 'shape_type': 'rectangle',
311
+ 'edge_width': 12
312
+ }
313
+ # return data, attributes for displaying and type of layer to add to viewer
314
+ return [(bboxes, layer_attributes, 'shapes')]","Python"
315
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_orgacount.py",".py","14778","286","from urllib.request import urlretrieve
316
+ from napari.utils import progress
317
+
318
+ from napari_organoid_counter._utils import *
319
+ from napari_organoid_counter import settings
320
+
321
+ #update_version_in_mmdet_init_file('mmdet', '2.2.0', '2.3.0')
322
+ import torch
323
+ import mmdet
324
+ from mmdet.apis import DetInferencer
325
+
326
+ class OrganoiDL():
327
+ '''
328
+ The back-end of the organoid counter widget
329
+ Attributes
330
+ ----------
331
+ device: torch.device
332
+ The current device, either 'cpu' or 'gpu:0'
333
+ cur_confidence: float
334
+ The confidence threshold of the model
335
+ cur_min_diam: float
336
+ The minimum diameter of the organoids
337
+ model: frcnn
338
+ The Faster R-CNN model
339
+ img_scale: list of floats
340
+ A list holding the image resolution in x and y
341
+ pred_bboxes: dict
342
+ Each key will be a set of predictions of the model, either past or current, and values will be the numpy arrays
343
+ holding the predicted bounding boxes
344
+ pred_scores: dict
345
+ Each key will be a set of predictions of the model and the values will hold the confidence of the model for each
346
+ predicted bounding box
347
+ pred_ids: dict
348
+ Each key will be a set of predictions of the model and the values will hold the box id for each
349
+ predicted bounding box
350
+ next_id: dict
351
+ Each key will be a set of predictions of the model and the values will hold the next id to be attributed to a
352
+ newly added box
353
+ '''
354
+ def __init__(self, handle_progress):
355
+ super().__init__()
356
+
357
+ self.handle_progress = handle_progress
358
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
359
+ self.cur_confidence = 0.05
360
+ self.cur_min_diam = 30
361
+
362
+ self.model = None
363
+ self.img_scale = [0., 0.]
364
+ self.pred_bboxes = {}
365
+ self.pred_scores = {}
366
+ self.pred_ids = {}
367
+ self.next_id = {}
368
+
369
+ def set_scale(self, img_scale):
370
+ ''' Set the image scale: used to calculate real box sizes. '''
371
+ self.img_scale = img_scale
372
+
373
+ def set_model(self, model_name):
374
+ ''' Initialise model instance and load model checkpoint and send to device. '''
375
+
376
+ model_checkpoint = join_paths(str(settings.MODELS_DIR), settings.MODELS[model_name][""filename""])
377
+ mmdet_path = os.path.dirname(mmdet.__file__)
378
+ config_dst = join_paths(mmdet_path, str(settings.CONFIGS[model_name][""destination""]))
379
+ # download the corresponding config if it doesn't exist already
380
+ if not os.path.exists(config_dst):
381
+ urlretrieve(settings.CONFIGS[model_name][""source""], config_dst, self.handle_progress)
382
+ self.model = DetInferencer(config_dst, model_checkpoint, self.device, show_progress=False)
383
+
384
+ def download_model(self, model_name='yolov3'):
385
+ ''' Downloads the model from zenodo and stores it in settings.MODELS_DIR '''
386
+ # specify the url of the model which is to be downloaded
387
+ down_url = settings.MODELS[model_name][""source""]
388
+ # specify save location where the file is to be saved
389
+ save_loc = join_paths(str(settings.MODELS_DIR), settings.MODELS[model_name][""filename""])
390
+ # downloading using urllib
391
+ urlretrieve(down_url, save_loc, self.handle_progress)
392
+
393
+ def sliding_window(self,
394
+ test_img,
395
+ step,
396
+ window_size,
397
+ rescale_factor,
398
+ prepadded_height,
399
+ prepadded_width,
400
+ pred_bboxes=[],
401
+ scores_list=[]):
402
+ ''' Runs sliding window inference and returns predicting bounding boxes and confidence scores for each box.
403
+ Inputs
404
+ ----------
405
+ test_img: Tensor of size [B, C, H, W]
406
+ The image ready to be given to model as input
407
+ step: int
408
+ The step of the sliding window, same in x and y
409
+ window_size: int
410
+ The sliding window size, same in x and y
411
+ rescale_factor: float
412
+ The rescaling factor by which the image has already been resized. Is 1/downsampling
413
+ prepadded_height: int
414
+ The image height before padding was applied
415
+ prepadded_width: int
416
+ The image width before padding was applied
417
+ pred_bboxes: list of
418
+ The
419
+ scores_list: list of
420
+ The
421
+ Outputs
422
+ ----------
423
+ pred_bboxes: list of Tensors, default is an empty list
424
+ The resulting predicted boxes are appended here - if model is run at different window
425
+ sizes and downsampling this list will store results of all runs of the sliding window
426
+ so will not be empty the second, third etc. time.
427
+ scores_list: list of Tensor, default is an empty list
428
+ The resulting confidence scores of the model for the predicted boxes are appended here
429
+ Same as pred_bboxes, can be empty on first run but stores results of all runs.
430
+ '''
431
+ for i in progress(range(0, prepadded_height, step)):
432
+ for j in progress(range(0, prepadded_width, step)):
433
+ # crop
434
+ img_crop = test_img[i:(i+window_size), j:(j+window_size)]
435
+ # get predictions
436
+ output = self.model(img_crop)
437
+ preds = output['predictions'][0]['bboxes']
438
+ if len(preds)==0: continue
439
+ else:
440
+ for bbox_id in range(len(preds)):
441
+ y1, x1, y2, x2 = preds[bbox_id] # predictions from model will be in form x1,y1,x2,y2
442
+ x1_real = torch.div(x1+i, rescale_factor, rounding_mode='floor')
443
+ x2_real = torch.div(x2+i, rescale_factor, rounding_mode='floor')
444
+ y1_real = torch.div(y1+j, rescale_factor, rounding_mode='floor')
445
+ y2_real = torch.div(y2+j, rescale_factor, rounding_mode='floor')
446
+ pred_bboxes.append(torch.Tensor([x1_real, y1_real, x2_real, y2_real]))
447
+ scores_list.append(output['predictions'][0]['scores'][bbox_id])
448
+ return pred_bboxes, scores_list
449
+
450
+ def run(self,
451
+ img,
452
+ shapes_name,
453
+ window_sizes,
454
+ downsampling_sizes,
455
+ window_overlap):
456
+ ''' Runs inference for an image at multiple window sizes and downsampling rates using sliding window ineference.
457
+ The results are filtered using the NMS algorithm and are then stored to dicts.
458
+ Inputs
459
+ ----------
460
+ img: Numpy array of size [H, W]
461
+ The image ready to be given to model as input
462
+ shapes_name: str
463
+ The name of the new predictions
464
+ window_size: list of ints
465
+ The sliding window size, same in x and y, if multiple sliding window will run mulitple times
466
+ downsampling_sizes: list of ints
467
+ The downsampling factor of the image, list size must match window_size
468
+ window_overlap: float
469
+ The window overlap for the sliding window inference.
470
+ '''
471
+ bboxes = []
472
+ scores = []
473
+ # run for all window sizes
474
+ for window_size, downsampling in zip(window_sizes, downsampling_sizes):
475
+ # compute the step for the sliding window, based on window overlap
476
+ rescale_factor = 1 / downsampling
477
+ # window size after rescaling
478
+ window_size = round(window_size * rescale_factor)
479
+ step = round(window_size * window_overlap)
480
+ # prepare image for model - norm, tensor, etc.
481
+ ready_img, prepadded_height, prepadded_width = prepare_img(img,
482
+ step,
483
+ window_size,
484
+ rescale_factor)
485
+ # and run sliding window over whole image
486
+ bboxes, scores = self.sliding_window(ready_img,
487
+ step,
488
+ window_size,
489
+ rescale_factor,
490
+ prepadded_height,
491
+ prepadded_width,
492
+ bboxes,
493
+ scores)
494
+ # stack results
495
+ bboxes = torch.stack(bboxes)
496
+ scores = torch.Tensor(scores)
497
+ # apply NMS to remove overlaping boxes
498
+ bboxes, pred_scores = apply_nms(bboxes, scores)
499
+ self.pred_bboxes[shapes_name] = bboxes
500
+ self.pred_scores[shapes_name] = pred_scores
501
+ num_predictions = bboxes.size(0)
502
+ self.pred_ids[shapes_name] = [(i+1) for i in range(num_predictions)]
503
+ self.next_id[shapes_name] = num_predictions+1
504
+
505
+ def apply_params(self, shapes_name, confidence, min_diameter_um):
506
+ """""" After results have been stored in dict this function will filter the dicts based on the confidence
507
+ and min_diameter_um thresholds for the given results defined by shape_name and return the filtered dicts. """"""
508
+ self.cur_confidence = confidence
509
+ self.cur_min_diam = min_diameter_um
510
+ pred_bboxes, pred_scores, pred_ids = self._apply_confidence_thresh(shapes_name)
511
+ if pred_bboxes.size(0)!=0:
512
+ pred_bboxes, pred_scores, pred_ids = self._filter_small_organoids(pred_bboxes, pred_scores, pred_ids)
513
+ pred_bboxes = convert_boxes_to_napari_view(pred_bboxes)
514
+ return pred_bboxes, pred_scores, pred_ids
515
+
516
+ def _apply_confidence_thresh(self, shapes_name):
517
+ """""" Filters out results of shapes_name based on the current confidence threshold. """"""
518
+ if shapes_name not in self.pred_bboxes.keys(): return torch.empty((0))
519
+ keep = (self.pred_scores[shapes_name]>self.cur_confidence).nonzero(as_tuple=True)[0]
520
+ result_bboxes = self.pred_bboxes[shapes_name][keep]
521
+ result_scores = self.pred_scores[shapes_name][keep]
522
+ result_ids = [self.pred_ids[shapes_name][int(i)] for i in keep.tolist()]
523
+ return result_bboxes, result_scores, result_ids
524
+
525
+ def _filter_small_organoids(self, pred_bboxes, pred_scores, pred_ids):
526
+ """""" Filters out small result boxes of shapes_name based on the current min diameter size. """"""
527
+ if pred_bboxes is None: return None
528
+ if len(pred_bboxes)==0: return None
529
+ min_diameter_x = self.cur_min_diam / self.img_scale[0]
530
+ min_diameter_y = self.cur_min_diam / self.img_scale[1]
531
+ keep = []
532
+ for idx in range(len(pred_bboxes)):
533
+ dx, dy = get_diams(pred_bboxes[idx])
534
+ if (dx >= min_diameter_x and dy >= min_diameter_y) or pred_scores[idx] == 1: keep.append(idx)
535
+ pred_bboxes = pred_bboxes[keep]
536
+ pred_scores = pred_scores[keep]
537
+ pred_ids = [pred_ids[i] for i in keep]
538
+ return pred_bboxes, pred_scores, pred_ids
539
+
540
+ def update_bboxes_scores(self, shapes_name, new_bboxes, new_scores, new_ids):
541
+ ''' Updated the results dicts, self.pred_bboxes, self.pred_scores and self.pred_ids with new results.
542
+ If the shapes name doesn't exist as a key in the dicts the results are added with the new key. If the
543
+ key exists then new_bboxes, new_scores and new_ids are compared to the class result dicts and the dicts
544
+ are updated, either by adding some box (user added box) or removing some box (user deleted a prediction).'''
545
+
546
+ new_bboxes = convert_boxes_from_napari_view(new_bboxes)
547
+ new_scores = torch.Tensor(list(new_scores))
548
+ new_ids = list(new_ids)
549
+ # if run hasn't been run
550
+ if shapes_name not in self.pred_bboxes.keys():
551
+ self.pred_bboxes[shapes_name] = new_bboxes
552
+ self.pred_scores[shapes_name] = new_scores
553
+ self.pred_ids[shapes_name] = new_ids
554
+ self.next_id[shapes_name] = len(new_ids)+1
555
+
556
+ elif len(new_ids)==0: return
557
+
558
+ else:
559
+ min_diameter_x = self.cur_min_diam / self.img_scale[0]
560
+ min_diameter_y = self.cur_min_diam / self.img_scale[1]
561
+ # find ids that do are not in self.pred_ids but are in new_ids
562
+ added_box_ids = list(set(new_ids).difference(self.pred_ids[shapes_name]))
563
+ if len(added_box_ids) > 0:
564
+ added_ids = [new_ids.index(box_id) for box_id in added_box_ids]
565
+ # and add them
566
+ self.pred_bboxes[shapes_name] = torch.cat((self.pred_bboxes[shapes_name], new_bboxes[added_ids]))
567
+ self.pred_scores[shapes_name] = torch.cat((self.pred_scores[shapes_name], new_scores[added_ids]))
568
+ new_ids_to_add = [new_ids[i] for i in added_ids]
569
+ self.pred_ids[shapes_name].extend(new_ids_to_add)
570
+
571
+ # and find ids that are in self.pred_ids and not in new_ids
572
+ potential_removed_box_ids = list(set(self.pred_ids[shapes_name]).difference(new_ids))
573
+ if len(potential_removed_box_ids) > 0:
574
+ potential_removed_ids = [self.pred_ids[shapes_name].index(box_id) for box_id in potential_removed_box_ids]
575
+ remove_ids = []
576
+ for idx in potential_removed_ids:
577
+ dx, dy = get_diams(self.pred_bboxes[shapes_name][idx])
578
+ if self.pred_scores[shapes_name][idx] > self.cur_confidence and dx > min_diameter_x and dy > min_diameter_y:
579
+ remove_ids.append(idx)
580
+ # and remove them
581
+ for idx in reversed(remove_ids):
582
+ self.pred_bboxes[shapes_name] = torch.cat((self.pred_bboxes[shapes_name][:idx, :], self.pred_bboxes[shapes_name][idx+1:, :]))
583
+ self.pred_scores[shapes_name] = torch.cat((self.pred_scores[shapes_name][:idx], self.pred_scores[shapes_name][idx+1:]))
584
+ new_pred_ids = self.pred_ids[shapes_name][:idx]
585
+ new_pred_ids.extend(self.pred_ids[shapes_name][idx+1:])
586
+ self.pred_ids[shapes_name] = new_pred_ids
587
+
588
+ def update_next_id(self, shapes_name, c=0):
589
+ """""" Updates the next id to append to result dicts. If input c is given then that will be the next id. """"""
590
+ if c!=0:
591
+ self.next_id[shapes_name] = c
592
+ else: self.next_id[shapes_name] += 1
593
+
594
+ def remove_shape_from_dict(self, shapes_name):
595
+ """""" Removes results of shapes_name from all result dicts. """"""
596
+ del self.pred_bboxes[shapes_name]
597
+ del self.pred_scores[shapes_name]
598
+ del self.pred_ids[shapes_name]
599
+ del self.next_id[shapes_name]
600
+ ","Python"
601
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/__init__.py",".py","178","8","try:
602
+ from ._version import version as __version__
603
+ except ImportError:
604
+ __version__ = ""unknown""
605
+
606
+ from ._widget import OrganoidCounterWidget
607
+ from ._reader import get_reader
608
+ ","Python"
609
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_widget.py",".py","49792","995","from typing import List
610
+
611
+ from skimage.io import imsave
612
+ from datetime import datetime
613
+
614
+ import napari
615
+
616
+ from napari import layers
617
+ from napari.utils.notifications import show_info, show_error, show_warning
618
+
619
+ import numpy as np
620
+
621
+ from qtpy.QtCore import Qt
622
+ from qtpy.QtWidgets import QWidget, QVBoxLayout, QApplication, QDialog, QFileDialog, QGroupBox, QHBoxLayout, QLabel, QComboBox, QPushButton, QLineEdit, QProgressBar, QSlider
623
+
624
+ from napari_organoid_counter._orgacount import OrganoiDL
625
+ from napari_organoid_counter import _utils as utils
626
+ from napari_organoid_counter import settings
627
+
628
+ import warnings
629
+ warnings.filterwarnings(""ignore"")
630
+
631
+
632
+ class OrganoidCounterWidget(QWidget):
633
+ '''
634
+ The main widget of the organoid counter
635
+ Parameters
636
+ ----------
637
+ napari_viewer: string
638
+ The current napari viewer
639
+ window_sizes: list of ints, default [1024]
640
+ A list with the sizes of the windows on which the model will be run. If more than one window_size is given then the model will run on several window sizes and then
641
+ combine the results
642
+ downsampling:list of ints, default [2]
643
+ A list with the sizes of the downsampling ratios for each window size. List size must be the same as the window_sizes list
644
+ min_diameter: int, default 30
645
+ The minimum organoid diameter given in um
646
+ confidence: float, default 0.8
647
+ The model confidence threhsold - equivalent to box_score_thresh of faster_rcnn
648
+ Attributes
649
+ ----------
650
+ model_name: str
651
+ The name of the model user has selected
652
+ image_layer_names: list of strings
653
+ Will hold the names of all the currently open images in the viewer
654
+ image_layer_name: string
655
+ The image we are currently working on
656
+ shape_layer_names: list of strings
657
+ Will hold the names of all the currently open images in the viewer
658
+ save_layer_name: string
659
+ The name of the shapes layer that has been selected for saving
660
+ cur_shapes_name: string
661
+ The name of the shapes layer that has been selected for visualisation
662
+ cur_shapes_layer: napari.layers.Shapes
663
+ The current shapes layer we are working on - it's name should correspond to cur_shapes_name
664
+ organoiDL: OrganoiDL
665
+ The class in which all the computations are performed for computing and storing the organoids bounding boxes and confidence scores
666
+ num_organoids: int
667
+ The current number of organoids
668
+ original_images: dict
669
+ original_contrast: dict
670
+ '''
671
+ def __init__(self,
672
+ napari_viewer,
673
+ window_sizes: List = [1024],
674
+ downsampling: List = [2],
675
+ window_overlap: float = 0.5,
676
+ min_diameter: int = 30,
677
+ confidence: float = 0.8):
678
+ super().__init__()
679
+
680
+ # assign class variables
681
+ self.viewer = napari_viewer
682
+
683
+ # create cache dir for models if it doesn't exist and add any previously added local
684
+ # models to the model dict
685
+ settings.init()
686
+ settings.MODELS_DIR.mkdir(parents=True, exist_ok=True)
687
+ utils.add_local_models()
688
+ self.model_id = 2 # yolov3
689
+ self.model_name = list(settings.MODELS.keys())[self.model_id]
690
+
691
+ # init params
692
+ self.window_sizes = window_sizes
693
+ self.downsampling = downsampling
694
+ self.window_overlap = window_overlap
695
+ self.min_diameter = min_diameter
696
+ self.confidence = confidence
697
+
698
+ self.image_layer_names = []
699
+ self.image_layer_name = None
700
+ self.shape_layer_names = []
701
+ self.save_layer_name = ''
702
+ self.cur_shapes_name = ''
703
+ self.cur_shapes_layer = None
704
+ self.num_organoids = 0
705
+ self.original_images = {}
706
+ self.original_contrast = {}
707
+ self.stored_confidences = {}
708
+ self.stored_diameters = {}
709
+
710
+ # Initialize multi_annotation_mode to False by default
711
+ self.multi_annotation_mode = False
712
+ # self.single_annotation_mode = True # Initially, it's single annotation mode
713
+
714
+ # setup gui
715
+ self.setLayout(QVBoxLayout())
716
+ self.layout().addWidget(self._setup_input_widget())
717
+ self.layout().addWidget(self._setup_output_widget())
718
+
719
+ # initialise organoidl instance
720
+ self.organoiDL = OrganoiDL(self.handle_progress)
721
+
722
+ # get already opened layers
723
+ self.image_layer_names = self._get_layer_names()
724
+ if len(self.image_layer_names)>0: self._update_added_image(self.image_layer_names)
725
+ self.shape_layer_names = self._get_layer_names(layer_type=layers.Shapes)
726
+ if len(self.shape_layer_names)>0: self._update_added_shapes(self.shape_layer_names)
727
+ # and watch for newly added images or shapes
728
+ self.viewer.layers.events.inserted.connect(self._added_layer)
729
+ self.viewer.layers.events.removed.connect(self._removed_layer)
730
+ self.viewer.layers.selection.events.changed.connect(self._sel_layer_changed)
731
+
732
+ # setup flags used for changing slider and text of min diameter and confidence threshold
733
+ self.diameter_slider_changed = False
734
+ self.confidence_slider_changed = False
735
+
736
+ # Key binding to change the edge_color of the bounding boxes to green
737
+ @self.viewer.bind_key('g')
738
+ def change_edge_color_to_green(viewer: napari.Viewer):
739
+ if not self.multi_annotation_mode: # Check if single-annotation mode is active
740
+ show_error(""Cannot change edge color. Change to multi-annotation mode to enable this feature."")
741
+ return
742
+ if self.cur_shapes_layer is not None: # Ensure shapes layer exists
743
+ selected_shapes = self.cur_shapes_layer.selected_data # Retrieves indices of shapes currently selected, returns a set
744
+ if len(selected_shapes) > 0:
745
+ # Modify the edge color only for the selected shapes
746
+ current_edge_colors = self.cur_shapes_layer.edge_color
747
+ for idx in selected_shapes:
748
+ # Save original color
749
+ # if idx not in self.original_colors:
750
+ # self.original_colors[idx] = current_edge_colors[idx].copy()
751
+ # Update to the new color
752
+ current_edge_colors[idx] = settings.COLOR_CLASS_1
753
+ self.cur_shapes_layer.edge_color = current_edge_colors # Apply the changes
754
+ show_info(f""Changed edge color of shapes {list(selected_shapes)} to green."")
755
+ else:
756
+ show_warning(""No shapes selected to change edge color."")
757
+
758
+ # Key binding to change the edge_color of the bounding boxes to blue
759
+ @self.viewer.bind_key('h')
760
+ def change_edge_color_to_blue(viewer: napari.Viewer):
761
+ if not self.multi_annotation_mode: # Check if single-annotation mode is active
762
+ show_error(""Cannot change edge color. Change to multi-annotation mode to enable this feature."")
763
+ return
764
+ if self.cur_shapes_layer is not None: # Ensure shapes layer exists
765
+ selected_shapes = self.cur_shapes_layer.selected_data
766
+ if len(selected_shapes) > 0:
767
+ # Modify the edge color only for the selected shapes
768
+ current_edge_colors = self.cur_shapes_layer.edge_color
769
+ for idx in selected_shapes:
770
+ # Save original color
771
+ # if idx not in self.original_colors:
772
+ # self.original_colors[idx] = current_edge_colors[idx].copy()
773
+ # Update to the new color
774
+ current_edge_colors[idx] = settings.COLOR_CLASS_2
775
+ self.cur_shapes_layer.edge_color = current_edge_colors # Apply the changes
776
+ show_info(f""Changed edge color of {list(selected_shapes)} to blue."")
777
+ else:
778
+ show_warning(""No shapes selected to change edge color."")
779
+
780
+ # Key binding to reset the edge_color of selected bounding boxes to the original magenta color
781
+ @self.viewer.bind_key('m')
782
+ def change_to_original_color(viewer: napari.Viewer):
783
+ if not self.multi_annotation_mode: # Check if single-annotation mode is active
784
+ show_info(""Cannot change edge color. Change to multi-annotation mode to enable this feature."")
785
+ return
786
+ if self.cur_shapes_layer is not None: # Ensure shapes layer exists
787
+ selected_shapes = self.cur_shapes_layer.selected_data
788
+ if len(selected_shapes) > 0:
789
+ current_edge_colors = self.cur_shapes_layer.edge_color
790
+ # Modify the edge color only for the selected shapes
791
+ current_edge_colors = self.cur_shapes_layer.edge_color
792
+ for idx in selected_shapes:
793
+ # if idx in self.original_colors:
794
+ # Revert to the original color
795
+ current_edge_colors[idx] = settings.COLOR_DEFAULT
796
+ self.cur_shapes_layer.edge_color = current_edge_colors # Apply the changes
797
+ show_info(f""Reset edge color of {list(selected_shapes)} to magenta."")
798
+ else:
799
+ show_warning(""No shapes selected to reset edge color."")
800
+
801
+
802
+ def handle_progress(self, blocknum, blocksize, totalsize):
803
+ """""" When the model is being downloaded, this method is called and th progress of the download
804
+ is calculated and displayed on the progress bar. This function was re-implemented from:
805
+ https://www.geeksforgeeks.org/pyqt5-how-to-automate-progress-bar-while-downloading-using-urllib/ """"""
806
+ read_data = blocknum * blocksize # calculate the progress
807
+ if totalsize > 0:
808
+ download_percentage = read_data * 100 / totalsize
809
+ self.progress_bar.setValue(int(download_percentage))
810
+ QApplication.processEvents()
811
+
812
+ def _sel_layer_changed(self, event):
813
+ """""" Is called whenever the user selects a different layer to work on. """"""
814
+ cur_layer_list = list(self.viewer.layers.selection)
815
+ if len(cur_layer_list)==0: return
816
+ cur_seg_selected = cur_layer_list[-1]
817
+ # switch to values of other shapes layer if clicked
818
+ if type(cur_seg_selected)==layers.Shapes:
819
+ if self.cur_shapes_layer is not None:
820
+ self.stored_confidences[self.cur_shapes_name] = self.confidence_slider.value()/100
821
+ self.stored_diameters[self.cur_shapes_name] = self.min_diameter_slider.value()
822
+ self.cur_shapes_layer = cur_seg_selected
823
+ self.cur_shapes_name = cur_seg_selected.name
824
+ # update min diameter text and slider with previous value of that layer
825
+ self.min_diameter = self.stored_diameters[self.cur_shapes_name]
826
+ self.min_diameter_textbox.setText(str(self.min_diameter))
827
+ # update confidence text and slider with previous value of that layer
828
+ self.confidence = self.stored_confidences[self.cur_shapes_name]
829
+ self.confidence_textbox.setText(str(self.confidence))
830
+
831
+ def _added_layer(self, event):
832
+ # get names of added layers, image and shapes
833
+ new_image_layer_names = self._get_layer_names()
834
+ new_shape_layer_names = self._get_layer_names(layer_type=layers.Shapes)
835
+ new_image_layer_names = [name for name in new_image_layer_names if name not in self.image_layer_names]
836
+ new_shape_layer_names = [name for name in new_shape_layer_names if name not in self.shape_layer_names]
837
+ if len(new_image_layer_names)>0 :
838
+ self._update_added_image(new_image_layer_names)
839
+ self.image_layer_names.extend(new_image_layer_names)
840
+ if len(new_shape_layer_names)>0:
841
+ self._update_added_shapes(new_shape_layer_names)
842
+ self.shape_layer_names.extend(new_shape_layer_names)
843
+
844
+ def _removed_layer(self, event):
845
+ """""" Is called whenever a layer has been deleted (by the user) and removes the layer from GUI and backend. """"""
846
+ new_image_layer_names = self._get_layer_names()
847
+ new_shape_layer_names = self._get_layer_names(layer_type=layers.Shapes)
848
+ removed_image_layer_names = [name for name in self.image_layer_names if name not in new_image_layer_names]
849
+ removed_shape_layer_names = [name for name in self.shape_layer_names if name not in new_shape_layer_names]
850
+ if len(removed_image_layer_names)>0:
851
+ self._update_removed_image(removed_image_layer_names)
852
+ self.image_layer_names = new_image_layer_names
853
+ if len(removed_shape_layer_names)>0:
854
+ self._update_remove_shapes(removed_shape_layer_names)
855
+ self.shape_layer_names = new_shape_layer_names
856
+
857
+ def _preprocess(self):
858
+ """""" Preprocess the current image in the viewer to improve visualisation for the user """"""
859
+ img = self.original_images[self.image_layer_name]
860
+ img = utils.apply_normalization(img)
861
+ self.viewer.layers[self.image_layer_name].data = img
862
+ self.viewer.layers[self.image_layer_name].contrast_limits = (0,255)
863
+
864
+ def _update_num_organoids(self, len_bboxes):
865
+ """""" Updates the number of organoids displayed in the viewer """"""
866
+ self.num_organoids = len_bboxes
867
+ new_text = 'Number of organoids: '+str(self.num_organoids)
868
+ self.organoid_number_label.setText(new_text)
869
+
870
+ def _update_vis_bboxes(self, bboxes, scores, box_ids, labels_layer_name):
871
+ """""" Adds the shapes layer to the viewer or updates it if already there """"""
872
+ self._update_num_organoids(len(bboxes))
873
+ # if layer already exists
874
+ if labels_layer_name in self.shape_layer_names:
875
+ self.viewer.layers[labels_layer_name].data = bboxes # hack to get edge_width stay the same!
876
+ self.viewer.layers[labels_layer_name].properties = {'box_id': box_ids,'scores': scores}
877
+ self.viewer.layers[labels_layer_name].edge_width = 12
878
+ self.viewer.layers[labels_layer_name].refresh()
879
+ self.viewer.layers[labels_layer_name].refresh_text()
880
+ # or if this is the first run
881
+ else:
882
+ # if no organoids were found just make an empty shapes layer
883
+ if self.num_organoids==0:
884
+ self.cur_shapes_layer = self.viewer.add_shapes(name=labels_layer_name,
885
+ properties={'box_id': [],'scores': []})
886
+ # otherwise make the layer and add the boxes
887
+ else:
888
+ properties = {'box_id': box_ids,'scores': scores}
889
+ text_params = {'string': 'ID: {box_id}\nConf.: {scores:.2f}',
890
+ 'size': 12,
891
+ 'anchor': 'upper_left',}
892
+ self.cur_shapes_layer = self.viewer.add_shapes(bboxes,
893
+ name=labels_layer_name,
894
+ scale=self.viewer.layers[self.image_layer_name].scale,
895
+ face_color='transparent',
896
+ properties = properties,
897
+ text = text_params,
898
+ edge_color=settings.COLOR_DEFAULT,
899
+ shape_type='rectangle',
900
+ edge_width=12) # warning generated here
901
+
902
+ # set current_edge_width so edge width is the same when users annotate - doesnt' fix new preds being added!
903
+ self.viewer.layers[labels_layer_name].current_edge_width = 12
904
+
905
+
906
+ def _on_preprocess_click(self):
907
+ """""" Is called whenever preprocess button is clicked """"""
908
+ if not self.image_layer_name: show_info('Please load an image first and try again!')
909
+ else: self._preprocess()
910
+
911
+ def _on_run_click(self):
912
+ """""" Is called whenever Run Organoid Counter button is clicked """"""
913
+ # check if an image has been loaded
914
+ if not self.image_layer_name:
915
+ show_info('Please load an image first and try again!')
916
+ return
917
+ # check if model exists locally and if not ask user if it's ok to download
918
+ if not utils.return_is_file(settings.MODELS_DIR, settings.MODELS[self.model_name][""filename""]):
919
+ confirm_window = ConfirmUpload(self)
920
+ confirm_window.exec_()
921
+ # if user clicks cancel return doing nothing
922
+ if confirm_window.result() != QDialog.Accepted: return
923
+ # otherwise donwload model and display progress in progress bar
924
+ else:
925
+ self.progress_box.show()
926
+ self.organoiDL.download_model(self.model_name)
927
+ self.progress_box.hide()
928
+
929
+ # load model checkpoint
930
+ self.organoiDL.set_model(self.model_name)
931
+ if self.organoiDL.img_scale[0]==0: self.organoiDL.set_scale(self.viewer.layers[self.image_layer_name].scale)
932
+
933
+ # make sure the number of windows and downsamplings are the same
934
+ if len(self.window_sizes) != len(self.downsampling):
935
+ show_info('Keep number of window sizes and downsampling the same and try again!')
936
+ return
937
+
938
+ # get the current image
939
+ img_data = self.viewer.layers[self.image_layer_name].data
940
+
941
+ # check that image is grayscale
942
+ if len(utils.squeeze_img(img_data).shape) > 2:
943
+ show_info('Only grayscale images currently supported. Try a different image or process it first and try again!')
944
+ return
945
+
946
+ # update the viewer with the new bboxes
947
+ labels_layer_name = 'Labels-'+self.image_layer_name
948
+ if labels_layer_name in self.shape_layer_names:
949
+ show_info('Found existing labels layer. Please remove or rename it and try again!')
950
+ return
951
+
952
+ # show activity docker for progrgess bar while running
953
+ self.viewer.window._status_bar._toggle_activity_dock(True)
954
+
955
+ # run inference
956
+ self.organoiDL.run(img_data,
957
+ labels_layer_name,
958
+ self.window_sizes,
959
+ self.downsampling,
960
+ self.window_overlap)
961
+
962
+ # set the confidence threshold, remove small organoids and get bboxes in format o visualise
963
+ bboxes, scores, box_ids = self.organoiDL.apply_params(labels_layer_name, self.confidence, self.min_diameter)
964
+ # hide activcity dock on completion
965
+ self.viewer.window._status_bar._toggle_activity_dock(False)
966
+ # update widget with results
967
+ self._update_vis_bboxes(bboxes, scores, box_ids, labels_layer_name)
968
+ # and update cur_shapes_name to newly created shapes layer
969
+ self.cur_shapes_name = labels_layer_name
970
+ # preprocess the image if not done so already to improve visualisation
971
+ self._preprocess()
972
+
973
+ def _on_model_selection_changed(self):
974
+ """""" Is called when user selects a new model from the dropdown menu. """"""
975
+ self.model_name = self.model_selection.currentText()
976
+
977
+ def _on_choose_model_clicked(self):
978
+ """""" Is called whenever browse button is clicked for model selection """"""
979
+ # called when the user hits the 'browse' button to select a model
980
+ fd = QFileDialog()
981
+ fd.setFileMode(QFileDialog.AnyFile)
982
+ if fd.exec_():
983
+ model_path = fd.selectedFiles()[0]
984
+ import shutil
985
+ shutil.copy2(model_path, settings.MODELS_DIR)
986
+ model_name = utils.add_to_dict(model_path)
987
+ self.model_selection.addItem(model_name)
988
+
989
+ def _on_window_sizes_changed(self):
990
+ """""" Is called whenever user changes the window sizes text box """"""
991
+ new_window_sizes = self.window_sizes_textbox.text()
992
+ new_window_sizes = new_window_sizes.split(',')
993
+ self.window_sizes = [int(win_size) for win_size in new_window_sizes]
994
+
995
+ def _on_downsampling_changed(self):
996
+ """""" Is called whenever user changes the downsampling text box """"""
997
+ new_downsampling = self.downsampling_textbox.text()
998
+ new_downsampling = new_downsampling.split(',')
999
+ self.downsampling = [int(ds) for ds in new_downsampling]
1000
+
1001
+ def _rerun(self):
1002
+ """""" Is called whenever user changes one of the two parameter sliders """"""
1003
+ # check if OrganoiDL instance exists - create it if not and set there current boxes, scores and ids
1004
+ if self.organoiDL.img_scale[0]==0: self.organoiDL.set_scale(self.cur_shapes_layer.scale)
1005
+ self.organoiDL.update_next_id(self.cur_shapes_name, len(self.cur_shapes_layer.scale)+1)
1006
+
1007
+ # make sure to add info to cur_shapes_layer.metadata to differentiate this action from when user adds/removes boxes
1008
+ with utils.set_dict_key( self.cur_shapes_layer.metadata, 'napari-organoid-counter:_rerun', True):
1009
+ # first update bboxes in organoiDLin case user has added/removed
1010
+ self.organoiDL.update_bboxes_scores(self.cur_shapes_name,
1011
+ self.cur_shapes_layer.data,
1012
+ self.cur_shapes_layer.properties['scores'],
1013
+ self.cur_shapes_layer.properties['box_id'])
1014
+ # and get new boxes, scores and box ids based on new confidence and min_diameter values
1015
+ bboxes, scores, box_ids = self.organoiDL.apply_params(self.cur_shapes_name, self.confidence, self.min_diameter)
1016
+ self._update_vis_bboxes(bboxes, scores, box_ids, self.cur_shapes_name)
1017
+
1018
+ def _on_diameter_slider_changed(self):
1019
+ """""" Is called whenever user changes the Minimum Diameter slider """"""
1020
+ # get current value
1021
+ self.min_diameter = self.min_diameter_slider.value()
1022
+ self.diameter_slider_changed = True
1023
+ if int(self.min_diameter_textbox.text())!= self.min_diameter:
1024
+ self.min_diameter_textbox.setText(str(self.min_diameter))
1025
+ self.diameter_slider_changed = False
1026
+ # check if no labels loaded yet
1027
+ if len(self.shape_layer_names)==0: return
1028
+ self._rerun()
1029
+
1030
+ def _on_diameter_textbox_changed(self):
1031
+ """""" Is called whenever user changes the minimum diameter from the textbox """"""
1032
+ # check if no labels loaded yet
1033
+ if self.diameter_slider_changed: return
1034
+ self.min_diameter = int(self.min_diameter_textbox.text())
1035
+ if self.min_diameter_slider.value() != self.min_diameter:
1036
+ self.min_diameter_slider.setValue(self.min_diameter)
1037
+ if len(self.shape_layer_names)==0: return
1038
+ self._rerun()
1039
+
1040
+ def _on_confidence_slider_changed(self):
1041
+ """""" Is called whenever user changes the confidence slider """"""
1042
+ self.confidence = self.confidence_slider.value()/100
1043
+ self.confidence_slider_changed = True
1044
+ if float(self.confidence_textbox.text()) != self.confidence:
1045
+ self.confidence_textbox.setText(str(self.confidence))
1046
+ self.confidence_slider_changed = False
1047
+ # check if no labels loaded yet
1048
+ if len(self.shape_layer_names)==0: return
1049
+ self._rerun()
1050
+
1051
+ def _on_confidence_textbox_changed(self):
1052
+ """""" Is called whenever user changes the confidence value from the textbox """"""
1053
+ if self.confidence_slider_changed: return
1054
+ self.confidence = float(self.confidence_textbox.text())
1055
+ slider_conf_value = int(self.confidence*100)
1056
+ if self.confidence_slider.value() != slider_conf_value:
1057
+ self.confidence_slider.setValue(slider_conf_value)
1058
+ if len(self.shape_layer_names)==0: return
1059
+ self._rerun()
1060
+
1061
+ def _on_image_selection_changed(self):
1062
+ """""" Is called whenever a new image has been selected from the drop down box """"""
1063
+ self.image_layer_name = self.image_layer_selection.currentText()
1064
+
1065
+ def _on_shapes_selection_changed(self):
1066
+ """""" Is called whenever a new shapes layer has been selected from the drop down box """"""
1067
+ self.save_layer_name = self.output_layer_selection.currentText()
1068
+
1069
+ def _on_reset_click(self):
1070
+ """""" Is called whenever Reset Configs button is clicked """"""
1071
+ # reset params
1072
+ self.min_diameter = 30
1073
+ self.confidence = 0.8
1074
+ vis_confidence = int(self.confidence*100)
1075
+ self.min_diameter_slider.setValue(self.min_diameter)
1076
+ self.confidence_slider.setValue(vis_confidence)
1077
+ if self.image_layer_name:
1078
+ # reset to original image
1079
+ self.viewer.layers[self.image_layer_name].data = self.original_images[self.image_layer_name]
1080
+ self.viewer.layers[self.image_layer_name].contrast_limits = self.original_contrast[self.image_layer_name]
1081
+
1082
+ def _on_screenshot_click(self):
1083
+ """""" Is called whenever Take Screenshot button is clicked """"""
1084
+ screenshot=self.viewer.screenshot()
1085
+ if not self.image_layer_name: potential_name = datetime.now().strftime(""%d%m%Y%H%M%S"")+'screenshot.png'
1086
+ else: potential_name = self.image_layer_name+datetime.now().strftime(""%d%m%Y%H%M%S"")+'_screenshot.png'
1087
+ fd = QFileDialog()
1088
+ name,_ = fd.getSaveFileName(self, 'Save File', potential_name, 'Image files (*.png);;(*.tiff)') #, 'CSV Files (*.csv)')
1089
+ if name: imsave(name, screenshot)
1090
+
1091
+ def on_annotation_mode_changed(self, index):
1092
+ """"""Callback for dropdown selection.""""""
1093
+ if index == 0: # Single Annotation
1094
+ self.multi_annotation_mode = False
1095
+ # self.single_annotation_mode = True
1096
+ show_info(""Switched to Single Annotation mode."")
1097
+ elif index == 1: # Multi Annotation
1098
+ self.multi_annotation_mode = True
1099
+ # self.single_annotation_mode = False
1100
+ show_info(""Switched to Multi Annotation mode."")
1101
+
1102
+ def _on_save_csv_click(self):
1103
+ """""" Is called whenever Save features button is clicked """"""
1104
+ bboxes = self.viewer.layers[self.save_layer_name].data
1105
+ if not bboxes: show_info('No organoids detected! Please run auto organoid counter or run algorithm first and try again!')
1106
+ else:
1107
+ # write diameters and area to csv
1108
+ data_csv = utils.get_bbox_diameters(bboxes,
1109
+ self.viewer.layers[self.save_layer_name].properties['box_id'],
1110
+ self.viewer.layers[self.save_layer_name].scale)
1111
+ fd = QFileDialog()
1112
+ name, _ = fd.getSaveFileName(self, 'Save File', self.save_layer_name, 'CSV files (*.csv)')#, 'CSV Files (*.csv)')
1113
+ if name: utils.write_to_csv(name, data_csv)
1114
+
1115
+ def _on_save_json_click(self):
1116
+ """""" Is called whenever Save boxes button is clicked """"""
1117
+ bboxes = self.viewer.layers[self.save_layer_name].data
1118
+ #scores = #add
1119
+ if not bboxes:
1120
+ show_info('No organoids detected! Please run auto organoid counter or run algorithm first and try again!')
1121
+ return
1122
+
1123
+ # Check for multi-annotation mode
1124
+ if self.multi_annotation_mode:
1125
+
1126
+ # Get the edge colors for all bounding boxes
1127
+ edge_colors = self.cur_shapes_layer.edge_color
1128
+ labels = []
1129
+
1130
+ # Check if all bounding boxes have their edge color set (not green or blue)
1131
+ green = np.array(settings.COLOR_CLASS_1)
1132
+ blue = np.array(settings.COLOR_CLASS_2)
1133
+
1134
+ all_colored = True
1135
+ for edge_color in edge_colors:
1136
+ # Compare the colors with a tolerance using np.allclose to account for floating-point errors
1137
+ if not (np.allclose(edge_color[:3], green[:3]) or np.allclose(edge_color[:3], blue[:3])):
1138
+ all_colored = False
1139
+ break
1140
+
1141
+ if not all_colored:
1142
+ show_error('Please change the color of all bounding boxes before saving.')
1143
+ return
1144
+
1145
+ # Assign organoid label based on edge_color
1146
+ for edge_color in edge_colors:
1147
+ if np.allclose(edge_color[:3], green[:3]):
1148
+ labels.append(0) # Label for green
1149
+ elif np.allclose(edge_color[:3], blue[:3]):
1150
+ labels.append(1) # Label for blue
1151
+ else:
1152
+ raise ValueError(f""Unexpected edge color {edge_color[:3]} encountered."")
1153
+
1154
+ #elif self.single_annotation_mode:
1155
+ else:
1156
+ # Single annotation mode: all bounding boxes get a default label
1157
+ labels = [0] * len(bboxes) # Default label for single annotation mode
1158
+
1159
+ data_json = utils.get_bboxes_as_dict(bboxes,
1160
+ self.viewer.layers[self.save_layer_name].properties['box_id'],
1161
+ self.viewer.layers[self.save_layer_name].properties['scores'],
1162
+ self.viewer.layers[self.save_layer_name].scale,
1163
+ labels=labels)
1164
+
1165
+
1166
+ # write bbox coordinates to json
1167
+ fd = QFileDialog()
1168
+ name,_ = fd.getSaveFileName(self, 'Save File', self.save_layer_name, 'JSON files (*.json)')#, 'CSV Files (*.csv)')
1169
+ if name: utils.write_to_json(name, data_json)
1170
+
1171
+ def _update_added_image(self, added_items):
1172
+ """"""
1173
+ Update the selection box with new images if images have been added and update the self.original_images and self.original_contrast dicts.
1174
+ Set the latest added image to the current working image (self.image_layer_name)
1175
+ """"""
1176
+ for layer_name in added_items:
1177
+ self.image_layer_selection.addItem(layer_name)
1178
+ self.original_images[layer_name] = self.viewer.layers[layer_name].data
1179
+ self.original_contrast[layer_name] = self.viewer.layers[self.image_layer_name].contrast_limits
1180
+ self.image_layer_name = added_items[0]
1181
+
1182
+ def _update_removed_image(self, removed_layers):
1183
+ """"""
1184
+ Update the selection box by removing image names if image has been deleted and remove items from self.original_images and self.original_contrast dicts.
1185
+ """"""
1186
+ # update drop-down selection box and remove image from dict
1187
+ for removed_layer in removed_layers:
1188
+ item_id = self.image_layer_selection.findText(removed_layer)
1189
+ self.image_layer_selection.removeItem(item_id)
1190
+ del self.original_images[removed_layer]
1191
+ del self.original_contrast[removed_layer]
1192
+
1193
+ def _update_added_shapes(self, added_items):
1194
+ """"""
1195
+ Update the selection box by shape layer names if it they have been added, update current working shape layer and instantiate OrganoiDL if not already there
1196
+ """"""
1197
+ # update the drop down box displaying shape layer names for saving
1198
+ for layer_name in added_items:
1199
+ self.output_layer_selection.addItem(layer_name)
1200
+ # set the latest added shapes layer to the shapes layer that has been selected for saving and visualisation
1201
+ self.save_layer_name = added_items[0]
1202
+ self.cur_shapes_name = added_items[0]
1203
+ self.cur_shapes_layer = self.viewer.layers[self.cur_shapes_name]
1204
+ # get the bounding box and update the displayed number of organoids
1205
+ self._update_num_organoids(len(self.cur_shapes_layer.data))
1206
+ # listen for a data change in the current shapes layer
1207
+ self.organoiDL.update_bboxes_scores(self.cur_shapes_name,
1208
+ self.cur_shapes_layer.data,
1209
+ self.cur_shapes_layer.properties['scores'],
1210
+ self.cur_shapes_layer.properties['box_id']
1211
+ )
1212
+ self.cur_shapes_layer.events.data.connect(self.shapes_event_handler)
1213
+
1214
+ def _update_remove_shapes(self, removed_layers):
1215
+ """"""
1216
+ Update the selection box by removing shape layer names if it they been deleted and set
1217
+ """"""
1218
+ # update selection box by removing image names if image has been deleted
1219
+ for removed_layer in removed_layers:
1220
+ item_id = self.output_layer_selection.findText(removed_layer)
1221
+ self.output_layer_selection.removeItem(item_id)
1222
+ if removed_layer==self.cur_shapes_name:
1223
+ self._update_num_organoids(0)
1224
+ self.organoiDL.remove_shape_from_dict(self.cur_shapes_name)
1225
+
1226
+ def shapes_event_handler(self, event):
1227
+ """"""
1228
+ This function will be called every time the current shapes layer data changes
1229
+ """"""
1230
+ # make sure this stuff isn't done if data in the layer has been changed by the sliders - only by the users
1231
+ key = 'napari-organoid-counter:_rerun'
1232
+ if key in self.cur_shapes_layer.metadata:
1233
+ return
1234
+
1235
+ # get new ids, new boxes and update the number of organoids
1236
+ new_ids = self.viewer.layers[self.cur_shapes_name].properties['box_id']
1237
+ self._update_num_organoids(len(new_ids))
1238
+
1239
+ # check if duplicate ids - this happens when user adds a box, currently only available fix current_properties doesn't work
1240
+ if len(new_ids) > len(set(new_ids)):
1241
+ num_sim = len(new_ids) - len(set(new_ids))
1242
+ if num_sim > 1: print('this should not happen!!!!!!!!!!!!!!!!!')
1243
+ else:
1244
+ new_ids[-1] = self.organoiDL.next_id[self.cur_shapes_name]
1245
+ new_scores = self.viewer.layers[self.cur_shapes_name].properties['scores']
1246
+ new_scores[-1] = 1
1247
+
1248
+ # set new properties to shapes layer
1249
+ self.viewer.layers[self.cur_shapes_name].properties ={'box_id': new_ids,'scores': new_scores}
1250
+ # refresh text displayed
1251
+ self.viewer.layers[self.cur_shapes_name].refresh()
1252
+ self.viewer.layers[self.cur_shapes_name].refresh_text()
1253
+ # and update the OrganoiDL instance
1254
+ self.organoiDL.update_next_id(self.cur_shapes_name)
1255
+
1256
+ # this doesn't work!!!!
1257
+ # the problem is that the event is called once before the drawing has been completed!!!!!!
1258
+ #new_bboxes = self.cur_shapes_layer.data
1259
+ #self.organoiDL.update_bboxes_scores(new_bboxes, new_scores, new_ids)
1260
+
1261
+ def _setup_input_widget(self):
1262
+ """"""
1263
+ Sets up the GUI part which corresposnds to the input configurations
1264
+ """"""
1265
+ # setup all the individual boxes
1266
+ input_box = self._setup_input_box()
1267
+ model_box = self._setup_model_box()
1268
+ window_sizes_box = self._setup_window_sizes_box()
1269
+ downsampling_box = self._setup_downsampling_box()
1270
+ run_box = self._setup_run_box()
1271
+ annotation_mode_box = self._setup_annotation_mode_box() # Annotation mode dropdown to select single or multi-annotation
1272
+ self._setup_progress_box()
1273
+
1274
+ # and add all these to the layout
1275
+ input_widget = QGroupBox('Input configurations')
1276
+ vbox = QVBoxLayout()
1277
+ vbox.addLayout(input_box)
1278
+ vbox.addLayout(model_box)
1279
+ vbox.addLayout(window_sizes_box)
1280
+ vbox.addLayout(downsampling_box)
1281
+ vbox.addLayout(run_box)
1282
+ vbox.addLayout(annotation_mode_box) # Add the annotation dropdown
1283
+ vbox.addWidget(self.progress_box)
1284
+ input_widget.setLayout(vbox)
1285
+ return input_widget
1286
+
1287
+ def _setup_output_widget(self):
1288
+ """"""
1289
+ Sets up the GUI part which corresposnds to the parameters and outputs
1290
+ """"""
1291
+ # setup all the individual boxes
1292
+ self.organoid_number_label = QLabel('Number of organoids: '+str(self.num_organoids), self)
1293
+ self.organoid_number_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1294
+ # and add all these to the layout
1295
+ output_widget = QGroupBox('Parameters and outputs')
1296
+ vbox = QVBoxLayout()
1297
+ vbox.addLayout(self._setup_min_diameter_box())
1298
+ vbox.addLayout(self._setup_confidence_box() )
1299
+ vbox.addWidget(self.organoid_number_label)
1300
+ vbox.addLayout(self._setup_reset_box())
1301
+ vbox.addLayout(self._setup_save_box())
1302
+
1303
+ output_widget.setLayout(vbox)
1304
+ return output_widget
1305
+
1306
+ def _setup_input_box(self):
1307
+ """"""
1308
+ Sets up the GUI part where the input image is defined
1309
+ """"""
1310
+ #self.input_box = QGroupBox()
1311
+ hbox = QHBoxLayout()
1312
+ # setup label
1313
+ image_label = QLabel('Image: ', self)
1314
+ image_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1315
+ # setup drop down option for selecting which image to process
1316
+ self.image_layer_selection = QComboBox()
1317
+ if self.image_layer_names is not None:
1318
+ for name in self.image_layer_names: self.image_layer_selection.addItem(name)
1319
+ #self.image_layer_selection.setItemText(self.image_layer_name)
1320
+ self.image_layer_selection.currentIndexChanged.connect(self._on_image_selection_changed)
1321
+ # setup preprocess button to improve visualisation
1322
+ preprocess_btn = QPushButton(""Preprocess"")
1323
+ preprocess_btn.clicked.connect(self._on_preprocess_click)
1324
+ # and add all these to the layout
1325
+ hbox.addWidget(image_label, 2)
1326
+ hbox.addWidget(self.image_layer_selection, 4)
1327
+ hbox.addWidget(preprocess_btn, 4)
1328
+ return hbox
1329
+
1330
+ def _setup_model_box(self):
1331
+ """"""
1332
+ Sets up the GUI part where the model is selected from a drop down menu.
1333
+ """"""
1334
+ hbox = QHBoxLayout()
1335
+ # setup the label
1336
+ model_label = QLabel('Model: ', self)
1337
+ model_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1338
+
1339
+ # setup the browse files button
1340
+ fileOpenButton = QPushButton('Add custom model', self)
1341
+ fileOpenButton.show()
1342
+ fileOpenButton.clicked.connect(self._on_choose_model_clicked)
1343
+
1344
+ # setup drop down option for selecting which image to process
1345
+ self.model_selection = QComboBox()
1346
+ for name in settings.MODELS.keys(): self.model_selection.addItem(name)
1347
+ self.model_selection.setCurrentIndex(self.model_id)
1348
+ self.model_selection.currentIndexChanged.connect(self._on_model_selection_changed)
1349
+
1350
+ # and add all these to the layout
1351
+ hbox.addWidget(model_label, 2)
1352
+ hbox.addWidget(self.model_selection, 4)
1353
+ hbox.addWidget(fileOpenButton, 4)
1354
+ return hbox
1355
+
1356
+ def _setup_window_sizes_box(self):
1357
+ """"""
1358
+ Sets up the GUI part where the window sizes parameters are set
1359
+ """"""
1360
+ #self.window_sizes_box = QGroupBox()
1361
+ hbox = QHBoxLayout()
1362
+ info_text = (""Typically a ratio of 512 to 1 between window size and downsampling rate will give good results, (larger window \n""
1363
+ ""sizes can lead to a drop in performance). Note that small window sizes will signicantly impact the runtime of the \n""
1364
+ ""algorithm. For organoids of different sizes consider setting multiple windows sizes. Hit Enter for the change to \n""
1365
+ ""take effect."")
1366
+ # setup label
1367
+ window_sizes_label = QLabel('Window sizes: [size1, size2, ...]', self)
1368
+ window_sizes_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1369
+ window_sizes_label.setToolTip(info_text)
1370
+ # setup textbox
1371
+ self.window_sizes_textbox = QLineEdit(self)
1372
+ text = [str(window_size) for window_size in self.window_sizes]
1373
+ text = ','.join(text)
1374
+ self.window_sizes_textbox.setText(text)
1375
+ self.window_sizes_textbox.returnPressed.connect(self._on_window_sizes_changed)
1376
+ self.window_sizes_textbox.setToolTip(info_text)
1377
+ # and add all these to the layout
1378
+ hbox.addWidget(window_sizes_label)
1379
+ hbox.addWidget(self.window_sizes_textbox)
1380
+ #self.window_sizes_box.setLayout(hbox)
1381
+ #self.window_sizes_box.setStyleSheet(""border: 0px"")
1382
+ return hbox
1383
+
1384
+ def _setup_downsampling_box(self):
1385
+ """"""
1386
+ Sets up the GUI part where the downsampling parameters are set
1387
+ """"""
1388
+ #self.downsampling_box = QGroupBox()
1389
+ hbox = QHBoxLayout()
1390
+ info_text = (""To detect large organoids (and ignore smaller structures) you can increase the downsampling rate. \n""
1391
+ ""If your organoids are small and are being missed by the algorithm, consider reducing the downsampling\n""
1392
+ ""rate. The number of downsampling inputs should match the number of windows sizes. Hit Enter for the \n""
1393
+ ""change to take effect. See window sizes for more info."")
1394
+
1395
+ # setup label
1396
+ downsampling_label = QLabel('Downsampling: [ds1, ds2, ...]', self)
1397
+ downsampling_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1398
+ downsampling_label.setToolTip(info_text)
1399
+ # setup textbox
1400
+ self.downsampling_textbox = QLineEdit(self)
1401
+ text = [str(ds) for ds in self.downsampling]
1402
+ text = ','.join(text)
1403
+ self.downsampling_textbox.setText(text)
1404
+ self.downsampling_textbox.returnPressed.connect(self._on_downsampling_changed)
1405
+ self.downsampling_textbox.setToolTip(info_text)
1406
+ # and add all these to the layout
1407
+ hbox.addWidget(downsampling_label)
1408
+ hbox.addWidget(self.downsampling_textbox)
1409
+ #self.downsampling_box.setLayout(hbox)
1410
+ #self.downsampling_box.setStyleSheet(""border: 0px"")
1411
+ return hbox
1412
+
1413
+ def _setup_run_box(self):
1414
+ """"""
1415
+ Sets up the GUI part where the user hits the run button
1416
+ """"""
1417
+ hbox = QHBoxLayout()
1418
+ hbox.addStretch(1)
1419
+ run_btn = QPushButton(""Run Organoid Counter"")
1420
+ run_btn.clicked.connect(self._on_run_click)
1421
+ run_btn.setStyleSheet(""border: 0px"")
1422
+ hbox.addWidget(run_btn)
1423
+ hbox.addStretch(1)
1424
+ return hbox
1425
+
1426
+ def _setup_annotation_mode_box(self):
1427
+ """"""
1428
+ Sets up the GUI part where the annotation mode is selected.
1429
+ """"""
1430
+ hbox = QHBoxLayout()
1431
+
1432
+ # Label
1433
+ annotation_mode_label = QLabel(""Annotation Mode:"", self)
1434
+ hbox.addWidget(annotation_mode_label)
1435
+
1436
+ # Dropdown
1437
+ self.annotation_mode_dropdown = QComboBox()
1438
+ self.annotation_mode_dropdown.addItems([""Single Annotation"", ""Multi Annotation""])
1439
+ self.annotation_mode_dropdown.currentIndexChanged.connect(self.on_annotation_mode_changed)
1440
+ hbox.addWidget(self.annotation_mode_dropdown)
1441
+
1442
+ return hbox
1443
+
1444
+ def _setup_progress_box(self):
1445
+ """"""
1446
+ Sets up the GUI part which appears when the model is being downloaded.
1447
+ This should only happen once for each model whihc is then stored in cache.
1448
+ """"""
1449
+ self.progress_box = QGroupBox()
1450
+ hbox = QHBoxLayout()
1451
+ download_label = QLabel('Downloading model progress: ', self)
1452
+ download_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1453
+ self.progress_bar = QProgressBar(self) # creating progress bar
1454
+ hbox.addWidget(download_label)
1455
+ hbox.addWidget(self.progress_bar)
1456
+ self.progress_box.setLayout(hbox)
1457
+ self.progress_box.hide()
1458
+
1459
+ def _setup_min_diameter_box(self):
1460
+ """"""
1461
+ Sets up the GUI part where the minimum diameter parameter is displayed
1462
+ """"""
1463
+ hbox = QHBoxLayout()
1464
+ # setup the min diameter slider
1465
+ self.min_diameter_slider = QSlider(Qt.Horizontal)
1466
+ self.min_diameter_slider.setMinimum(10)
1467
+ self.min_diameter_slider.setMaximum(100)
1468
+ self.min_diameter_slider.setSingleStep(10)
1469
+ self.min_diameter_slider.setValue(self.min_diameter)
1470
+ self.min_diameter_slider.valueChanged.connect(self._on_diameter_slider_changed)
1471
+ # setup the label
1472
+ min_diameter_label = QLabel('Minimum Diameter [um]: ', self)
1473
+ min_diameter_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1474
+ # setup text box
1475
+ self.min_diameter_textbox = QLineEdit(self)
1476
+ self.min_diameter_textbox.setText(str(self.min_diameter))
1477
+ self.min_diameter_textbox.returnPressed.connect(self._on_diameter_textbox_changed)
1478
+ # and add all these to the layout
1479
+ hbox.addWidget(min_diameter_label, 4)
1480
+ hbox.addWidget(self.min_diameter_textbox, 1)
1481
+ hbox.addWidget(self.min_diameter_slider, 5)
1482
+ return hbox
1483
+
1484
+ def _setup_confidence_box(self):
1485
+ """"""
1486
+ Sets up the GUI part where the confidence parameter is displayed
1487
+ """"""
1488
+ hbox = QHBoxLayout()
1489
+ # setup confidence slider
1490
+ self.confidence_slider = QSlider(Qt.Horizontal)
1491
+ self.confidence_slider.setMinimum(5)
1492
+ self.confidence_slider.setMaximum(100)
1493
+ self.confidence_slider.setSingleStep(5)
1494
+ vis_confidence = int(self.confidence*100)
1495
+ self.confidence_slider.setValue(vis_confidence)
1496
+ self.confidence_slider.valueChanged.connect(self._on_confidence_slider_changed)
1497
+ # setup label
1498
+ confidence_label = QLabel('Model confidence: ', self)
1499
+ confidence_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1500
+ # setup text box
1501
+ self.confidence_textbox = QLineEdit(self)
1502
+ self.confidence_textbox.setText(str(self.confidence))
1503
+ self.confidence_textbox.returnPressed.connect(self._on_confidence_textbox_changed)
1504
+ # and add all these to the layout
1505
+ hbox.addWidget(confidence_label, 3)
1506
+ hbox.addWidget(self.confidence_textbox, 1)
1507
+ hbox.addWidget(self.confidence_slider, 6)
1508
+ return hbox
1509
+
1510
+ def _setup_reset_box(self):
1511
+ """"""
1512
+ Sets up the GUI part where screenshot and reset are available to the user
1513
+ """"""
1514
+ #self.reset_box = QGroupBox()
1515
+ hbox = QHBoxLayout()
1516
+ # setup button for resetting parameters
1517
+ self.reset_btn = QPushButton(""Reset Configs"")
1518
+ self.reset_btn.clicked.connect(self._on_reset_click)
1519
+ # setup button for taking screenshot of current viewer
1520
+ self.screenshot_btn = QPushButton(""Take screenshot"")
1521
+ self.screenshot_btn.clicked.connect(self._on_screenshot_click)
1522
+ # and add all these to the layout
1523
+ hbox.addStretch(1)
1524
+ hbox.addWidget(self.screenshot_btn)
1525
+ hbox.addSpacing(15)
1526
+ hbox.addWidget(self.reset_btn)
1527
+ hbox.addStretch(1)
1528
+ #self.reset_box.setLayout(hbox)
1529
+ #self.reset_box.setStyleSheet(""border: 0px"")
1530
+ return hbox
1531
+
1532
+ def _setup_save_box(self):
1533
+ """"""
1534
+ Sets up the GUI part where shapes layer is saved
1535
+ """"""
1536
+ #self.save_box = QGroupBox()
1537
+ hbox = QHBoxLayout()
1538
+ # setup button for saving features
1539
+ self.save_csv_btn = QPushButton(""Save features"")
1540
+ self.save_csv_btn.clicked.connect(self._on_save_csv_click)
1541
+ # setup button for saving boxes
1542
+ self.save_json_btn = QPushButton(""Save boxes"")
1543
+ self.save_json_btn.clicked.connect(self._on_save_json_click)
1544
+ # setup label
1545
+ self.save_label = QLabel('Save: ', self)
1546
+ self.save_label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
1547
+ # setup drop down option for selecting which shapes layer to save
1548
+ self.output_layer_selection = QComboBox()
1549
+ if self.shape_layer_names is not None:
1550
+ for name in self.shape_layer_names: self.output_layer_selection.addItem(name)
1551
+ self.output_layer_selection.currentIndexChanged.connect(self._on_shapes_selection_changed)
1552
+ # and add all these to the layout
1553
+ hbox.addWidget(self.save_label)
1554
+ hbox.addSpacing(5)
1555
+ hbox.addWidget(self.output_layer_selection)
1556
+ hbox.addWidget(self.save_csv_btn)
1557
+ hbox.addWidget(self.save_json_btn)
1558
+ #self.save_box.setLayout(hbox)
1559
+ #self.save_box.setStyleSheet(""border: 0px"")
1560
+ return hbox
1561
+
1562
+ def _get_layer_names(self, layer_type: layers.Layer = layers.Image) -> List[str]:
1563
+ """"""
1564
+ Get a list of layer names of a given layer type.
1565
+ """"""
1566
+ layer_names = [layer.name for layer in self.viewer.layers if type(layer) == layer_type]
1567
+ if layer_names: return [] + layer_names
1568
+ else: return []
1569
+
1570
+
1571
+ class ConfirmUpload(QDialog):
1572
+ '''
1573
+ The QDialog box that appears when the user selects to run organoid counter
1574
+ without having the selected model locally
1575
+ Parameters
1576
+ ----------
1577
+ parent: QWidget
1578
+ The parent widget, in this case an instance of OrganoidCounterWidget
1579
+
1580
+ '''
1581
+ def __init__(self, parent: QWidget):
1582
+ super().__init__(parent)
1583
+
1584
+ self.setWindowTitle(""Confirm Download"")
1585
+ # setup buttons and text to be displayed
1586
+ ok_btn = QPushButton(""OK"")
1587
+ cancel_btn = QPushButton(""Cancel"")
1588
+ text = (""Model not found locally. Downloading default model to \n""
1589
+ +str(settings.MODELS_DIR)+""\n""
1590
+ ""This will only happen once. Click ok to continue or \n""
1591
+ ""cancel if you do not agree. You won't be able to run\n""
1592
+ ""the organoid counter if you click cancel."")
1593
+ # add all to layout
1594
+ layout = QVBoxLayout()
1595
+ layout.addWidget(QLabel(text))
1596
+ hbox = QHBoxLayout()
1597
+ hbox.addWidget(ok_btn)
1598
+ hbox.addWidget(cancel_btn)
1599
+ layout.addLayout(hbox)
1600
+ self.setLayout(layout)
1601
+ # connect ok and cancel buttons with accept and reject signals
1602
+ ok_btn.clicked.connect(self.accept)
1603
+ cancel_btn.clicked.connect(self.reject)","Python"
1604
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_tests/__init__.py",".py","0","0","","Python"
1605
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_tests/test_reader.py",".py","2162","67","import json
1606
+ import numpy as np
1607
+ from napari_organoid_counter import get_reader
1608
+
1609
+
1610
+ # tmp_path is a pytest fixture
1611
+ def test_reader(tmp_path):
1612
+ """"""Testing the reader part of the plugin""""""
1613
+
1614
+ # write some fake data using your supported file format
1615
+ my_test_file = str(tmp_path / 'myfile.json')
1616
+ bboxes = [np.array([[2000,2000], [2000,2500], [2500,2500], [2500,2000]]),
1617
+ np.array([[3000,3000], [3000,3500], [3500,3500], [3500,3000]])]
1618
+
1619
+ original_data = {
1620
+ '1':{
1621
+ 'box_id': '1',
1622
+ 'x1': 2000,
1623
+ 'x2': 2500,
1624
+ 'y1': 2000,
1625
+ 'y2': 2500,
1626
+ 'confidence': 0.8,
1627
+ 'scale_x': 0.9,
1628
+ 'scale_y': 0.9,
1629
+ },
1630
+ '2':{
1631
+ 'box_id': '2',
1632
+ 'x1': 3000,
1633
+ 'x2': 3500,
1634
+ 'y1': 3000,
1635
+ 'y2': 3500,
1636
+ 'confidence': 0.85,
1637
+ 'scale_x': 0.9,
1638
+ 'scale_y': 0.9,
1639
+ }
1640
+ }
1641
+ with open(my_test_file, 'w') as outfile:
1642
+ outfile.write(json.dumps(original_data))
1643
+
1644
+ # try to read it back in
1645
+ reader = get_reader(my_test_file) #reader should return [(bboxes, layer_attributes, 'shapes')]
1646
+ assert callable(reader)
1647
+
1648
+ # make sure we're delivering the right format
1649
+ layer_data_list = reader(my_test_file)
1650
+ assert isinstance(layer_data_list, list) and len(layer_data_list) > 0
1651
+ layer_data_tuple = layer_data_list[0]
1652
+ assert isinstance(layer_data_tuple, tuple) and len(layer_data_tuple)==3
1653
+
1654
+ # make sure it's the same as it started
1655
+ data = layer_data_tuple[0]
1656
+ for idx, bbox in enumerate(bboxes):
1657
+ assert (data[idx]==bbox).all()
1658
+
1659
+ # and that correct attributes and layer type is set
1660
+ attributes = layer_data_tuple[1]
1661
+ assert attributes['name']=='Labels-myfile'
1662
+ assert attributes['scale']==(original_data['2']['scale_x'], original_data['2']['scale_y'])
1663
+ assert attributes['properties']['scores'][-1]==original_data['2']['confidence']
1664
+
1665
+ layer_type = layer_data_tuple[2]
1666
+ assert isinstance(layer_type, str) and layer_type=='shapes'
1667
+
1668
+
1669
+ def test_get_reader_pass():
1670
+ reader = get_reader('fake.file')
1671
+ assert reader is None","Python"
1672
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_tests/test_utils.py",".py","7","1","# TO DO","Python"
1673
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_tests/test_widget.py",".py","2964","77","from napari_organoid_counter import OrganoidCounterWidget
1674
+ import numpy as np
1675
+ from skimage import draw
1676
+ from napari import layers
1677
+
1678
+ # make_napari_viewer is a pytest fixture that returns a napari viewer object
1679
+ # capsys is a pytest fixture that captures stdout and stderr output streams
1680
+ def test_organoid_counter_widget(make_napari_viewer, capsys):
1681
+ # make viewer and add an image layer using our fixture
1682
+ viewer = make_napari_viewer()
1683
+ test_img = np.zeros((1000,1000))
1684
+ x1, y1 = draw.disk((500,500), 400)
1685
+ x2, y2 = draw.disk((400,400), 40)
1686
+ x3, y3 = draw.disk((600,600), 10)
1687
+ x4, y4 = draw.disk((650,400), 100)
1688
+ test_img[x1,y1] = 3000
1689
+ test_img[x2,y2] = 1500
1690
+ test_img[x3,y3] = 2000
1691
+ test_img[x4,y4] = 1000
1692
+ viewer.add_image(test_img, name='Test')
1693
+
1694
+ # create our widget, passing in the viewer
1695
+ my_widget = OrganoidCounterWidget(viewer,
1696
+ window_sizes=[500],
1697
+ downsampling=[2],
1698
+ window_overlap=1)
1699
+
1700
+ # call preprocessing - remove duplicate here?
1701
+ my_widget._preprocess()
1702
+ img = my_widget.viewer.layers['Test'].data
1703
+ assert np.max(img) <= 255.
1704
+ assert np.min(img) >= 0.
1705
+
1706
+ my_widget._on_preprocess_click()
1707
+ img = my_widget.viewer.layers['Test'].data
1708
+ assert np.max(img) <= 255.
1709
+ assert np.min(img) >= 0.
1710
+
1711
+ # test that organoid counting algorithm has run and new layer with res has been added to viewer
1712
+ my_widget.organoiDL.download_model(my_widget.model_name)
1713
+ my_widget._on_run_click()
1714
+ layer_names = [layer.name for layer in my_widget.viewer.layers]
1715
+ assert 'Labels-Test' in layer_names
1716
+
1717
+ # test that class attributes are updated when user changes values from GUI
1718
+ my_widget._on_diameter_slider_changed()
1719
+ assert my_widget.min_diameter == my_widget.min_diameter_slider.value()
1720
+
1721
+ my_widget._on_image_selection_changed()
1722
+ assert my_widget.image_layer_name == my_widget.image_layer_selection.currentText()
1723
+
1724
+ # test that number of organoids is updated after manual corrections
1725
+
1726
+ # test that reset button resets all parameters to default settings
1727
+ my_widget._on_reset_click()
1728
+ assert my_widget.min_diameter==30
1729
+ assert my_widget.min_diameter_slider.value()==30
1730
+ assert my_widget.confidence==0.8
1731
+ assert my_widget.confidence_slider.value()==80
1732
+
1733
+ #my_widget._on_screenshot_click()
1734
+ #'''TO DO'''
1735
+
1736
+ #my_widget._on_save_csv_click()
1737
+ #'''TO DO'''
1738
+
1739
+ #my_widget._on_save_json_click()
1740
+ #'''TO DO'''
1741
+
1742
+ my_widget._get_layer_names()
1743
+ layer_names = [layer.name for layer in my_widget.viewer.layers if type(layer)==layers.Image]
1744
+ assert len(layer_names) == 1
1745
+ assert layer_names[0] == 'Test'
1746
+ my_widget._get_layer_names(layer_type=layers.Shapes)
1747
+ layer_names = [layer.name for layer in my_widget.viewer.layers if type(layer)==layers.Shapes]
1748
+ assert len(layer_names) == 1
1749
+ assert layer_names[0] == 'Labels-Test'","Python"
1750
+ "Organoid","HelmholtzAI-Consultants-Munich/napari-organoid-counter","napari_organoid_counter/_tests/test_orgacount.py",".py","7","1","# TO DO","Python"