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.
Files changed (148) hide show
  1. senoquant/__init__.py +6 -0
  2. senoquant/_reader.py +7 -0
  3. senoquant/_widget.py +33 -0
  4. senoquant/napari.yaml +83 -0
  5. senoquant/reader/__init__.py +5 -0
  6. senoquant/reader/core.py +369 -0
  7. senoquant/tabs/__init__.py +15 -0
  8. senoquant/tabs/batch/__init__.py +10 -0
  9. senoquant/tabs/batch/backend.py +641 -0
  10. senoquant/tabs/batch/config.py +270 -0
  11. senoquant/tabs/batch/frontend.py +1283 -0
  12. senoquant/tabs/batch/io.py +326 -0
  13. senoquant/tabs/batch/layers.py +86 -0
  14. senoquant/tabs/quantification/__init__.py +1 -0
  15. senoquant/tabs/quantification/backend.py +228 -0
  16. senoquant/tabs/quantification/features/__init__.py +80 -0
  17. senoquant/tabs/quantification/features/base.py +142 -0
  18. senoquant/tabs/quantification/features/marker/__init__.py +5 -0
  19. senoquant/tabs/quantification/features/marker/config.py +69 -0
  20. senoquant/tabs/quantification/features/marker/dialog.py +437 -0
  21. senoquant/tabs/quantification/features/marker/export.py +879 -0
  22. senoquant/tabs/quantification/features/marker/feature.py +119 -0
  23. senoquant/tabs/quantification/features/marker/morphology.py +285 -0
  24. senoquant/tabs/quantification/features/marker/rows.py +654 -0
  25. senoquant/tabs/quantification/features/marker/thresholding.py +46 -0
  26. senoquant/tabs/quantification/features/roi.py +346 -0
  27. senoquant/tabs/quantification/features/spots/__init__.py +5 -0
  28. senoquant/tabs/quantification/features/spots/config.py +62 -0
  29. senoquant/tabs/quantification/features/spots/dialog.py +477 -0
  30. senoquant/tabs/quantification/features/spots/export.py +1292 -0
  31. senoquant/tabs/quantification/features/spots/feature.py +112 -0
  32. senoquant/tabs/quantification/features/spots/morphology.py +279 -0
  33. senoquant/tabs/quantification/features/spots/rows.py +241 -0
  34. senoquant/tabs/quantification/frontend.py +815 -0
  35. senoquant/tabs/segmentation/__init__.py +1 -0
  36. senoquant/tabs/segmentation/backend.py +131 -0
  37. senoquant/tabs/segmentation/frontend.py +1009 -0
  38. senoquant/tabs/segmentation/models/__init__.py +5 -0
  39. senoquant/tabs/segmentation/models/base.py +146 -0
  40. senoquant/tabs/segmentation/models/cpsam/details.json +65 -0
  41. senoquant/tabs/segmentation/models/cpsam/model.py +150 -0
  42. senoquant/tabs/segmentation/models/default_2d/details.json +69 -0
  43. senoquant/tabs/segmentation/models/default_2d/model.py +664 -0
  44. senoquant/tabs/segmentation/models/default_3d/details.json +69 -0
  45. senoquant/tabs/segmentation/models/default_3d/model.py +682 -0
  46. senoquant/tabs/segmentation/models/hf.py +71 -0
  47. senoquant/tabs/segmentation/models/nuclear_dilation/__init__.py +1 -0
  48. senoquant/tabs/segmentation/models/nuclear_dilation/details.json +26 -0
  49. senoquant/tabs/segmentation/models/nuclear_dilation/model.py +96 -0
  50. senoquant/tabs/segmentation/models/perinuclear_rings/__init__.py +1 -0
  51. senoquant/tabs/segmentation/models/perinuclear_rings/details.json +34 -0
  52. senoquant/tabs/segmentation/models/perinuclear_rings/model.py +132 -0
  53. senoquant/tabs/segmentation/stardist_onnx_utils/__init__.py +2 -0
  54. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/__init__.py +3 -0
  55. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/__init__.py +6 -0
  56. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/generate.py +470 -0
  57. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/prepare.py +273 -0
  58. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/rawdata.py +112 -0
  59. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/transform.py +384 -0
  60. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/__init__.py +0 -0
  61. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/blocks.py +184 -0
  62. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/losses.py +79 -0
  63. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/nets.py +165 -0
  64. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/predict.py +467 -0
  65. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/probability.py +67 -0
  66. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/train.py +148 -0
  67. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/io/__init__.py +163 -0
  68. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/__init__.py +52 -0
  69. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/base_model.py +329 -0
  70. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_isotropic.py +160 -0
  71. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_projection.py +178 -0
  72. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_standard.py +446 -0
  73. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_upsampling.py +54 -0
  74. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/config.py +254 -0
  75. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/pretrained.py +119 -0
  76. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/scripts/__init__.py +0 -0
  77. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/scripts/care_predict.py +180 -0
  78. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/__init__.py +5 -0
  79. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/plot_utils.py +159 -0
  80. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/six.py +18 -0
  81. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/tf.py +644 -0
  82. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/utils.py +272 -0
  83. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/version.py +1 -0
  84. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/docs/source/conf.py +368 -0
  85. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/setup.py +68 -0
  86. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_datagen.py +169 -0
  87. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_models.py +462 -0
  88. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_utils.py +166 -0
  89. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tools/create_zip_contents.py +34 -0
  90. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/__init__.py +30 -0
  91. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/big.py +624 -0
  92. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/bioimageio_utils.py +494 -0
  93. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/data/__init__.py +39 -0
  94. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/__init__.py +10 -0
  95. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/geom2d.py +215 -0
  96. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/geom3d.py +349 -0
  97. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/matching.py +483 -0
  98. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/__init__.py +28 -0
  99. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/base.py +1217 -0
  100. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/model2d.py +594 -0
  101. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/model3d.py +696 -0
  102. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/nms.py +384 -0
  103. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/__init__.py +2 -0
  104. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/plot.py +74 -0
  105. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/render.py +298 -0
  106. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/rays3d.py +373 -0
  107. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/sample_patches.py +65 -0
  108. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/__init__.py +0 -0
  109. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/predict2d.py +90 -0
  110. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/predict3d.py +93 -0
  111. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/utils.py +408 -0
  112. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/version.py +1 -0
  113. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/__init__.py +45 -0
  114. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/__init__.py +17 -0
  115. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/cli.py +55 -0
  116. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/core.py +285 -0
  117. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/__init__.py +15 -0
  118. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/cli.py +36 -0
  119. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/divisibility.py +193 -0
  120. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/probe.py +100 -0
  121. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/receptive_field.py +182 -0
  122. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/rf_cli.py +48 -0
  123. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/valid_sizes.py +278 -0
  124. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/post/__init__.py +8 -0
  125. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/post/core.py +157 -0
  126. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/pre/__init__.py +17 -0
  127. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/pre/core.py +226 -0
  128. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/predict/__init__.py +5 -0
  129. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/predict/core.py +401 -0
  130. senoquant/tabs/settings/__init__.py +1 -0
  131. senoquant/tabs/settings/backend.py +29 -0
  132. senoquant/tabs/settings/frontend.py +19 -0
  133. senoquant/tabs/spots/__init__.py +1 -0
  134. senoquant/tabs/spots/backend.py +139 -0
  135. senoquant/tabs/spots/frontend.py +800 -0
  136. senoquant/tabs/spots/models/__init__.py +5 -0
  137. senoquant/tabs/spots/models/base.py +94 -0
  138. senoquant/tabs/spots/models/rmp/details.json +61 -0
  139. senoquant/tabs/spots/models/rmp/model.py +499 -0
  140. senoquant/tabs/spots/models/udwt/details.json +103 -0
  141. senoquant/tabs/spots/models/udwt/model.py +482 -0
  142. senoquant/utils.py +25 -0
  143. senoquant-1.0.0b1.dist-info/METADATA +193 -0
  144. senoquant-1.0.0b1.dist-info/RECORD +148 -0
  145. senoquant-1.0.0b1.dist-info/WHEEL +5 -0
  146. senoquant-1.0.0b1.dist-info/entry_points.txt +2 -0
  147. senoquant-1.0.0b1.dist-info/licenses/LICENSE +28 -0
  148. senoquant-1.0.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1217 @@
