senoquant 1.0.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- senoquant/__init__.py +6 -0
- senoquant/_reader.py +7 -0
- senoquant/_widget.py +33 -0
- senoquant/napari.yaml +83 -0
- senoquant/reader/__init__.py +5 -0
- senoquant/reader/core.py +369 -0
- senoquant/tabs/__init__.py +15 -0
- senoquant/tabs/batch/__init__.py +10 -0
- senoquant/tabs/batch/backend.py +641 -0
- senoquant/tabs/batch/config.py +270 -0
- senoquant/tabs/batch/frontend.py +1283 -0
- senoquant/tabs/batch/io.py +326 -0
- senoquant/tabs/batch/layers.py +86 -0
- senoquant/tabs/quantification/__init__.py +1 -0
- senoquant/tabs/quantification/backend.py +228 -0
- senoquant/tabs/quantification/features/__init__.py +80 -0
- senoquant/tabs/quantification/features/base.py +142 -0
- senoquant/tabs/quantification/features/marker/__init__.py +5 -0
- senoquant/tabs/quantification/features/marker/config.py +69 -0
- senoquant/tabs/quantification/features/marker/dialog.py +437 -0
- senoquant/tabs/quantification/features/marker/export.py +879 -0
- senoquant/tabs/quantification/features/marker/feature.py +119 -0
- senoquant/tabs/quantification/features/marker/morphology.py +285 -0
- senoquant/tabs/quantification/features/marker/rows.py +654 -0
- senoquant/tabs/quantification/features/marker/thresholding.py +46 -0
- senoquant/tabs/quantification/features/roi.py +346 -0
- senoquant/tabs/quantification/features/spots/__init__.py +5 -0
- senoquant/tabs/quantification/features/spots/config.py +62 -0
- senoquant/tabs/quantification/features/spots/dialog.py +477 -0
- senoquant/tabs/quantification/features/spots/export.py +1292 -0
- senoquant/tabs/quantification/features/spots/feature.py +112 -0
- senoquant/tabs/quantification/features/spots/morphology.py +279 -0
- senoquant/tabs/quantification/features/spots/rows.py +241 -0
- senoquant/tabs/quantification/frontend.py +815 -0
- senoquant/tabs/segmentation/__init__.py +1 -0
- senoquant/tabs/segmentation/backend.py +131 -0
- senoquant/tabs/segmentation/frontend.py +1009 -0
- senoquant/tabs/segmentation/models/__init__.py +5 -0
- senoquant/tabs/segmentation/models/base.py +146 -0
- senoquant/tabs/segmentation/models/cpsam/details.json +65 -0
- senoquant/tabs/segmentation/models/cpsam/model.py +150 -0
- senoquant/tabs/segmentation/models/default_2d/details.json +69 -0
- senoquant/tabs/segmentation/models/default_2d/model.py +664 -0
- senoquant/tabs/segmentation/models/default_3d/details.json +69 -0
- senoquant/tabs/segmentation/models/default_3d/model.py +682 -0
- senoquant/tabs/segmentation/models/hf.py +71 -0
- senoquant/tabs/segmentation/models/nuclear_dilation/__init__.py +1 -0
- senoquant/tabs/segmentation/models/nuclear_dilation/details.json +26 -0
- senoquant/tabs/segmentation/models/nuclear_dilation/model.py +96 -0
- senoquant/tabs/segmentation/models/perinuclear_rings/__init__.py +1 -0
- senoquant/tabs/segmentation/models/perinuclear_rings/details.json +34 -0
- senoquant/tabs/segmentation/models/perinuclear_rings/model.py +132 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/__init__.py +2 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/__init__.py +3 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/__init__.py +6 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/generate.py +470 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/prepare.py +273 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/rawdata.py +112 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/transform.py +384 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/__init__.py +0 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/blocks.py +184 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/losses.py +79 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/nets.py +165 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/predict.py +467 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/probability.py +67 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/train.py +148 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/io/__init__.py +163 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/__init__.py +52 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/base_model.py +329 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_isotropic.py +160 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_projection.py +178 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_standard.py +446 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_upsampling.py +54 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/config.py +254 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/pretrained.py +119 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/scripts/__init__.py +0 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/scripts/care_predict.py +180 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/__init__.py +5 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/plot_utils.py +159 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/six.py +18 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/tf.py +644 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/utils.py +272 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/version.py +1 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/docs/source/conf.py +368 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/setup.py +68 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_datagen.py +169 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_models.py +462 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_utils.py +166 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tools/create_zip_contents.py +34 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/__init__.py +30 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/big.py +624 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/bioimageio_utils.py +494 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/data/__init__.py +39 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/__init__.py +10 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/geom2d.py +215 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/geom3d.py +349 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/matching.py +483 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/__init__.py +28 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/base.py +1217 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/model2d.py +594 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/model3d.py +696 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/nms.py +384 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/__init__.py +2 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/plot.py +74 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/render.py +298 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/rays3d.py +373 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/sample_patches.py +65 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/__init__.py +0 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/predict2d.py +90 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/predict3d.py +93 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/utils.py +408 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/version.py +1 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/__init__.py +45 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/__init__.py +17 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/cli.py +55 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/core.py +285 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/__init__.py +15 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/cli.py +36 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/divisibility.py +193 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/probe.py +100 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/receptive_field.py +182 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/rf_cli.py +48 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/valid_sizes.py +278 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/post/__init__.py +8 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/post/core.py +157 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/pre/__init__.py +17 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/pre/core.py +226 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/predict/__init__.py +5 -0
- senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/predict/core.py +401 -0
- senoquant/tabs/settings/__init__.py +1 -0
- senoquant/tabs/settings/backend.py +29 -0
- senoquant/tabs/settings/frontend.py +19 -0
- senoquant/tabs/spots/__init__.py +1 -0
- senoquant/tabs/spots/backend.py +139 -0
- senoquant/tabs/spots/frontend.py +800 -0
- senoquant/tabs/spots/models/__init__.py +5 -0
- senoquant/tabs/spots/models/base.py +94 -0
- senoquant/tabs/spots/models/rmp/details.json +61 -0
- senoquant/tabs/spots/models/rmp/model.py +499 -0
- senoquant/tabs/spots/models/udwt/details.json +103 -0
- senoquant/tabs/spots/models/udwt/model.py +482 -0
- senoquant/utils.py +25 -0
- senoquant-1.0.0b1.dist-info/METADATA +193 -0
- senoquant-1.0.0b1.dist-info/RECORD +148 -0
- senoquant-1.0.0b1.dist-info/WHEEL +5 -0
- senoquant-1.0.0b1.dist-info/entry_points.txt +2 -0
- senoquant-1.0.0b1.dist-info/licenses/LICENSE +28 -0
- senoquant-1.0.0b1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from numba import jit
|
|
4
|
+
from tqdm import tqdm
|
|
5
|
+
from scipy.optimize import linear_sum_assignment
|
|
6
|
+
from skimage.measure import regionprops
|
|
7
|
+
from collections import namedtuple
|
|
8
|
+
from csbdeep.utils import _raise
|
|
9
|
+
|
|
10
|
+
matching_criteria = dict()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def label_are_sequential(y):
|
|
14
|
+
""" returns true if y has only sequential labels from 1... """
|
|
15
|
+
labels = np.unique(y)
|
|
16
|
+
return (set(labels)-{0}) == set(range(1,1+labels.max()))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_array_of_integers(y):
|
|
20
|
+
return isinstance(y,np.ndarray) and np.issubdtype(y.dtype, np.integer)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _check_label_array(y, name=None, check_sequential=False):
|
|
24
|
+
err = ValueError("{label} must be an array of {integers}.".format(
|
|
25
|
+
label = 'labels' if name is None else name,
|
|
26
|
+
integers = ('sequential ' if check_sequential else '') + 'non-negative integers',
|
|
27
|
+
))
|
|
28
|
+
is_array_of_integers(y) or _raise(err)
|
|
29
|
+
if len(y) == 0:
|
|
30
|
+
return True
|
|
31
|
+
if check_sequential:
|
|
32
|
+
label_are_sequential(y) or _raise(err)
|
|
33
|
+
else:
|
|
34
|
+
y.min() >= 0 or _raise(err)
|
|
35
|
+
return True
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def label_overlap(x, y, check=True):
|
|
39
|
+
if check:
|
|
40
|
+
_check_label_array(x,'x',True)
|
|
41
|
+
_check_label_array(y,'y',True)
|
|
42
|
+
x.shape == y.shape or _raise(ValueError("x and y must have the same shape"))
|
|
43
|
+
return _label_overlap(x, y)
|
|
44
|
+
|
|
45
|
+
@jit(nopython=True)
|
|
46
|
+
def _label_overlap(x, y):
|
|
47
|
+
x = x.ravel()
|
|
48
|
+
y = y.ravel()
|
|
49
|
+
overlap = np.zeros((1+x.max(),1+y.max()), dtype=np.uint)
|
|
50
|
+
for i in range(len(x)):
|
|
51
|
+
overlap[x[i],y[i]] += 1
|
|
52
|
+
return overlap
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _safe_divide(x,y, eps=1e-10):
|
|
56
|
+
"""computes a safe divide which returns 0 if y is zero"""
|
|
57
|
+
if np.isscalar(x) and np.isscalar(y):
|
|
58
|
+
return x/y if np.abs(y)>eps else 0.0
|
|
59
|
+
else:
|
|
60
|
+
out = np.zeros(np.broadcast(x,y).shape, np.float32)
|
|
61
|
+
np.divide(x,y, out=out, where=np.abs(y)>eps)
|
|
62
|
+
return out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def intersection_over_union(overlap):
|
|
66
|
+
_check_label_array(overlap,'overlap')
|
|
67
|
+
if np.sum(overlap) == 0:
|
|
68
|
+
return overlap
|
|
69
|
+
n_pixels_pred = np.sum(overlap, axis=0, keepdims=True)
|
|
70
|
+
n_pixels_true = np.sum(overlap, axis=1, keepdims=True)
|
|
71
|
+
return _safe_divide(overlap, (n_pixels_pred + n_pixels_true - overlap))
|
|
72
|
+
|
|
73
|
+
matching_criteria['iou'] = intersection_over_union
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def intersection_over_true(overlap):
|
|
77
|
+
_check_label_array(overlap,'overlap')
|
|
78
|
+
if np.sum(overlap) == 0:
|
|
79
|
+
return overlap
|
|
80
|
+
n_pixels_true = np.sum(overlap, axis=1, keepdims=True)
|
|
81
|
+
return _safe_divide(overlap, n_pixels_true)
|
|
82
|
+
|
|
83
|
+
matching_criteria['iot'] = intersection_over_true
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def intersection_over_pred(overlap):
|
|
87
|
+
_check_label_array(overlap,'overlap')
|
|
88
|
+
if np.sum(overlap) == 0:
|
|
89
|
+
return overlap
|
|
90
|
+
n_pixels_pred = np.sum(overlap, axis=0, keepdims=True)
|
|
91
|
+
return _safe_divide(overlap, n_pixels_pred)
|
|
92
|
+
|
|
93
|
+
matching_criteria['iop'] = intersection_over_pred
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def precision(tp,fp,fn):
|
|
97
|
+
return tp/(tp+fp) if tp > 0 else 0
|
|
98
|
+
def recall(tp,fp,fn):
|
|
99
|
+
return tp/(tp+fn) if tp > 0 else 0
|
|
100
|
+
def accuracy(tp,fp,fn):
|
|
101
|
+
# also known as "average precision" (?)
|
|
102
|
+
# -> https://www.kaggle.com/c/data-science-bowl-2018#evaluation
|
|
103
|
+
return tp/(tp+fp+fn) if tp > 0 else 0
|
|
104
|
+
def f1(tp,fp,fn):
|
|
105
|
+
# also known as "dice coefficient"
|
|
106
|
+
return (2*tp)/(2*tp+fp+fn) if tp > 0 else 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def matching(y_true, y_pred, thresh=0.5, criterion='iou', report_matches=False):
|
|
110
|
+
"""Calculate detection/instance segmentation metrics between ground truth and predicted label images.
|
|
111
|
+
|
|
112
|
+
Currently, the following metrics are implemented:
|
|
113
|
+
|
|
114
|
+
'fp', 'tp', 'fn', 'precision', 'recall', 'accuracy', 'f1', 'criterion', 'thresh', 'n_true', 'n_pred', 'mean_true_score', 'mean_matched_score', 'panoptic_quality'
|
|
115
|
+
|
|
116
|
+
Corresponding objects of y_true and y_pred are counted as true positives (tp), false positives (fp), and false negatives (fn)
|
|
117
|
+
whether their intersection over union (IoU) >= thresh (for criterion='iou', which can be changed)
|
|
118
|
+
|
|
119
|
+
* mean_matched_score is the mean IoUs of matched true positives
|
|
120
|
+
|
|
121
|
+
* mean_true_score is the mean IoUs of matched true positives but normalized by the total number of GT objects
|
|
122
|
+
|
|
123
|
+
* panoptic_quality defined as in Eq. 1 of Kirillov et al. "Panoptic Segmentation", CVPR 2019
|
|
124
|
+
|
|
125
|
+
Parameters
|
|
126
|
+
----------
|
|
127
|
+
y_true: ndarray
|
|
128
|
+
ground truth label image (integer valued)
|
|
129
|
+
y_pred: ndarray
|
|
130
|
+
predicted label image (integer valued)
|
|
131
|
+
thresh: float
|
|
132
|
+
threshold for matching criterion (default 0.5)
|
|
133
|
+
criterion: string
|
|
134
|
+
matching criterion (default IoU)
|
|
135
|
+
report_matches: bool
|
|
136
|
+
if True, additionally calculate matched_pairs and matched_scores (note, that this returns even gt-pred pairs whose scores are below 'thresh')
|
|
137
|
+
|
|
138
|
+
Returns
|
|
139
|
+
-------
|
|
140
|
+
Matching object with different metrics as attributes
|
|
141
|
+
|
|
142
|
+
Examples
|
|
143
|
+
--------
|
|
144
|
+
>>> y_true = np.zeros((100,100), np.uint16)
|
|
145
|
+
>>> y_true[10:20,10:20] = 1
|
|
146
|
+
>>> y_pred = np.roll(y_true,5,axis = 0)
|
|
147
|
+
|
|
148
|
+
>>> stats = matching(y_true, y_pred)
|
|
149
|
+
>>> print(stats)
|
|
150
|
+
Matching(criterion='iou', thresh=0.5, fp=1, tp=0, fn=1, precision=0, recall=0, accuracy=0, f1=0, n_true=1, n_pred=1, mean_true_score=0.0, mean_matched_score=0.0, panoptic_quality=0.0)
|
|
151
|
+
|
|
152
|
+
"""
|
|
153
|
+
_check_label_array(y_true,'y_true')
|
|
154
|
+
_check_label_array(y_pred,'y_pred')
|
|
155
|
+
y_true.shape == y_pred.shape or _raise(ValueError("y_true ({y_true.shape}) and y_pred ({y_pred.shape}) have different shapes".format(y_true=y_true, y_pred=y_pred)))
|
|
156
|
+
criterion in matching_criteria or _raise(ValueError("Matching criterion '%s' not supported." % criterion))
|
|
157
|
+
if thresh is None: thresh = 0
|
|
158
|
+
thresh = float(thresh) if np.isscalar(thresh) else map(float,thresh)
|
|
159
|
+
|
|
160
|
+
y_true, _, map_rev_true = relabel_sequential(y_true)
|
|
161
|
+
y_pred, _, map_rev_pred = relabel_sequential(y_pred)
|
|
162
|
+
|
|
163
|
+
overlap = label_overlap(y_true, y_pred, check=False)
|
|
164
|
+
scores = matching_criteria[criterion](overlap)
|
|
165
|
+
assert 0 <= np.min(scores) <= np.max(scores) <= 1
|
|
166
|
+
|
|
167
|
+
# ignoring background
|
|
168
|
+
scores = scores[1:,1:]
|
|
169
|
+
n_true, n_pred = scores.shape
|
|
170
|
+
n_matched = min(n_true, n_pred)
|
|
171
|
+
|
|
172
|
+
def _single(thr):
|
|
173
|
+
# not_trivial = n_matched > 0 and np.any(scores >= thr)
|
|
174
|
+
not_trivial = n_matched > 0
|
|
175
|
+
if not_trivial:
|
|
176
|
+
# compute optimal matching with scores as tie-breaker
|
|
177
|
+
costs = -(scores >= thr).astype(float) - scores / (2*n_matched)
|
|
178
|
+
true_ind, pred_ind = linear_sum_assignment(costs)
|
|
179
|
+
assert n_matched == len(true_ind) == len(pred_ind)
|
|
180
|
+
match_ok = scores[true_ind,pred_ind] >= thr
|
|
181
|
+
tp = np.count_nonzero(match_ok)
|
|
182
|
+
else:
|
|
183
|
+
tp = 0
|
|
184
|
+
fp = n_pred - tp
|
|
185
|
+
fn = n_true - tp
|
|
186
|
+
# assert tp+fp == n_pred
|
|
187
|
+
# assert tp+fn == n_true
|
|
188
|
+
|
|
189
|
+
# the score sum over all matched objects (tp)
|
|
190
|
+
sum_matched_score = np.sum(scores[true_ind,pred_ind][match_ok]) if not_trivial else 0.0
|
|
191
|
+
|
|
192
|
+
# the score average over all matched objects (tp)
|
|
193
|
+
mean_matched_score = _safe_divide(sum_matched_score, tp)
|
|
194
|
+
# the score average over all gt/true objects
|
|
195
|
+
mean_true_score = _safe_divide(sum_matched_score, n_true)
|
|
196
|
+
panoptic_quality = _safe_divide(sum_matched_score, tp+fp/2+fn/2)
|
|
197
|
+
|
|
198
|
+
stats_dict = dict (
|
|
199
|
+
criterion = criterion,
|
|
200
|
+
thresh = thr,
|
|
201
|
+
fp = fp,
|
|
202
|
+
tp = tp,
|
|
203
|
+
fn = fn,
|
|
204
|
+
precision = precision(tp,fp,fn),
|
|
205
|
+
recall = recall(tp,fp,fn),
|
|
206
|
+
accuracy = accuracy(tp,fp,fn),
|
|
207
|
+
f1 = f1(tp,fp,fn),
|
|
208
|
+
n_true = n_true,
|
|
209
|
+
n_pred = n_pred,
|
|
210
|
+
mean_true_score = mean_true_score,
|
|
211
|
+
mean_matched_score = mean_matched_score,
|
|
212
|
+
panoptic_quality = panoptic_quality,
|
|
213
|
+
)
|
|
214
|
+
if bool(report_matches):
|
|
215
|
+
if not_trivial:
|
|
216
|
+
stats_dict.update (
|
|
217
|
+
# int() to be json serializable
|
|
218
|
+
matched_pairs = tuple((int(map_rev_true[i]),int(map_rev_pred[j])) for i,j in zip(1+true_ind,1+pred_ind)),
|
|
219
|
+
matched_scores = tuple(scores[true_ind,pred_ind]),
|
|
220
|
+
matched_tps = tuple(map(int,np.flatnonzero(match_ok))),
|
|
221
|
+
)
|
|
222
|
+
else:
|
|
223
|
+
stats_dict.update (
|
|
224
|
+
matched_pairs = (),
|
|
225
|
+
matched_scores = (),
|
|
226
|
+
matched_tps = (),
|
|
227
|
+
)
|
|
228
|
+
return namedtuple('Matching',stats_dict.keys())(*stats_dict.values())
|
|
229
|
+
|
|
230
|
+
return _single(thresh) if np.isscalar(thresh) else tuple(map(_single,thresh))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def matching_dataset(y_true, y_pred, thresh=0.5, criterion='iou', by_image=False, show_progress=True, parallel=False):
|
|
235
|
+
"""matching metrics for list of images, see `stardist.matching.matching`
|
|
236
|
+
"""
|
|
237
|
+
len(y_true) == len(y_pred) or _raise(ValueError("y_true and y_pred must have the same length."))
|
|
238
|
+
return matching_dataset_lazy (
|
|
239
|
+
tuple(zip(y_true,y_pred)), thresh=thresh, criterion=criterion, by_image=by_image, show_progress=show_progress, parallel=parallel,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def matching_dataset_lazy(y_gen, thresh=0.5, criterion='iou', by_image=False, show_progress=True, parallel=False):
|
|
245
|
+
|
|
246
|
+
expected_keys = set(('fp', 'tp', 'fn', 'precision', 'recall', 'accuracy', 'f1', 'criterion', 'thresh', 'n_true', 'n_pred', 'mean_true_score', 'mean_matched_score', 'panoptic_quality'))
|
|
247
|
+
|
|
248
|
+
single_thresh = False
|
|
249
|
+
if np.isscalar(thresh):
|
|
250
|
+
single_thresh = True
|
|
251
|
+
thresh = (thresh,)
|
|
252
|
+
|
|
253
|
+
tqdm_kwargs = {}
|
|
254
|
+
tqdm_kwargs['disable'] = not bool(show_progress)
|
|
255
|
+
if int(show_progress) > 1:
|
|
256
|
+
tqdm_kwargs['total'] = int(show_progress)
|
|
257
|
+
|
|
258
|
+
# compute matching stats for every pair of label images
|
|
259
|
+
if parallel:
|
|
260
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
261
|
+
fn = lambda pair: matching(*pair, thresh=thresh, criterion=criterion, report_matches=False)
|
|
262
|
+
with ThreadPoolExecutor() as pool:
|
|
263
|
+
stats_all = tuple(pool.map(fn, tqdm(y_gen,**tqdm_kwargs)))
|
|
264
|
+
else:
|
|
265
|
+
stats_all = tuple (
|
|
266
|
+
matching(y_t, y_p, thresh=thresh, criterion=criterion, report_matches=False)
|
|
267
|
+
for y_t,y_p in tqdm(y_gen,**tqdm_kwargs)
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
# accumulate results over all images for each threshold separately
|
|
271
|
+
n_images, n_threshs = len(stats_all), len(thresh)
|
|
272
|
+
accumulate = [{} for _ in range(n_threshs)]
|
|
273
|
+
for stats in stats_all:
|
|
274
|
+
for i,s in enumerate(stats):
|
|
275
|
+
acc = accumulate[i]
|
|
276
|
+
for k,v in s._asdict().items():
|
|
277
|
+
if k == 'mean_true_score' and not bool(by_image):
|
|
278
|
+
# convert mean_true_score to "sum_matched_score"
|
|
279
|
+
acc[k] = acc.setdefault(k,0) + v * s.n_true
|
|
280
|
+
else:
|
|
281
|
+
try:
|
|
282
|
+
acc[k] = acc.setdefault(k,0) + v
|
|
283
|
+
except TypeError:
|
|
284
|
+
pass
|
|
285
|
+
|
|
286
|
+
# normalize/compute 'precision', 'recall', 'accuracy', 'f1'
|
|
287
|
+
for thr,acc in zip(thresh,accumulate):
|
|
288
|
+
set(acc.keys()) == expected_keys or _raise(ValueError("unexpected keys"))
|
|
289
|
+
acc['criterion'] = criterion
|
|
290
|
+
acc['thresh'] = thr
|
|
291
|
+
acc['by_image'] = bool(by_image)
|
|
292
|
+
if bool(by_image):
|
|
293
|
+
for k in ('precision', 'recall', 'accuracy', 'f1', 'mean_true_score', 'mean_matched_score', 'panoptic_quality'):
|
|
294
|
+
acc[k] /= n_images
|
|
295
|
+
else:
|
|
296
|
+
tp, fp, fn, n_true = acc['tp'], acc['fp'], acc['fn'], acc['n_true']
|
|
297
|
+
sum_matched_score = acc['mean_true_score']
|
|
298
|
+
|
|
299
|
+
mean_matched_score = _safe_divide(sum_matched_score, tp)
|
|
300
|
+
mean_true_score = _safe_divide(sum_matched_score, n_true)
|
|
301
|
+
panoptic_quality = _safe_divide(sum_matched_score, tp+fp/2+fn/2)
|
|
302
|
+
|
|
303
|
+
acc.update(
|
|
304
|
+
precision = precision(tp,fp,fn),
|
|
305
|
+
recall = recall(tp,fp,fn),
|
|
306
|
+
accuracy = accuracy(tp,fp,fn),
|
|
307
|
+
f1 = f1(tp,fp,fn),
|
|
308
|
+
mean_true_score = mean_true_score,
|
|
309
|
+
mean_matched_score = mean_matched_score,
|
|
310
|
+
panoptic_quality = panoptic_quality,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
accumulate = tuple(namedtuple('DatasetMatching',acc.keys())(*acc.values()) for acc in accumulate)
|
|
314
|
+
return accumulate[0] if single_thresh else accumulate
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# copied from scikit-image master for now (remove when part of a release)
|
|
319
|
+
def relabel_sequential(label_field, offset=1):
|
|
320
|
+
"""Relabel arbitrary labels to {`offset`, ... `offset` + number_of_labels}.
|
|
321
|
+
|
|
322
|
+
This function also returns the forward map (mapping the original labels to
|
|
323
|
+
the reduced labels) and the inverse map (mapping the reduced labels back
|
|
324
|
+
to the original ones).
|
|
325
|
+
|
|
326
|
+
Parameters
|
|
327
|
+
----------
|
|
328
|
+
label_field : numpy array of int, arbitrary shape
|
|
329
|
+
An array of labels, which must be non-negative integers.
|
|
330
|
+
offset : int, optional
|
|
331
|
+
The return labels will start at `offset`, which should be
|
|
332
|
+
strictly positive.
|
|
333
|
+
|
|
334
|
+
Returns
|
|
335
|
+
-------
|
|
336
|
+
relabeled : numpy array of int, same shape as `label_field`
|
|
337
|
+
The input label field with labels mapped to
|
|
338
|
+
{offset, ..., number_of_labels + offset - 1}.
|
|
339
|
+
The data type will be the same as `label_field`, except when
|
|
340
|
+
offset + number_of_labels causes overflow of the current data type.
|
|
341
|
+
forward_map : numpy array of int, shape ``(label_field.max() + 1,)``
|
|
342
|
+
The map from the original label space to the returned label
|
|
343
|
+
space. Can be used to re-apply the same mapping. See examples
|
|
344
|
+
for usage. The data type will be the same as `relabeled`.
|
|
345
|
+
inverse_map : 1D numpy array of int, of length offset + number of labels
|
|
346
|
+
The map from the new label space to the original space. This
|
|
347
|
+
can be used to reconstruct the original label field from the
|
|
348
|
+
relabeled one. The data type will be the same as `relabeled`.
|
|
349
|
+
|
|
350
|
+
Notes
|
|
351
|
+
-----
|
|
352
|
+
The label 0 is assumed to denote the background and is never remapped.
|
|
353
|
+
|
|
354
|
+
The forward map can be extremely big for some inputs, since its
|
|
355
|
+
length is given by the maximum of the label field. However, in most
|
|
356
|
+
situations, ``label_field.max()`` is much smaller than
|
|
357
|
+
``label_field.size``, and in these cases the forward map is
|
|
358
|
+
guaranteed to be smaller than either the input or output images.
|
|
359
|
+
|
|
360
|
+
Examples
|
|
361
|
+
--------
|
|
362
|
+
>>> from skimage.segmentation import relabel_sequential
|
|
363
|
+
>>> label_field = np.array([1, 1, 5, 5, 8, 99, 42])
|
|
364
|
+
>>> relab, fw, inv = relabel_sequential(label_field)
|
|
365
|
+
>>> relab
|
|
366
|
+
array([1, 1, 2, 2, 3, 5, 4])
|
|
367
|
+
>>> fw
|
|
368
|
+
array([0, 1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
|
369
|
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0,
|
|
370
|
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
|
371
|
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
|
372
|
+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5])
|
|
373
|
+
>>> inv
|
|
374
|
+
array([ 0, 1, 5, 8, 42, 99])
|
|
375
|
+
>>> (fw[label_field] == relab).all()
|
|
376
|
+
True
|
|
377
|
+
>>> (inv[relab] == label_field).all()
|
|
378
|
+
True
|
|
379
|
+
>>> relab, fw, inv = relabel_sequential(label_field, offset=5)
|
|
380
|
+
>>> relab
|
|
381
|
+
array([5, 5, 6, 6, 7, 9, 8])
|
|
382
|
+
"""
|
|
383
|
+
offset = int(offset)
|
|
384
|
+
if offset <= 0:
|
|
385
|
+
raise ValueError("Offset must be strictly positive.")
|
|
386
|
+
if np.min(label_field) < 0:
|
|
387
|
+
raise ValueError("Cannot relabel array that contains negative values.")
|
|
388
|
+
max_label = int(label_field.max()) # Ensure max_label is an integer
|
|
389
|
+
if not np.issubdtype(label_field.dtype, np.integer):
|
|
390
|
+
new_type = np.min_scalar_type(max_label)
|
|
391
|
+
label_field = label_field.astype(new_type)
|
|
392
|
+
labels = np.unique(label_field)
|
|
393
|
+
labels0 = labels[labels != 0]
|
|
394
|
+
new_max_label = offset - 1 + len(labels0)
|
|
395
|
+
new_labels0 = np.arange(offset, new_max_label + 1)
|
|
396
|
+
output_type = label_field.dtype
|
|
397
|
+
required_type = np.min_scalar_type(new_max_label)
|
|
398
|
+
if np.dtype(required_type).itemsize > np.dtype(label_field.dtype).itemsize:
|
|
399
|
+
output_type = required_type
|
|
400
|
+
forward_map = np.zeros(max_label + 1, dtype=output_type)
|
|
401
|
+
forward_map[labels0] = new_labels0
|
|
402
|
+
inverse_map = np.zeros(new_max_label + 1, dtype=output_type)
|
|
403
|
+
inverse_map[offset:] = labels0
|
|
404
|
+
relabeled = forward_map[label_field]
|
|
405
|
+
return relabeled, forward_map, inverse_map
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def group_matching_labels(ys, thresh=1e-10, criterion='iou'):
|
|
410
|
+
"""
|
|
411
|
+
Group matching objects (i.e. assign the same label id) in a
|
|
412
|
+
list of label images (e.g. consecutive frames of a time-lapse).
|
|
413
|
+
|
|
414
|
+
Uses function `matching` (with provided `criterion` and `thresh`) to
|
|
415
|
+
iteratively/greedily match and group objects/labels in consecutive images of `ys`.
|
|
416
|
+
To that end, matching objects are grouped together by assigning the same label id,
|
|
417
|
+
whereas unmatched objects are assigned a new label id.
|
|
418
|
+
At the end of this process, each label group will have been assigned a unique id.
|
|
419
|
+
|
|
420
|
+
Note that the label images `ys` will not be modified. Instead, they will initially
|
|
421
|
+
be duplicated and converted to data type `np.int32` before objects are grouped and the result
|
|
422
|
+
is returned. (Note that `np.int32` limits the number of label groups to at most 2147483647.)
|
|
423
|
+
|
|
424
|
+
Example
|
|
425
|
+
-------
|
|
426
|
+
import numpy as np
|
|
427
|
+
from stardist.data import test_image_nuclei_2d
|
|
428
|
+
from stardist.matching import group_matching_labels
|
|
429
|
+
|
|
430
|
+
_y = test_image_nuclei_2d(return_mask=True)[1]
|
|
431
|
+
labels = np.stack([_y, 2*np.roll(_y,10)], axis=0)
|
|
432
|
+
|
|
433
|
+
labels_new = group_matching_labels(labels)
|
|
434
|
+
|
|
435
|
+
Parameters
|
|
436
|
+
----------
|
|
437
|
+
ys : np.ndarray or list/tuple of np.ndarray
|
|
438
|
+
list/array of integer labels (2D or 3D)
|
|
439
|
+
|
|
440
|
+
"""
|
|
441
|
+
# check 'ys' without making a copy
|
|
442
|
+
len(ys) > 1 or _raise(ValueError("'ys' must have 2 or more entries"))
|
|
443
|
+
if isinstance(ys, np.ndarray):
|
|
444
|
+
_check_label_array(ys, 'ys')
|
|
445
|
+
ys.ndim > 1 or _raise(ValueError("'ys' must be at least 2-dimensional"))
|
|
446
|
+
ys_grouped = np.empty_like(ys, dtype=np.int32)
|
|
447
|
+
else:
|
|
448
|
+
all(_check_label_array(y, 'ys') for y in ys) or _raise(ValueError("'ys' must be a list of label images"))
|
|
449
|
+
all(y.shape==ys[0].shape for y in ys) or _raise(ValueError("all label images must have the same shape"))
|
|
450
|
+
ys_grouped = np.empty((len(ys),)+ys[0].shape, dtype=np.int32)
|
|
451
|
+
|
|
452
|
+
def _match_single(y_prev, y, next_id):
|
|
453
|
+
y = y.astype(np.int32, copy=False)
|
|
454
|
+
res = matching(y_prev, y, report_matches=True, thresh=thresh, criterion=criterion)
|
|
455
|
+
# relabel dict (for matching labels) that maps label ids from y -> y_prev
|
|
456
|
+
relabel = dict(reversed(res.matched_pairs[i]) for i in res.matched_tps)
|
|
457
|
+
y_grouped = np.zeros_like(y)
|
|
458
|
+
for r in regionprops(y):
|
|
459
|
+
m = (y[r.slice] == r.label)
|
|
460
|
+
if r.label in relabel:
|
|
461
|
+
y_grouped[r.slice][m] = relabel[r.label]
|
|
462
|
+
else:
|
|
463
|
+
y_grouped[r.slice][m] = next_id
|
|
464
|
+
next_id += 1
|
|
465
|
+
return y_grouped, next_id
|
|
466
|
+
|
|
467
|
+
ys_grouped[0] = ys[0]
|
|
468
|
+
next_id = ys_grouped[0].max() + 1
|
|
469
|
+
for i in range(len(ys)-1):
|
|
470
|
+
ys_grouped[i+1], next_id = _match_single(ys_grouped[i], ys[i+1], next_id)
|
|
471
|
+
return ys_grouped
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _shuffle_labels(y):
|
|
476
|
+
_check_label_array(y, 'y')
|
|
477
|
+
y2 = np.zeros_like(y)
|
|
478
|
+
ids = tuple(set(np.unique(y)) - {0})
|
|
479
|
+
relabel = dict(zip(ids,np.random.permutation(ids)))
|
|
480
|
+
for r in regionprops(y):
|
|
481
|
+
m = (y[r.slice] == r.label)
|
|
482
|
+
y2[r.slice][m] = relabel[r.label]
|
|
483
|
+
return y2
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import absolute_import, print_function
|
|
2
|
+
|
|
3
|
+
from .model2d import Config2D, StarDist2D, StarDistData2D
|
|
4
|
+
from .model3d import Config3D, StarDist3D, StarDistData3D
|
|
5
|
+
|
|
6
|
+
from csbdeep.utils import backend_channels_last
|
|
7
|
+
from csbdeep.utils.tf import BACKEND as K
|
|
8
|
+
if not backend_channels_last():
|
|
9
|
+
raise NotImplementedError(
|
|
10
|
+
"Keras is configured to use the '%s' image data format, which is currently not supported. "
|
|
11
|
+
"Please change it to use 'channels_last' instead: "
|
|
12
|
+
"https://keras.io/getting-started/faq/#where-is-the-keras-configuration-file-stored" % K.image_data_format()
|
|
13
|
+
)
|
|
14
|
+
del backend_channels_last, K
|
|
15
|
+
|
|
16
|
+
from csbdeep.models import register_model, register_aliases, clear_models_and_aliases
|
|
17
|
+
# register pre-trained models and aliases (TODO: replace with updatable solution)
|
|
18
|
+
clear_models_and_aliases(StarDist2D, StarDist3D)
|
|
19
|
+
register_model(StarDist2D, '2D_versatile_fluo', 'https://github.com/stardist/stardist-models/releases/download/v0.1/python_2D_versatile_fluo.zip', '4ad678d0758eed6e55625f1b5ae30771e59adb79f1239e09b9772eac8846c3dd')
|
|
20
|
+
register_model(StarDist2D, '2D_versatile_he', 'https://github.com/stardist/stardist-models/releases/download/v0.1/python_2D_versatile_he.zip', 'f1696ef0631bd7e1c0e5c0d3017e2b4c6a95e284c6aab9c22fc2f08317817b28')
|
|
21
|
+
register_model(StarDist2D, '2D_paper_dsb2018', 'https://github.com/stardist/stardist-models/releases/download/v0.1/python_2D_paper_dsb2018.zip', '4c11cf68512341d9e8ce3d1278c64ceb8ac400582739f85fcab079a2e82840d2')
|
|
22
|
+
register_model(StarDist2D, '2D_demo', 'https://github.com/stardist/stardist-models/releases/download/v0.1/python_2D_demo.zip', 'a1efaebd7103db6236655bf158b6e21cf5b38d58ec77a509802244a89a260fa4')
|
|
23
|
+
register_model(StarDist3D, '3D_demo', 'https://github.com/stardist/stardist-models/releases/download/v0.1/python_3D_demo.zip', 'ea05831eb5acc8a2fd31eaa23f4460a196a9af53b14f40affb9d80885f699f90')
|
|
24
|
+
|
|
25
|
+
register_aliases(StarDist2D, '2D_paper_dsb2018', 'DSB 2018 (from StarDist 2D paper)')
|
|
26
|
+
register_aliases(StarDist2D, '2D_versatile_fluo', 'Versatile (fluorescent nuclei)')
|
|
27
|
+
register_aliases(StarDist2D, '2D_versatile_he', 'Versatile (H&E nuclei)')
|
|
28
|
+
del register_model, register_aliases, clear_models_and_aliases
|