1
+ from __future__ import print_function, unicode_literals, absolute_import, division
2
+
3
+ import numpy as np
4
+ import sys
5
+ import warnings
6
+ import math
7
+ from tqdm import tqdm
8
+ from collections import namedtuple
9
+ from pathlib import Path
10
+ import threading
11
+ import functools
12
+ import scipy.ndimage as ndi
13
+ import numbers
14
+
15
+ from csbdeep.models.base_model import BaseModel
16
+ from csbdeep.utils.tf import export_SavedModel, keras_import, IS_TF_1, CARETensorBoard, BACKEND as K
17
+
18
+ import tensorflow as tf
19
+ Sequence = keras_import('utils', 'Sequence')
20
+ Adam = keras_import('optimizers', 'Adam')
21
+ ReduceLROnPlateau, TensorBoard = keras_import('callbacks', 'ReduceLROnPlateau', 'TensorBoard')
22
+
23
+ from csbdeep.utils import _raise, backend_channels_last, axes_check_and_normalize, axes_dict, load_json, save_json
24
+ from csbdeep.internals.predict import tile_iterator, total_n_tiles
25
+ from csbdeep.internals.train import RollingSequence
26
+ from csbdeep.data import Resizer
27
+
28
+ from ..sample_patches import get_valid_inds
29
+ from ..nms import _ind_prob_thresh
30
+ from ..utils import _is_power_of_2, _is_floatarray, optimize_threshold, grid_divisible_patch_size
31
+
32
+ # TODO: helper function to check if receptive field of cnn is sufficient for object sizes in GT
33
+
34
+ def generic_masked_loss(mask, loss, weights=1, norm_by_mask=True, reg_weight=0, reg_penalty=K.abs):
35
+ mask = K.cast(mask, K.floatx())
36
+ weights = K.cast(weights, K.floatx())
37
+ _reg_weight = K.cast(reg_weight, K.floatx())
38
+ def _loss(y_true, y_pred):
39
+ actual_loss = K.mean(mask * weights * loss(y_true, y_pred), axis=-1)
40
+ norm_mask = (K.mean(mask) + K.epsilon()) if norm_by_mask else 1
41
+ if reg_weight > 0:
42
+ reg_loss = K.mean((1-mask) * reg_penalty(y_pred), axis=-1)
43
+ return actual_loss / norm_mask + _reg_weight * reg_loss
44
+ else:
45
+ return actual_loss / norm_mask
46
+ return _loss
47
+
48
+ def masked_loss(mask, penalty, reg_weight, norm_by_mask):
49
+ loss = lambda y_true, y_pred: penalty(K.cast(y_true, K.floatx()) - y_pred)
50
+ return generic_masked_loss(mask, loss, reg_weight=reg_weight, norm_by_mask=norm_by_mask)
51
+
52
+ # TODO: should we use norm_by_mask=True in the loss or only in a metric?
53
+ # previous 2D behavior was norm_by_mask=False
54
+ # same question for reg_weight? use 1e-4 (as in 3D) or 0 (as in 2D)?
55
+
56
+ def masked_loss_mae(mask, reg_weight=0, norm_by_mask=True):
57
+ return masked_loss(mask, K.abs, reg_weight=reg_weight, norm_by_mask=norm_by_mask)
58
+
59
+ def masked_loss_mse(mask, reg_weight=0, norm_by_mask=True):
60
+ return masked_loss(mask, K.square, reg_weight=reg_weight, norm_by_mask=norm_by_mask)
61
+
62
+ def masked_metric_mae(mask):
63
+ def relevant_mae(y_true, y_pred):
64
+ return masked_loss(mask, K.abs, reg_weight=0, norm_by_mask=True)(y_true, y_pred)
65
+ return relevant_mae
66
+
67
+ def masked_metric_mse(mask):
68
+ def relevant_mse(y_true, y_pred):
69
+ return masked_loss(mask, K.square, reg_weight=0, norm_by_mask=True)(y_true, y_pred)
70
+ return relevant_mse
71
+
72
+ def kld(y_true, y_pred):
73
+ y_true = K.cast(y_true, K.floatx())
74
+ mask = y_true >= 0 # pixels to ignore have y_true == -1
75
+ y_true = K.clip(y_true[mask], K.epsilon(), 1)
76
+ y_pred = K.clip(y_pred[mask], K.epsilon(), 1)
77
+ return K.mean(K.binary_crossentropy(y_true, y_pred) - K.binary_crossentropy(y_true, y_true), axis=-1)
78
+
79
+
80
+ def masked_loss_iou(mask, reg_weight=0, norm_by_mask=True):
81
+ def iou_loss(y_true, y_pred):
82
+ y_true = K.cast(y_true, K.floatx())
83
+ axis = -1 if backend_channels_last() else 1
84
+ # y_pred can be negative (since not constrained) -> 'inter' can be very large for y_pred << 0
85
+ # - clipping y_pred values at 0 can lead to vanishing gradients
86
+ # - 'K.sign(y_pred)' term fixes issue by enforcing that y_pred values >= 0 always lead to larger 'inter' (lower loss)
87
+ inter = K.mean(K.sign(y_pred)*K.square(K.minimum(y_true,y_pred)), axis=axis)
88
+ union = K.mean(K.square(K.maximum(y_true,y_pred)), axis=axis)
89
+ iou = inter/(union+K.epsilon())
90
+ iou = K.expand_dims(iou,axis)
91
+ loss = 1. - iou # + 0.005*K.abs(y_true-y_pred)
92
+ return loss
93
+ return generic_masked_loss(mask, iou_loss, reg_weight=reg_weight, norm_by_mask=norm_by_mask)
94
+
95
+ def masked_metric_iou(mask, reg_weight=0, norm_by_mask=True):
96
+ def iou_metric(y_true, y_pred):
97
+ y_true = K.cast(y_true, K.floatx())
98
+ axis = -1 if backend_channels_last() else 1
99
+ y_pred = K.maximum(0., y_pred)
100
+ inter = K.mean(K.square(K.minimum(y_true,y_pred)), axis=axis)
101
+ union = K.mean(K.square(K.maximum(y_true,y_pred)), axis=axis)
102
+ iou = inter/(union+K.epsilon())
103
+ loss = K.expand_dims(iou,axis)
104
+ return loss
105
+ return generic_masked_loss(mask, iou_metric, reg_weight=reg_weight, norm_by_mask=norm_by_mask)
106
+
107
+
108
+ def weighted_categorical_crossentropy(weights, ndim):
109
+ """ ndim = (2,3) """
110
+
111
+ axis = -1 if backend_channels_last() else 1
112
+ shape = [1]*(ndim+2)
113
+ shape[axis] = len(weights)
114
+ weights = np.broadcast_to(weights, shape)
115
+ weights = K.cast(weights, K.floatx())
116
+
117
+ def weighted_cce(y_true, y_pred):
118
+ # ignore pixels that have y_true (prob_class) < 0
119
+ y_true = K.cast(y_true, K.floatx())
120
+ mask = K.cast(y_true>=0, K.floatx())
121
+ y_pred /= K.sum(y_pred+K.epsilon(), axis=axis, keepdims=True)
122
+ y_pred = K.clip(y_pred, K.epsilon(), 1. - K.epsilon())
123
+ loss = - K.sum(weights*mask*y_true*K.log(y_pred), axis = axis)
124
+ return loss
125
+
126
+ return weighted_cce
127
+
128
+
129
+ class StarDistDataBase(RollingSequence):
130
+
131
+ def __init__(self, X, Y, n_rays, grid, batch_size, patch_size, length,
132
+ n_classes=None, classes=None,
133
+ use_gpu=False, sample_ind_cache=True, maxfilter_patch_size=None, augmenter=None, foreground_prob=0, keras_kwargs=None):
134
+
135
+ super().__init__(data_size=len(X), batch_size=batch_size, length=length, shuffle=True, keras_kwargs=keras_kwargs)
136
+
137
+ if isinstance(X, (np.ndarray, tuple, list)):
138
+ X = [x.astype(np.float32, copy=False) for x in X]
139
+
140
+ # sanity checks
141
+ len(X)==len(Y) and len(X)>0 or _raise(ValueError("X and Y can't be empty and must have same length"))
142
+
143
+ if classes is None:
144
+ # set classes to None for all images (i.e. defaults to every object instance assigned the same class)
145
+ classes = (None,)*len(X)
146
+ else:
147
+ n_classes is not None or warnings.warn("Ignoring classes since n_classes is None")
148
+
149
+ len(classes)==len(X) or _raise(ValueError("X and classes must have same length"))
150
+
151
+ self.n_classes, self.classes = n_classes, classes
152
+ patch_size = grid_divisible_patch_size(patch_size, grid)
153
+
154
+ nD = len(patch_size)
155
+ assert nD in (2,3)
156
+ x_ndim = X[0].ndim
157
+ assert x_ndim in (nD,nD+1)
158
+
159
+ if isinstance(X, (np.ndarray, tuple, list)) and \
160
+ isinstance(Y, (np.ndarray, tuple, list)):
161
+ all(y.ndim==nD and x.ndim==x_ndim and x.shape[:nD]==y.shape for x,y in zip(X,Y)) or _raise(ValueError("images and masks should have corresponding shapes/dimensions"))
162
+ all(x.shape[:nD]>=tuple(patch_size) for x in X) or _raise(ValueError("Some images are too small for given patch_size {patch_size}".format(patch_size=patch_size)))
163
+
164
+ if x_ndim == nD:
165
+ self.n_channel = None
166
+ else:
167
+ self.n_channel = X[0].shape[-1]
168
+ if isinstance(X, (np.ndarray, tuple, list)):
169
+ assert all(x.shape[-1]==self.n_channel for x in X)
170
+
171
+ assert 0 <= foreground_prob <= 1
172
+
173
+ self.X, self.Y = X, Y
174
+ # self.batch_size = batch_size
175
+ self.n_rays = n_rays
176
+ self.patch_size = patch_size
177
+ self.ss_grid = (slice(None),) + tuple(slice(0, None, g) for g in grid)
178
+ self.grid = tuple(grid)
179
+ self.use_gpu = bool(use_gpu)
180
+ if augmenter is None:
181
+ augmenter = lambda *args: args
182
+ callable(augmenter) or _raise(ValueError("augmenter must be None or callable"))
183
+ self.augmenter = augmenter
184
+ self.foreground_prob = foreground_prob
185
+
186
+ if self.use_gpu:
187
+ from gputools import max_filter
188
+ self.max_filter = lambda y, patch_size: max_filter(y.astype(np.float32), patch_size)
189
+ else:
190
+ from scipy.ndimage import maximum_filter
191
+ self.max_filter = lambda y, patch_size: maximum_filter(y, patch_size, mode='constant')
192
+
193
+ self.maxfilter_patch_size = maxfilter_patch_size if maxfilter_patch_size is not None else self.patch_size
194
+
195
+ self.sample_ind_cache = sample_ind_cache
196
+ self._ind_cache_fg = {}
197
+ self._ind_cache_all = {}
198
+ self.lock = threading.Lock()
199
+
200
+
201
+ def get_valid_inds(self, k, foreground_prob=None):
202
+ if foreground_prob is None:
203
+ foreground_prob = self.foreground_prob
204
+ foreground_only = np.random.uniform() < foreground_prob
205
+ _ind_cache = self._ind_cache_fg if foreground_only else self._ind_cache_all
206
+ if k in _ind_cache:
207
+ inds = _ind_cache[k]
208
+ else:
209
+ patch_filter = (lambda y,p: self.max_filter(y, self.maxfilter_patch_size) > 0) if foreground_only else None
210
+ inds = get_valid_inds(self.Y[k], self.patch_size, patch_filter=patch_filter)
211
+ if self.sample_ind_cache:
212
+ with self.lock:
213
+ _ind_cache[k] = inds
214
+ if foreground_only and len(inds[0])==0:
215
+ # no foreground pixels available
216
+ return self.get_valid_inds(k, foreground_prob=0)
217
+ return inds
218
+
219
+
220
+ def channels_as_tuple(self, x):
221
+ if self.n_channel is None:
222
+ return (x,)
223
+ else:
224
+ return tuple(x[...,i] for i in range(self.n_channel))
225
+
226
+
227
+
228
+ class StarDistBase(BaseModel):
229
+
230
+ def __init__(self, config, name=None, basedir='.'):
231
+ super().__init__(config=config, name=name, basedir=basedir)
232
+ threshs = dict(prob=None, nms=None)
233
+ if basedir is not None:
234
+ try:
235
+ threshs = load_json(str(self.logdir / 'thresholds.json'))
236
+ print("Loading thresholds from 'thresholds.json'.")
237
+ if threshs.get('prob') is None or not (0 < threshs.get('prob') < 1):
238
+ print("- Invalid 'prob' threshold (%s), using default value." % str(threshs.get('prob')))
239
+ threshs['prob'] = None
240
+ if threshs.get('nms') is None or not (0 < threshs.get('nms') < 1):
241
+ print("- Invalid 'nms' threshold (%s), using default value." % str(threshs.get('nms')))
242
+ threshs['nms'] = None
243
+ except FileNotFoundError:
244
+ if config is None and len(tuple(self.logdir.glob('*.h5'))) > 0:
245
+ print("Couldn't load thresholds from 'thresholds.json', using default values. "
246
+ "(Call 'optimize_thresholds' to change that.)")
247
+
248
+ self.thresholds = dict (
249
+ prob = 0.5 if threshs['prob'] is None else threshs['prob'],
250
+ nms = 0.4 if threshs['nms'] is None else threshs['nms'],
251
+ )
252
+ print("Using default values: prob_thresh={prob:g}, nms_thresh={nms:g}.".format(prob=self.thresholds.prob, nms=self.thresholds.nms))
253
+
254
+
255
+ @property
256
+ def thresholds(self):
257
+ return self._thresholds
258
+
259
+ def _is_multiclass(self):
260
+ return (self.config.n_classes is not None)
261
+
262
+ def _parse_classes_arg(self, classes, length):
263
+ """ creates a proper classes tuple from different possible "classes" arguments in model.train()
264
+
265
+ classes can be
266
+ "auto" -> all objects will be assigned to the first foreground class (unless n_classes is None)
267
+ single integer -> all objects will be assigned that class
268
+ tuple, list, ndarray -> do nothing (needs to be of given length)
269
+
270
+ returns a tuple of given length
271
+ """
272
+ if isinstance(classes, str):
273
+ classes == "auto" or _raise(ValueError(f"classes = '{classes}': only 'auto' supported as string argument for classes"))
274
+ if self.config.n_classes is None:
275
+ classes = None
276
+ elif self.config.n_classes == 1:
277
+ classes = (1,)*length
278
+ else:
279
+ raise ValueError("using classes = 'auto' for n_classes > 1 not supported")
280
+ elif isinstance(classes, (tuple, list, np.ndarray)):
281
+ len(classes) == length or _raise(ValueError(f"len(classes) should be {length}!"))
282
+ else:
283
+ raise ValueError("classes should either be 'auto' or a list of scalars/label dicts")
284
+ return classes
285
+
286
+ @thresholds.setter
287
+ def thresholds(self, d):
288
+ self._thresholds = namedtuple('Thresholds',d.keys())(*d.values())
289
+
290
+
291
+ def prepare_for_training(self, optimizer=None):
292
+ """Prepare for neural network training.
293
+
294
+ Compiles the model and creates
295
+ `Keras Callbacks <https://keras.io/callbacks/>`_ to be used for training.
296
+
297
+ Note that this method will be implicitly called once by :func:`train`
298
+ (with default arguments) if not done so explicitly beforehand.
299
+
300
+ Parameters
301
+ ----------
302
+ optimizer : obj or None
303
+ Instance of a `Keras Optimizer <https://keras.io/optimizers/>`_ to be used for training.
304
+ If ``None`` (default), uses ``Adam`` with the learning rate specified in ``config``.
305
+
306
+ """
307
+ if optimizer is None:
308
+ optimizer = Adam(self.config.train_learning_rate)
309
+
310
+ masked_dist_loss = {'mse': masked_loss_mse,
311
+ 'mae': masked_loss_mae,
312
+ 'iou': masked_loss_iou,
313
+ }[self.config.train_dist_loss]
314
+
315
+ def prob_loss(y_true, y_pred):
316
+ y_true = K.cast(y_true, K.floatx())
317
+ mask = y_true >= 0
318
+ return K.mean(K.binary_crossentropy(y_true[mask], y_pred[mask]), axis=-1)
319
+
320
+ def split_dist_true_mask(dist_true_mask):
321
+ return tf.split(dist_true_mask, num_or_size_splits=[self.config.n_rays,-1], axis=-1)
322
+
323
+ def dist_loss(dist_true_mask, dist_pred):
324
+ dist_true, dist_mask = split_dist_true_mask(dist_true_mask)
325
+ return masked_dist_loss(dist_mask, reg_weight=self.config.train_background_reg)(dist_true, dist_pred)
326
+
327
+ def dist_iou_metric(dist_true_mask, dist_pred):
328
+ dist_true, dist_mask = split_dist_true_mask(dist_true_mask)
329
+ return masked_metric_iou(dist_mask, reg_weight=0)(dist_true, dist_pred)
330
+
331
+ def relevant_mae(dist_true_mask, dist_pred):
332
+ dist_true, dist_mask = split_dist_true_mask(dist_true_mask)
333
+ return masked_metric_mae(dist_mask)(dist_true, dist_pred)
334
+
335
+ def relevant_mse(dist_true_mask, dist_pred):
336
+ dist_true, dist_mask = split_dist_true_mask(dist_true_mask)
337
+ return masked_metric_mse(dist_mask)(dist_true, dist_pred)
338
+
339
+
340
+ if self._is_multiclass():
341
+ prob_class_loss = weighted_categorical_crossentropy(self.config.train_class_weights, ndim=self.config.n_dim)
342
+ loss = [prob_loss, dist_loss, prob_class_loss]
343
+ else:
344
+ loss = [prob_loss, dist_loss]
345
+
346
+ self.keras_model.compile(optimizer, loss = loss,
347
+ loss_weights = list(self.config.train_loss_weights),
348
+ metrics = {'prob': kld,
349
+ 'dist': [relevant_mae, relevant_mse, dist_iou_metric]})
350
+
351
+ self.callbacks = []
352
+ if self.basedir is not None:
353
+ self.callbacks += self._checkpoint_callbacks()
354
+
355
+ if self.config.train_tensorboard:
356
+ if IS_TF_1:
357
+ self.callbacks.append(CARETensorBoard(log_dir=str(self.logdir), prefix_with_timestamp=False, n_images=3, write_images=True, prob_out=False))
358
+ else:
359
+ self.callbacks.append(TensorBoard(log_dir=str(self.logdir/'logs'), write_graph=False, profile_batch=0))
360
+
361
+ if self.config.train_reduce_lr is not None:
362
+ rlrop_params = self.config.train_reduce_lr
363
+ if 'verbose' not in rlrop_params:
364
+ rlrop_params['verbose'] = True
365
+ # TF2: add as first callback to put 'lr' in the logs for TensorBoard
366
+ self.callbacks.insert(0,ReduceLROnPlateau(**rlrop_params))
367
+
368
+ self._model_prepared = True
369
+
370
+
371
+ def _predict_setup(self, img, axes, normalizer, n_tiles, show_tile_progress, predict_kwargs):
372
+ """ Shared setup code between `predict` and `predict_sparse` """
373
+ if n_tiles is None:
374
+ n_tiles = [1]*img.ndim
375
+ try:
376
+ n_tiles = tuple(n_tiles)
377
+ img.ndim == len(n_tiles) or _raise(TypeError())
378
+ except TypeError:
379
+ raise ValueError("n_tiles must be an iterable of length %d" % img.ndim)
380
+ all(np.isscalar(t) and 1<=t and int(t)==t for t in n_tiles) or _raise(
381
+ ValueError("all values of n_tiles must be integer values >= 1"))
382
+
383
+ n_tiles = tuple(map(int,n_tiles))
384
+
385
+ axes = self._normalize_axes(img, axes)
386
+ axes_net = self.config.axes
387
+
388
+ _permute_axes = self._make_permute_axes(axes, axes_net)
389
+ x = _permute_axes(img) # x has axes_net semantics
390
+
391
+ channel = axes_dict(axes_net)['C']
392
+ self.config.n_channel_in == x.shape[channel] or _raise(ValueError())
393
+ axes_net_div_by = self._axes_div_by(axes_net)
394
+
395
+ grid = tuple(self.config.grid)
396
+ len(grid) == len(axes_net)-1 or _raise(ValueError())
397
+ grid_dict = dict(zip(axes_net.replace('C',''),grid))
398
+
399
+ normalizer = self._check_normalizer_resizer(normalizer, None)[0]
400
+ resizer = StarDistPadAndCropResizer(grid=grid_dict)
401
+
402
+ x = normalizer.before(x, axes_net)
403
+ x = resizer.before(x, axes_net, axes_net_div_by)
404
+
405
+ if not _is_floatarray(x):
406
+ warnings.warn("Predicting on non-float input... ( forgot to normalize? )")
407
+
408
+ def predict_direct(x):
409
+ ys = self.keras_model.predict(x[np.newaxis], **predict_kwargs)
410
+ return tuple(y[0] for y in ys)
411
+
412
+ def tiling_setup():
413
+ assert np.prod(n_tiles) > 1
414
+ tiling_axes = axes_net.replace('C','') # axes eligible for tiling
415
+ x_tiling_axis = tuple(axes_dict(axes_net)[a] for a in tiling_axes) # numerical axis ids for x
416
+ axes_net_tile_overlaps = self._axes_tile_overlap(axes_net)
417
+ # hack: permute tiling axis in the same way as img -> x was permuted
418
+ _n_tiles = _permute_axes(np.empty(n_tiles,bool)).shape
419
+ (all(_n_tiles[i] == 1 for i in range(x.ndim) if i not in x_tiling_axis) or
420
+ _raise(ValueError("entry of n_tiles > 1 only allowed for axes '%s'" % tiling_axes)))
421
+
422
+ sh = [s//grid_dict.get(a,1) for a,s in zip(axes_net,x.shape)]
423
+ sh[channel] = None
424
+ def create_empty_output(n_channel, dtype=np.float32):
425
+ sh[channel] = n_channel
426
+ return np.empty(sh,dtype)
427
+
428
+ if callable(show_tile_progress):
429
+ progress, _show_tile_progress = show_tile_progress, True
430
+ else:
431
+ progress, _show_tile_progress = tqdm, show_tile_progress
432
+
433
+ n_block_overlaps = [int(np.ceil(overlap/blocksize)) for overlap, blocksize
434
+ in zip(axes_net_tile_overlaps, axes_net_div_by)]
435
+
436
+ num_tiles_used = total_n_tiles(x, _n_tiles, block_sizes=axes_net_div_by, n_block_overlaps=n_block_overlaps)
437
+
438
+ tile_generator = progress(tile_iterator(x, _n_tiles, block_sizes=axes_net_div_by, n_block_overlaps=n_block_overlaps),
439
+ disable=(not _show_tile_progress), total=num_tiles_used)
440
+
441
+ return tile_generator, tuple(sh), create_empty_output
442
+
443
+ return x, axes, axes_net, axes_net_div_by, _permute_axes, resizer, n_tiles, grid, grid_dict, channel, predict_direct, tiling_setup
444
+
445
+
446
+ def _predict_generator(self, img, axes=None, normalizer=None, n_tiles=None, show_tile_progress=True, **predict_kwargs):
447
+ """Predict.
448
+
449
+ Parameters
450
+ ----------
451
+ img : :class:`numpy.ndarray`
452
+ Input image
453
+ axes : str or None
454
+ Axes of the input ``img``.
455
+ ``None`` denotes that axes of img are the same as denoted in the config.
456
+ normalizer : :class:`csbdeep.data.Normalizer` or None
457
+ (Optional) normalization of input image before prediction.
458
+ Note that the default (``None``) assumes ``img`` to be already normalized.
459
+ n_tiles : iterable or None
460
+ Out of memory (OOM) errors can occur if the input image is too large.
461
+ To avoid this problem, the input image is broken up into (overlapping) tiles
462
+ that are processed independently and re-assembled.
463
+ This parameter denotes a tuple of the number of tiles for every image axis (see ``axes``).
464
+ ``None`` denotes that no tiling should be used.
465
+ show_tile_progress: bool or callable
466
+ If boolean, indicates whether to show progress (via tqdm) during tiled prediction.
467
+ If callable, must be a drop-in replacement for tqdm.
468
+ show_tile_progress: bool
469
+ Whether to show progress during tiled prediction.
470
+ predict_kwargs: dict
471
+ Keyword arguments for ``predict`` function of Keras model.
472
+
473
+ Returns
474
+ -------
475
+ (:class:`numpy.ndarray`, :class:`numpy.ndarray`, [:class:`numpy.ndarray`])
476
+ Returns the tuple (`prob`, `dist`, [`prob_class`]) of per-pixel object probabilities and star-convex polygon/polyhedra distances.
477
+ In multiclass prediction mode, `prob_class` is the probability map for each of the 1+'n_classes' classes (first class is background)
478
+
479
+ """
480
+
481
+ predict_kwargs.setdefault('verbose', 0)
482
+ x, axes, axes_net, axes_net_div_by, _permute_axes, resizer, n_tiles, grid, grid_dict, channel, predict_direct, tiling_setup = \
483
+ self._predict_setup(img, axes, normalizer, n_tiles, show_tile_progress, predict_kwargs)
484
+
485
+ if np.prod(n_tiles) > 1:
486
+ tile_generator, output_shape, create_empty_output = tiling_setup()
487
+
488
+ prob = create_empty_output(1)
489
+ dist = create_empty_output(self.config.n_rays)
490
+ if self._is_multiclass():
491
+ prob_class = create_empty_output(self.config.n_classes+1)
492
+ result = (prob, dist, prob_class)
493
+ else:
494
+ result = (prob, dist)
495
+
496
+ for tile, s_src, s_dst in tile_generator:
497
+ # predict_direct -> prob, dist, [prob_class if multi_class]
498
+ result_tile = predict_direct(tile)
499
+ # account for grid
500
+ s_src = [slice(s.start//grid_dict.get(a,1),s.stop//grid_dict.get(a,1)) for s,a in zip(s_src,axes_net)]
501
+ s_dst = [slice(s.start//grid_dict.get(a,1),s.stop//grid_dict.get(a,1)) for s,a in zip(s_dst,axes_net)]
502
+ # prob and dist have different channel dimensionality than image x
503
+ s_src[channel] = slice(None)
504
+ s_dst[channel] = slice(None)
505
+ s_src, s_dst = tuple(s_src), tuple(s_dst)
506
+ # print(s_src,s_dst)
507
+ for part, part_tile in zip(result, result_tile):
508
+ part[s_dst] = part_tile[s_src]
509
+ yield # yield None after each processed tile
510
+ else:
511
+ # predict_direct -> prob, dist, [prob_class if multi_class]
512
+ result = predict_direct(x)
513
+
514
+ result = [resizer.after(part, axes_net) for part in result]
515
+
516
+ # result = (prob, dist) for legacy or (prob, dist, prob_class) for multiclass
517
+
518
+ # prob
519
+ result[0] = np.take(result[0],0,axis=channel)
520
+ # dist
521
+ result[1] = np.maximum(1e-3, result[1]) # avoid small dist values to prevent problems with Qhull
522
+ result[1] = np.moveaxis(result[1],channel,-1)
523
+
524
+ if self._is_multiclass():
525
+ # prob_class
526
+ result[2] = np.moveaxis(result[2],channel,-1)
527
+
528
+ # last "yield" is the actual output that would have been "return"ed if this was a regular function
529
+ yield tuple(result)
530
+
531
+
532
+ @functools.wraps(_predict_generator)
533
+ def predict(self, *args, **kwargs):
534
+ # return last "yield"ed value of generator
535
+ r = None
536
+ for r in self._predict_generator(*args, **kwargs):
537
+ pass
538
+ return r
539
+
540
+
541
+ def _predict_sparse_generator(self, img, prob_thresh=None, axes=None, normalizer=None, n_tiles=None, show_tile_progress=True, b=2, **predict_kwargs):
542
+ """ Sparse version of model.predict()
543
+ Returns
544
+ -------
545
+ (prob, dist, [prob_class], points) flat list of probs, dists, (optional prob_class) and points
546
+ """
547
+ if prob_thresh is None: prob_thresh = self.thresholds.prob
548
+
549
+ predict_kwargs.setdefault('verbose', 0)
550
+ x, axes, axes_net, axes_net_div_by, _permute_axes, resizer, n_tiles, grid, grid_dict, channel, predict_direct, tiling_setup = \
551
+ self._predict_setup(img, axes, normalizer, n_tiles, show_tile_progress, predict_kwargs)
552
+
553
+ def _prep(prob, dist):
554
+ prob = np.take(prob,0,axis=channel)
555
+ dist = np.moveaxis(dist,channel,-1)
556
+ dist = np.maximum(1e-3, dist)
557
+ return prob, dist
558
+
559
+ proba, dista, pointsa, prob_class = [],[],[], []
560
+
561
+ if np.prod(n_tiles) > 1:
562
+ tile_generator, output_shape, create_empty_output = tiling_setup()
563
+
564
+ sh = list(output_shape)
565
+ sh[channel] = 1;
566
+
567
+ proba, dista, pointsa, prob_classa = [], [], [], []
568
+
569
+ for tile, s_src, s_dst in tile_generator:
570
+
571
+ results_tile = predict_direct(tile)
572
+
573
+ # account for grid
574
+ s_src = [slice(s.start//grid_dict.get(a,1),s.stop//grid_dict.get(a,1)) for s,a in zip(s_src,axes_net)]
575
+ s_dst = [slice(s.start//grid_dict.get(a,1),s.stop//grid_dict.get(a,1)) for s,a in zip(s_dst,axes_net)]
576
+ s_src[channel] = slice(None)
577
+ s_dst[channel] = slice(None)
578
+ s_src, s_dst = tuple(s_src), tuple(s_dst)
579
+
580
+ prob_tile, dist_tile = results_tile[:2]
581
+ prob_tile, dist_tile = _prep(prob_tile[s_src], dist_tile[s_src])
582
+
583
+ bs = list((b if s.start==0 else -1, b if s.stop==_sh else -1) for s,_sh in zip(s_dst, sh))
584
+ bs.pop(channel)
585
+ inds = _ind_prob_thresh(prob_tile, prob_thresh, b=bs)
586
+ proba.extend(prob_tile[inds].copy())
587
+ dista.extend(dist_tile[inds].copy())
588
+ _points = np.stack(np.where(inds), axis=1)
589
+ offset = list(s.start for i,s in enumerate(s_dst))
590
+ offset.pop(channel)
591
+ _points = _points + np.array(offset).reshape((1,len(offset)))
592
+ _points = _points * np.array(self.config.grid).reshape((1,len(self.config.grid)))
593
+ pointsa.extend(_points)
594
+
595
+ if self._is_multiclass():
596
+ p = results_tile[2][s_src].copy()
597
+ p = np.moveaxis(p,channel,-1)
598
+ prob_classa.extend(p[inds])
599
+ yield # yield None after each processed tile
600
+
601
+ else:
602
+ # predict_direct -> prob, dist, [prob_class if multi_class]
603
+ results = predict_direct(x)
604
+ prob, dist = results[:2]
605
+ prob, dist = _prep(prob, dist)
606
+ inds = _ind_prob_thresh(prob, prob_thresh, b=b)
607
+ proba = prob[inds].copy()
608
+ dista = dist[inds].copy()
609
+ _points = np.stack(np.where(inds), axis=1)
610
+ pointsa = (_points * np.array(self.config.grid).reshape((1,len(self.config.grid))))
611
+
612
+ if self._is_multiclass():
613
+ p = np.moveaxis(results[2],channel,-1)
614
+ prob_classa = p[inds].copy()
615
+
616
+
617
+ proba = np.asarray(proba)
618
+ dista = np.asarray(dista).reshape((-1,self.config.n_rays))
619
+ pointsa = np.asarray(pointsa).reshape((-1,self.config.n_dim))
620
+
621
+ idx = resizer.filter_points(x.ndim, pointsa, axes_net)
622
+ proba = proba[idx]
623
+ dista = dista[idx]
624
+ pointsa = pointsa[idx]
625
+
626
+ # last "yield" is the actual output that would have been "return"ed if this was a regular function
627
+ if self._is_multiclass():
628
+ prob_classa = np.asarray(prob_classa).reshape((-1,self.config.n_classes+1))
629
+ prob_classa = prob_classa[idx]
630
+ yield proba, dista, prob_classa, pointsa
631
+ else:
632
+ prob_classa = None
633
+ yield proba, dista, pointsa
634
+
635
+
636
+ @functools.wraps(_predict_sparse_generator)
637
+ def predict_sparse(self, *args, **kwargs):
638
+ # return last "yield"ed value of generator
639
+ r = None
640
+ for r in self._predict_sparse_generator(*args, **kwargs):
641
+ pass
642
+ return r
643
+
644
+
645
+ def _predict_instances_generator(self, img, axes=None, normalizer=None,
646
+ sparse=True,
647
+ prob_thresh=None, nms_thresh=None,
648
+ scale=None,
649
+ n_tiles=None, show_tile_progress=True,
650
+ verbose=False,
651
+ return_labels=True,
652
+ predict_kwargs=None, nms_kwargs=None,
653
+ overlap_label=None, return_predict=False):
654
+ """Predict instance segmentation from input image.
655
+
656
+ Parameters
657
+ ----------
658
+ img : :class:`numpy.ndarray`
659
+ Input image
660
+ axes : str or None
661
+ Axes of the input ``img``.
662
+ ``None`` denotes that axes of img are the same as denoted in the config.
663
+ normalizer : :class:`csbdeep.data.Normalizer` or None
664
+ (Optional) normalization of input image before prediction.
665
+ Note that the default (``None``) assumes ``img`` to be already normalized.
666
+ sparse: bool
667
+ If true, aggregate probabilities/distances sparsely during tiled
668
+ prediction to save memory (recommended).
669
+ prob_thresh : float or None
670
+ Consider only object candidates from pixels with predicted object probability
671
+ above this threshold (also see `optimize_thresholds`).
672
+ nms_thresh : float or None
673
+ Perform non-maximum suppression that considers two objects to be the same
674
+ when their area/surface overlap exceeds this threshold (also see `optimize_thresholds`).
675
+ scale: None or float or iterable
676
+ Scale the input image internally by this factor and rescale the output accordingly.
677
+ All spatial axes (X,Y,Z) will be scaled if a scalar value is provided.
678
+ Alternatively, multiple scale values (compatible with input `axes`) can be used
679
+ for more fine-grained control (scale values for non-spatial axes must be 1).
680
+ n_tiles : iterable or None
681
+ Out of memory (OOM) errors can occur if the input image is too large.
682
+ To avoid this problem, the input image is broken up into (overlapping) tiles
683
+ that are processed independently and re-assembled.
684
+ This parameter denotes a tuple of the number of tiles for every image axis (see ``axes``).
685
+ ``None`` denotes that no tiling should be used.
686
+ show_tile_progress: bool
687
+ Whether to show progress during tiled prediction.
688
+ verbose: bool
689
+ Whether to print some info messages.
690
+ return_labels: bool
691
+ Whether to create a label image, otherwise return None in its place.
692
+ predict_kwargs: dict
693
+ Keyword arguments for ``predict`` function of Keras model.
694
+ nms_kwargs: dict
695
+ Keyword arguments for non-maximum suppression.
696
+ overlap_label: scalar or None
697
+ if not None, label the regions where polygons overlap with that value
698
+ return_predict: bool
699
+ Also return the outputs of :func:`predict` (in a separate tuple)
700
+ If True, implies sparse = False
701
+
702
+ Returns
703
+ -------
704
+ (:class:`numpy.ndarray`, dict), (optional: return tuple of :func:`predict`)
705
+ Returns a tuple of the label instances image and also
706
+ a dictionary with the details (coordinates, etc.) of all remaining polygons/polyhedra.
707
+
708
+ """
709
+ if predict_kwargs is None:
710
+ predict_kwargs = {}
711
+ if nms_kwargs is None:
712
+ nms_kwargs = {}
713
+
714
+ if return_predict and sparse:
715
+ sparse = False
716
+ warnings.warn("Setting sparse to False because return_predict is True")
717
+
718
+ nms_kwargs.setdefault("verbose", verbose)
719
+
720
+ _axes = self._normalize_axes(img, axes)
721
+ _axes_net = self.config.axes
722
+ _permute_axes = self._make_permute_axes(_axes, _axes_net)
723
+ _shape_inst = tuple(s for s,a in zip(_permute_axes(img).shape, _axes_net) if a != 'C')
724
+
725
+ if scale is not None:
726
+ if isinstance(scale, numbers.Number):
727
+ scale = tuple(scale if a in 'XYZ' else 1 for a in _axes)
728
+ scale = tuple(scale)
729
+ len(scale) == len(_axes) or _raise(ValueError(f"scale {scale} must be of length {len(_axes)}, i.e. one value for each of the axes {_axes}"))
730
+ for s,a in zip(scale,_axes):
731
+ s > 0 or _raise(ValueError("scale values must be greater than 0"))
732
+ (s in (1,None) or a in 'XYZ') or warnings.warn(f"replacing scale value {s} for non-spatial axis {a} with 1")
733
+ scale = tuple(s if a in 'XYZ' else 1 for s,a in zip(scale,_axes))
734
+ verbose and print(f"scaling image by factors {scale} for axes {_axes}")
735
+ img = ndi.zoom(img, scale, order=1)
736
+
737
+ yield 'predict' # indicate that prediction is starting
738
+ res = None
739
+ if sparse:
740
+ for res in self._predict_sparse_generator(img, axes=axes, normalizer=normalizer, n_tiles=n_tiles,
741
+ prob_thresh=prob_thresh, show_tile_progress=show_tile_progress, **predict_kwargs):
742
+ if res is None:
743
+ yield 'tile' # yield 'tile' each time a tile has been processed
744
+ else:
745
+ for res in self._predict_generator(img, axes=axes, normalizer=normalizer, n_tiles=n_tiles,
746
+ show_tile_progress=show_tile_progress, **predict_kwargs):
747
+ if res is None:
748
+ yield 'tile' # yield 'tile' each time a tile has been processed
749
+ res = tuple(res) + (None,)
750
+
751
+ if self._is_multiclass():
752
+ prob, dist, prob_class, points = res
753
+ else:
754
+ prob, dist, points = res
755
+ prob_class = None
756
+
757
+ yield 'nms' # indicate that non-maximum suppression is starting
758
+ res_instances = self._instances_from_prediction(_shape_inst, prob, dist,
759
+ points=points,
760
+ prob_class=prob_class,
761
+ prob_thresh=prob_thresh,
762
+ nms_thresh=nms_thresh,
763
+ scale=(None if scale is None else dict(zip(_axes,scale))),
764
+ return_labels=return_labels,
765
+ overlap_label=overlap_label,
766
+ **nms_kwargs)
767
+
768
+ # last "yield" is the actual output that would have been "return"ed if this was a regular function
769
+ if return_predict:
770
+ yield res_instances, tuple(res[:-1])
771
+ else:
772
+ yield res_instances
773
+
774
+
775
+ @functools.wraps(_predict_instances_generator)
776
+ def predict_instances(self, *args, **kwargs):
777
+ # the reason why the actual computation happens as a generator function
778
+ # (in '_predict_instances_generator') is that the generator is called
779
+ # from the stardist napari plugin, which has its benefits regarding
780
+ # control flow and progress display. however, typical use cases should
781
+ # almost always use this function ('predict_instances'), and shouldn't
782
+ # even notice (thanks to @functools.wraps) that it wraps the generator
783
+ # function. note that similar reasoning applies to 'predict' and
784
+ # 'predict_sparse'.
785
+
786
+ # return last "yield"ed value of generator
787
+ r = None
788
+ for r in self._predict_instances_generator(*args, **kwargs):
789
+ pass
790
+ return r
791
+
792
+
793
+ # def _predict_instances_old(self, img, axes=None, normalizer=None,
794
+ # sparse = False,
795
+ # prob_thresh=None, nms_thresh=None,
796
+ # n_tiles=None, show_tile_progress=True,
797
+ # verbose = False,
798
+ # predict_kwargs=None, nms_kwargs=None, overlap_label=None):
799
+ # """
800
+ # old version, should be removed....
801
+ # """
802
+ # if predict_kwargs is None:
803
+ # predict_kwargs = {}
804
+ # if nms_kwargs is None:
805
+ # nms_kwargs = {}
806
+
807
+ # nms_kwargs.setdefault("verbose", verbose)
808
+
809
+ # _axes = self._normalize_axes(img, axes)
810
+ # _axes_net = self.config.axes
811
+ # _permute_axes = self._make_permute_axes(_axes, _axes_net)
812
+ # _shape_inst = tuple(s for s,a in zip(_permute_axes(img).shape, _axes_net) if a != 'C')
813
+
814
+
815
+ # res = self.predict(img, axes=axes, normalizer=normalizer,
816
+ # n_tiles=n_tiles,
817
+ # show_tile_progress=show_tile_progress,
818
+ # **predict_kwargs)
819
+
820
+ # res = tuple(res) + (None,)
821
+
822
+ # if self._is_multiclass():
823
+ # prob, dist, prob_class, points = res
824
+ # else:
825
+ # prob, dist, points = res
826
+ # prob_class = None
827
+
828
+
829
+ # return self._instances_from_prediction_old(_shape_inst, prob, dist,
830
+ # points = points,
831
+ # prob_class = prob_class,
832
+ # prob_thresh=prob_thresh,
833
+ # nms_thresh=nms_thresh,
834
+ # overlap_label=overlap_label,
835
+ # **nms_kwargs)
836
+
837
+
838
+ def predict_instances_big(self, img, axes, block_size, min_overlap, context=None,
839
+ labels_out=None, labels_out_dtype=np.int32, show_progress=True, **kwargs):
840
+ """Predict instance segmentation from very large input images.
841
+
842
+ Intended to be used when `predict_instances` cannot be used due to memory limitations.
843
+ This function will break the input image into blocks and process them individually
844
+ via `predict_instances` and assemble all the partial results. If used as intended, the result
845
+ should be the same as if `predict_instances` was used directly on the whole image.
846
+
847
+ **Important**: The crucial assumption is that all predicted object instances are smaller than
848
+ the provided `min_overlap`. Also, it must hold that: min_overlap + 2*context < block_size.
849
+
850
+ Example
851
+ -------
852
+ >>> img.shape
853
+ (20000, 20000)
854
+ >>> labels, polys = model.predict_instances_big(img, axes='YX', block_size=4096,
855
+ min_overlap=128, context=128, n_tiles=(4,4))
856
+
857
+ Parameters
858
+ ----------
859
+ img: :class:`numpy.ndarray` or similar
860
+ Input image
861
+ axes: str
862
+ Axes of the input ``img`` (such as 'YX', 'ZYX', 'YXC', etc.)
863
+ block_size: int or iterable of int
864
+ Process input image in blocks of the provided shape.
865
+ (If a scalar value is given, it is used for all spatial image dimensions.)
866
+ min_overlap: int or iterable of int
867
+ Amount of guaranteed overlap between blocks.
868
+ (If a scalar value is given, it is used for all spatial image dimensions.)
869
+ context: int or iterable of int, or None
870
+ Amount of image context on all sides of a block, which is discarded.
871
+ If None, uses an automatic estimate that should work in many cases.
872
+ (If a scalar value is given, it is used for all spatial image dimensions.)
873
+ labels_out: :class:`numpy.ndarray` or similar, or None, or False
874
+ numpy array or similar (must be of correct shape) to which the label image is written.
875
+ If None, will allocate a numpy array of the correct shape and data type ``labels_out_dtype``.
876
+ If False, will not write the label image (useful if only the dictionary is needed).
877
+ labels_out_dtype: str or dtype
878
+ Data type of returned label image if ``labels_out=None`` (has no effect otherwise).
879
+ show_progress: bool
880
+ Show progress bar for block processing.
881
+ kwargs: dict
882
+ Keyword arguments for ``predict_instances``.
883
+
884
+ Returns
885
+ -------
886
+ (:class:`numpy.ndarray` or False, dict)
887
+ Returns the label image and a dictionary with the details (coordinates, etc.) of the polygons/polyhedra.
888
+
889
+ """
890
+ from ..big import _grid_divisible, BlockND, OBJECT_KEYS#, repaint_labels
891
+ from ..matching import relabel_sequential
892
+
893
+ n = img.ndim
894
+ axes = axes_check_and_normalize(axes, length=n)
895
+ grid = self._axes_div_by(axes)
896
+ axes_out = self._axes_out.replace('C','')
897
+ shape_dict = dict(zip(axes,img.shape))
898
+ shape_out = tuple(shape_dict[a] for a in axes_out)
899
+
900
+ if context is None:
901
+ context = self._axes_tile_overlap(axes)
902
+
903
+ if np.isscalar(block_size): block_size = n*[block_size]
904
+ if np.isscalar(min_overlap): min_overlap = n*[min_overlap]
905
+ if np.isscalar(context): context = n*[context]
906
+ block_size, min_overlap, context = list(block_size), list(min_overlap), list(context)
907
+ assert n == len(block_size) == len(min_overlap) == len(context)
908
+
909
+ if 'C' in axes:
910
+ # single block for channel axis
911
+ i = axes_dict(axes)['C']
912
+ # if (block_size[i], min_overlap[i], context[i]) != (None, None, None):
913
+ # print("Ignoring values of 'block_size', 'min_overlap', and 'context' for channel axis " +
914
+ # "(set to 'None' to avoid this warning).", file=sys.stderr, flush=True)
915
+ block_size[i] = img.shape[i]
916
+ min_overlap[i] = context[i] = 0
917
+
918
+ block_size = tuple(_grid_divisible(g, v, name='block_size', verbose=False) for v,g,a in zip(block_size, grid,axes))
919
+ min_overlap = tuple(_grid_divisible(g, v, name='min_overlap', verbose=False) for v,g,a in zip(min_overlap,grid,axes))
920
+ context = tuple(_grid_divisible(g, v, name='context', verbose=False) for v,g,a in zip(context, grid,axes))
921
+
922
+ # print(f"input: shape {img.shape} with axes {axes}")
923
+ print(f'effective: block_size={block_size}, min_overlap={min_overlap}, context={context}', flush=True)
924
+
925
+ for a,c,o in zip(axes,context,self._axes_tile_overlap(axes)):
926
+ if c < o:
927
+ print(f"{a}: context of {c} is small, recommended to use at least {o}", flush=True)
928
+
929
+ # create block cover
930
+ blocks = BlockND.cover(img.shape, axes, block_size, min_overlap, context, grid)
931
+
932
+ if np.isscalar(labels_out) and bool(labels_out) is False:
933
+ labels_out = None
934
+ else:
935
+ if labels_out is None:
936
+ labels_out = np.zeros(shape_out, dtype=labels_out_dtype)
937
+ else:
938
+ labels_out.shape == shape_out or _raise(ValueError(f"'labels_out' must have shape {shape_out} (axes {axes_out})."))
939
+
940
+ polys_all = {}
941
+ # problem_ids = []
942
+ label_offset = 1
943
+
944
+ kwargs_override = dict(axes=axes, overlap_label=None, return_labels=True, return_predict=False)
945
+ if show_progress:
946
+ kwargs_override['show_tile_progress'] = False # disable progress for predict_instances
947
+ for k,v in kwargs_override.items():
948
+ if k in kwargs: print(f"changing '{k}' from {kwargs[k]} to {v}", flush=True)
949
+ kwargs[k] = v
950
+
951
+ blocks = tqdm(blocks, disable=(not show_progress))
952
+ # actual computation
953
+ for block in blocks:
954
+ labels, polys = self.predict_instances(block.read(img, axes=axes), **kwargs)
955
+ labels = block.crop_context(labels, axes=axes_out)
956
+ labels, polys = block.filter_objects(labels, polys, axes=axes_out)
957
+ # TODO: relabel_sequential is not very memory-efficient (will allocate memory proportional to label_offset)
958
+ # this should not change the order of labels
959
+ labels = relabel_sequential(labels, label_offset)[0]
960
+
961
+ # labels, fwd_map, _ = relabel_sequential(labels, label_offset)
962
+ # if len(incomplete) > 0:
963
+ # problem_ids.extend([fwd_map[i] for i in incomplete])
964
+ # if show_progress:
965
+ # blocks.set_postfix_str(f"found {len(problem_ids)} problematic {'object' if len(problem_ids)==1 else 'objects'}")
966
+ if labels_out is not None:
967
+ block.write(labels_out, labels, axes=axes_out)
968
+
969
+ for k,v in polys.items():
970
+ polys_all.setdefault(k,[]).append(v)
971
+
972
+ label_offset += len(polys['prob'])
973
+ del labels
974
+
975
+ polys_all = {k: (np.concatenate(v) if k in OBJECT_KEYS else v[0]) for k,v in polys_all.items()}
976
+
977
+ # if labels_out is not None and len(problem_ids) > 0:
978
+ # # if show_progress:
979
+ # # blocks.write('')
980
+ # # print(f"Found {len(problem_ids)} objects that violate the 'min_overlap' assumption.", file=sys.stderr, flush=True)
981
+ # repaint_labels(labels_out, problem_ids, polys_all, show_progress=False)
982
+
983
+ return labels_out, polys_all#, tuple(problem_ids)
984
+
985
+
986
+ def optimize_thresholds(self, X_val, Y_val, nms_threshs=[0.3,0.4,0.5], iou_threshs=[0.3,0.5,0.7], predict_kwargs=None, optimize_kwargs=None, save_to_json=True):
987
+ """Optimize two thresholds (probability, NMS overlap) necessary for predicting object instances.
988
+
989
+ Note that the default thresholds yield good results in many cases, but optimizing
990
+ the thresholds for a particular dataset can further improve performance.
991
+
992
+ The optimized thresholds are automatically used for all further predictions
993
+ and also written to the model directory.
994
+
995
+ See ``utils.optimize_threshold`` for details and possible choices for ``optimize_kwargs``.
996
+
997
+ Parameters
998
+ ----------
999
+ X_val : list of ndarray
1000
+ (Validation) input images (must be normalized) to use for threshold tuning.
1001
+ Y_val : list of ndarray
1002
+ (Validation) label images to use for threshold tuning.
1003
+ nms_threshs : list of float
1004
+ List of overlap thresholds to be considered for NMS.
1005
+ For each value in this list, optimization is run to find a corresponding prob_thresh value.
1006
+ iou_threshs : list of float
1007
+ List of intersection over union (IOU) thresholds for which
1008
+ the (average) matching performance is considered to tune the thresholds.
1009
+ predict_kwargs: dict
1010
+ Keyword arguments for ``predict`` function of this class.
1011
+ (If not provided, will guess value for `n_tiles` to prevent out of memory errors.)
1012
+ optimize_kwargs: dict
1013
+ Keyword arguments for ``utils.optimize_threshold`` function.
1014
+
1015
+ """
1016
+ if predict_kwargs is None:
1017
+ predict_kwargs = {}
1018
+ if optimize_kwargs is None:
1019
+ optimize_kwargs = {}
1020
+
1021
+ def _predict_kwargs(x):
1022
+ if 'n_tiles' in predict_kwargs:
1023
+ return predict_kwargs
1024
+ else:
1025
+ return {**predict_kwargs, 'n_tiles': self._guess_n_tiles(x), 'show_tile_progress': False}
1026
+
1027
+ # only take first two elements of predict in case multi class is activated
1028
+ Yhat_val = [self.predict(x, **_predict_kwargs(x))[:2] for x in X_val]
1029
+
1030
+ opt_prob_thresh, opt_measure, opt_nms_thresh = None, -np.inf, None
1031
+ for _opt_nms_thresh in nms_threshs:
1032
+ _opt_prob_thresh, _opt_measure = optimize_threshold(Y_val, Yhat_val, model=self, nms_thresh=_opt_nms_thresh, iou_threshs=iou_threshs, **optimize_kwargs)
1033
+ if _opt_measure > opt_measure:
1034
+ opt_prob_thresh, opt_measure, opt_nms_thresh = _opt_prob_thresh, _opt_measure, _opt_nms_thresh
1035
+ opt_threshs = dict(prob=float(opt_prob_thresh), nms=float(opt_nms_thresh))
1036
+
1037
+ self.thresholds = opt_threshs
1038
+ print(end='', file=sys.stderr, flush=True)
1039
+ print("Using optimized values: prob_thresh={prob:g}, nms_thresh={nms:g}.".format(prob=self.thresholds.prob, nms=self.thresholds.nms))
1040
+ if save_to_json and self.basedir is not None:
1041
+ print("Saving to 'thresholds.json'.")
1042
+ save_json(opt_threshs, str(self.logdir / 'thresholds.json'))
1043
+ return opt_threshs
1044
+
1045
+
1046
+ def _guess_n_tiles(self, img):
1047
+ axes = self._normalize_axes(img, axes=None)
1048
+ shape = list(img.shape)
1049
+ if 'C' in axes:
1050
+ del shape[axes_dict(axes)['C']]
1051
+ b = self.config.train_batch_size**(1.0/self.config.n_dim)
1052
+ n_tiles = [int(np.ceil(s/(p*b))) for s,p in zip(shape,self.config.train_patch_size)]
1053
+ if 'C' in axes:
1054
+ n_tiles.insert(axes_dict(axes)['C'],1)
1055
+ return tuple(n_tiles)
1056
+
1057
+
1058
+ def _normalize_axes(self, img, axes):
1059
+ if axes is None:
1060
+ axes = self.config.axes
1061
+ assert 'C' in axes
1062
+ if img.ndim == len(axes)-1 and self.config.n_channel_in == 1:
1063
+ # img has no dedicated channel axis, but 'C' always part of config axes
1064
+ axes = axes.replace('C','')
1065
+ return axes_check_and_normalize(axes, img.ndim)
1066
+
1067
+
1068
+ def _compute_receptive_field(self, img_size=None, keras_model=None):
1069
+ # TODO: good enough?
1070
+ from scipy.ndimage import zoom
1071
+ if img_size is None:
1072
+ img_size = tuple(g*(128 if self.config.n_dim==2 else 64) for g in self.config.grid)
1073
+ if keras_model is None:
1074
+ keras_model = self.keras_model
1075
+ if np.isscalar(img_size):
1076
+ img_size = (img_size,) * self.config.n_dim
1077
+ img_size = tuple(img_size)
1078
+ # print(img_size)
1079
+ assert all(_is_power_of_2(s) for s in img_size)
1080
+ mid = tuple(s//2 for s in img_size)
1081
+ x = np.zeros((1,)+img_size+(self.config.n_channel_in,), dtype=np.float32)
1082
+ z = np.zeros_like(x)
1083
+ x[(0,)+mid+(slice(None),)] = 1
1084
+ y = keras_model.predict(x, verbose=0)[0][0,...,0]
1085
+ y0 = keras_model.predict(z, verbose=0)[0][0,...,0]
1086
+ grid = tuple((np.array(x.shape[1:-1])/np.array(y.shape)).astype(int))
1087
+ assert grid == self.config.grid
1088
+ y = zoom(y, grid,order=0)
1089
+ y0 = zoom(y0,grid,order=0)
1090
+ ind = np.where(np.abs(y-y0)>0)
1091
+ if any(len(i)==0 for i in ind):
1092
+ import contextlib, io
1093
+ with contextlib.redirect_stdout(io.StringIO()) as _:
1094
+ keras_model_untrained = type(self)(self.config,basedir=None).keras_model
1095
+ return self._compute_receptive_field(img_size=img_size, keras_model=keras_model_untrained)
1096
+ else:
1097
+ return [(m-np.min(i), np.max(i)-m) for (m,i) in zip(mid,ind)]
1098
+
1099
+
1100
+ def _axes_tile_overlap(self, query_axes):
1101
+ query_axes = axes_check_and_normalize(query_axes)
1102
+ try:
1103
+ self._tile_overlap
1104
+ except AttributeError:
1105
+ self._tile_overlap = self._compute_receptive_field()
1106
+ overlap = dict(zip(
1107
+ self.config.axes.replace('C',''),
1108
+ tuple(max(rf) for rf in self._tile_overlap)
1109
+ ))
1110
+ return tuple(overlap.get(a,0) for a in query_axes)
1111
+
1112
+
1113
+ def export_TF(self, fname=None, single_output=True, upsample_grid=True):
1114
+ """Export model to TensorFlow's SavedModel format that can be used e.g. in the Fiji plugin
1115
+
1116
+ Parameters
1117
+ ----------
1118
+ fname : str
1119
+ Path of the zip file to store the model
1120
+ If None, the default path "<modeldir>/TF_SavedModel.zip" is used
1121
+ single_output: bool
1122
+ If set, concatenates the two model outputs into a single output (note: this is currently mandatory for further use in Fiji)
1123
+ upsample_grid: bool
1124
+ If set, upsamples the output to the input shape (note: this is currently mandatory for further use in Fiji)
1125
+ """
1126
+ Concatenate, UpSampling2D, UpSampling3D, Conv2DTranspose, Conv3DTranspose = keras_import('layers', 'Concatenate', 'UpSampling2D', 'UpSampling3D', 'Conv2DTranspose', 'Conv3DTranspose')
1127
+ Model = keras_import('models', 'Model')
1128
+
1129
+ if self.basedir is None and fname is None:
1130
+ raise ValueError("Need explicit 'fname', since model directory not available (basedir=None).")
1131
+
1132
+ if self._is_multiclass():
1133
+ warnings.warn("multi-class mode not supported yet, removing classification output from exported model")
1134
+
1135
+ grid = self.config.grid
1136
+ prob = self.keras_model.outputs[0]
1137
+ dist = self.keras_model.outputs[1]
1138
+ assert self.config.n_dim in (2,3)
1139
+
1140
+ if upsample_grid and any(g>1 for g in grid):
1141
+ # CSBDeep Fiji plugin needs same size input/output
1142
+ # -> we need to upsample the outputs if grid > (1,1)
1143
+ # note: upsampling prob with a transposed convolution creates sparse
1144
+ # prob output with less candidates than with standard upsampling
1145
+ conv_transpose = Conv2DTranspose if self.config.n_dim==2 else Conv3DTranspose
1146
+ upsampling = UpSampling2D if self.config.n_dim==2 else UpSampling3D
1147
+ prob = conv_transpose(1, (1,)*self.config.n_dim,
1148
+ strides=grid, padding='same',
1149
+ kernel_initializer='ones', use_bias=False)(prob)
1150
+ dist = upsampling(grid)(dist)
1151
+
1152
+ inputs = self.keras_model.inputs[0]
1153
+ outputs = Concatenate()([prob,dist]) if single_output else [prob,dist]
1154
+ csbdeep_model = Model(inputs, outputs)
1155
+
1156
+ fname = (self.logdir / 'TF_SavedModel.zip') if fname is None else Path(fname)
1157
+ export_SavedModel(csbdeep_model, str(fname))
1158
+ return csbdeep_model
1159
+
1160
+
1161
+
1162
+ class StarDistPadAndCropResizer(Resizer):
1163
+
1164
+ # TODO: check correctness
1165
+ def __init__(self, grid, mode='reflect', **kwargs):
1166
+ assert isinstance(grid, dict)
1167
+ self.mode = mode
1168
+ self.grid = grid
1169
+ self.kwargs = kwargs
1170
+
1171
+
1172
+ def before(self, x, axes, axes_div_by):
1173
+ assert all(a%g==0 for g,a in zip((self.grid.get(a,1) for a in axes), axes_div_by))
1174
+ axes = axes_check_and_normalize(axes,x.ndim)
1175
+ def _split(v):
1176
+ return 0, v # only pad at the end
1177
+ self.pad = {
1178
+ a : _split((div_n-s%div_n)%div_n)
1179
+ for a, div_n, s in zip(axes, axes_div_by, x.shape)
1180
+ }
1181
+ x_pad = np.pad(x, tuple(self.pad[a] for a in axes), mode=self.mode, **self.kwargs)
1182
+ self.padded_shape = dict(zip(axes,x_pad.shape))
1183
+ if 'C' in self.padded_shape: del self.padded_shape['C']
1184
+ return x_pad
1185
+
1186
+
1187
+ def after(self, x, axes):
1188
+ # axes can include 'C', which may not have been present in before()
1189
+ axes = axes_check_and_normalize(axes,x.ndim)
1190
+ assert all(s_pad == s * g for s,s_pad,g in zip(x.shape,
1191
+ (self.padded_shape.get(a,_s) for a,_s in zip(axes,x.shape)),
1192
+ (self.grid.get(a,1) for a in axes)))
1193
+ # print(self.padded_shape)
1194
+ # print(self.pad)
1195
+ # print(self.grid)
1196
+ crop = tuple (
1197
+ slice(0, -(math.floor(p[1]/g)) if p[1]>=g else None)
1198
+ for p,g in zip((self.pad.get(a,(0,0)) for a in axes),(self.grid.get(a,1) for a in axes))
1199
+ )
1200
+ # print(crop)
1201
+ return x[crop]
1202
+
1203
+
1204
+ def filter_points(self, ndim, points, axes):
1205
+ """ returns indices of points inside crop region """
1206
+ assert points.ndim==2
1207
+ axes = axes_check_and_normalize(axes,ndim)
1208
+
1209
+ bounds = np.array(tuple(self.padded_shape[a]-self.pad[a][1] for a in axes if a.lower() in ('z','y','x')))
1210
+ idx = np.where(np.all(points< bounds, 1))
1211
+ return idx
1212
+
1213
+
1214
+
1215
+ def _tf_version_at_least(version_string="1.0.0"):
1216
+ from packaging import version
1217
+ return version.parse(tf.__version__) >= version.parse(version_string)