-
-
Notifications
You must be signed in to change notification settings - Fork 410
/
labels.py
1521 lines (1336 loc) · 53.1 KB
/
labels.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
from collections import deque
from contextlib import contextmanager
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
from scipy import ndimage as ndi
from napari.layers.base import no_op
from napari.layers.image._image_utils import guess_multiscale
from napari.layers.image.image import _ImageBase
from napari.layers.labels._labels_constants import (
LabelColorMode,
LabelsRendering,
Mode,
)
from napari.layers.labels._labels_mouse_bindings import draw, pick
from napari.layers.labels._labels_utils import (
indices_in_shape,
interpolate_coordinates,
sphere_indices,
)
from napari.layers.utils.color_transformations import transform_color
from napari.layers.utils.layer_utils import _FeatureTable
from napari.utils import config
from napari.utils._dtype import normalize_dtype
from napari.utils.colormaps import (
color_dict_to_colormap,
label_colormap,
low_discrepancy_image,
)
from napari.utils.events import Event
from napari.utils.events.custom_types import Array
from napari.utils.geometry import clamp_point_to_bounding_box
from napari.utils.misc import _is_array_type
from napari.utils.naming import magic_name
from napari.utils.status_messages import generate_layer_coords_status
from napari.utils.translations import trans
class Labels(_ImageBase):
"""Labels (or segmentation) layer.
An image-like layer where every pixel contains an integer ID
corresponding to the region it belongs to.
Parameters
----------
data : array or list of array
Labels data as an array or multiscale. Must be integer type or bools.
Please note multiscale rendering is only supported in 2D. In 3D, only
the lowest resolution scale is displayed.
num_colors : int
Number of unique colors to use in colormap.
features : dict[str, array-like] or DataFrame
Features table where each row corresponds to a label and each column
is a feature. The first row corresponds to the background label.
properties : dict {str: array (N,)} or DataFrame
Properties for each label. Each property should be an array of length
N, where N is the number of labels, and the first property corresponds
to background.
color : dict of int to str or array
Custom label to color mapping. Values must be valid color names or RGBA
arrays.
seed : float
Seed for colormap random generator.
name : str
Name of the layer.
metadata : dict
Layer metadata.
scale : tuple of float
Scale factors for the layer.
translate : tuple of float
Translation values for the layer.
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,
pitch, roll convention. Otherwise assume an nD rotation. Angles are
assumed to be in degrees. They can be converted from radians with
np.degrees if needed.
shear : 1-D array or n-D array
Either a vector of upper triangular values, or an nD shear matrix with
ones along the main diagonal.
affine : n-D array or napari.utils.transforms.Affine
(N+1, N+1) affine transformation matrix in homogeneous coordinates.
The first (N, N) entries correspond to a linear transform and
the final column is a length N translation vector and a 1 or a napari
`Affine` transform object. Applied as an extra transform on top of the
provided scale, rotate, and shear values.
opacity : float
Opacity of the layer visual, between 0.0 and 1.0.
blending : str
One of a list of preset blending modes that determines how RGB and
alpha values of the layer visual get mixed. Allowed values are
{'opaque', 'translucent', and 'additive'}.
rendering : str
3D Rendering mode used by vispy. Must be one {'translucent', 'iso_categorical'}.
'translucent' renders without lighting. 'iso_categorical' uses isosurface
rendering to calculate lighting effects on labeled surfaces.
The default value is 'iso_categorical'.
depiction : str
3D Depiction mode. Must be one of {'volume', 'plane'}.
The default value is 'volume'.
visible : bool
Whether the layer visual is currently being displayed.
multiscale : bool
Whether the data is a multiscale image or not. Multiscale data is
represented by a list of array like image data. If not specified by
the user and if the data is a list of arrays that decrease in shape
then it will be taken to be multiscale. The first image in the list
should be the largest. Please note multiscale rendering is only
supported in 2D. In 3D, only the lowest resolution scale is
displayed.
cache : bool
Whether slices of out-of-core datasets should be cached upon retrieval.
Currently, this only applies to dask arrays.
plane : dict or SlicingPlane
Properties defining plane rendering in 3D. Properties are defined in
data coordinates. Valid dictionary keys are
{'position', 'normal', 'thickness', and 'enabled'}.
experimental_clipping_planes : list of dicts, list of ClippingPlane, or ClippingPlaneList
Each dict defines a clipping plane in 3D in data coordinates.
Valid dictionary keys are {'position', 'normal', and 'enabled'}.
Values on the negative side of the normal are discarded if the plane is enabled.
Attributes
----------
data : array or list of array
Integer label data as an array or multiscale. Can be N dimensional.
Every pixel contains an integer ID corresponding to the region it
belongs to. The label 0 is rendered as transparent. Please note
multiscale rendering is only supported in 2D. In 3D, only
the lowest resolution scale is displayed.
multiscale : bool
Whether the data is a multiscale image or not. Multiscale data is
represented by a list of array like image data. The first image in the
list should be the largest. Please note multiscale rendering is only
supported in 2D. In 3D, only the lowest resolution scale is
displayed.
metadata : dict
Labels metadata.
num_colors : int
Number of unique colors to use in colormap.
features : Dataframe-like
Features table where each row corresponds to a label and each column
is a feature. The first row corresponds to the background label.
properties : dict {str: array (N,)}, DataFrame
Properties for each label. Each property should be an array of length
N, where N is the number of labels, and the first property corresponds
to background.
color : dict of int to str or array
Custom label to color mapping. Values must be valid color names or RGBA
arrays. While there is no limit to the number of custom labels, the
the layer will render incorrectly if they map to more than 1024 distinct
colors.
seed : float
Seed for colormap random generator.
opacity : float
Opacity of the labels, must be between 0 and 1.
contiguous : bool
If `True`, the fill bucket changes only connected pixels of same label.
n_edit_dimensions : int
The number of dimensions across which labels will be edited.
contour : int
If greater than 0, displays contours of labels instead of shaded regions
with a thickness equal to its value.
brush_size : float
Size of the paint brush in data coordinates.
selected_label : int
Index of selected label. Can be greater than the current maximum label.
mode : str
Interactive mode. The normal, default mode is PAN_ZOOM, which
allows for normal interactivity with the canvas.
In PICK mode the cursor functions like a color picker, setting the
clicked on label to be the current label. If the background is picked it
will select the background label `0`.
In PAINT mode the cursor functions like a paint brush changing any
pixels it brushes over to the current label. If the background label
`0` is selected than any pixels will be changed to background and this
tool functions like an eraser. The size and shape of the cursor can be
adjusted in the properties widget.
In FILL mode the cursor functions like a fill bucket replacing pixels
of the label clicked on with the current label. It can either replace
all pixels of that label or just those that are contiguous with the
clicked on pixel. If the background label `0` is selected than any
pixels will be changed to background and this tool functions like an
eraser.
In ERASE mode the cursor functions similarly to PAINT mode, but to
paint with background label, which effectively removes the label.
plane : SlicingPlane
Properties defining plane rendering in 3D.
experimental_clipping_planes : ClippingPlaneList
Clipping planes defined in data coordinates, used to clip the volume.
Notes
-----
_selected_color : 4-tuple or None
RGBA tuple of the color of the selected label, or None if the
background label `0` is selected.
"""
_history_limit = 100
def __init__(
self,
data,
*,
num_colors=50,
features=None,
properties=None,
color=None,
seed=0.5,
name=None,
metadata=None,
scale=None,
translate=None,
rotate=None,
shear=None,
affine=None,
opacity=0.7,
blending='translucent',
rendering='iso_categorical',
depiction='volume',
visible=True,
multiscale=None,
cache=True,
plane=None,
experimental_clipping_planes=None,
):
if name is None and data is not None:
name = magic_name(data)
self._seed = seed
self._background_label = 0
self._num_colors = num_colors
self._random_colormap = label_colormap(self.num_colors)
self._all_vals = np.array([], dtype=float)
self._color_mode = LabelColorMode.AUTO
self._show_selected_label = False
self._contour = 0
data = self._ensure_int_labels(data)
self._color_lookup_func = None
super().__init__(
data,
rgb=False,
colormap=self._random_colormap,
contrast_limits=[0.0, 1.0],
interpolation2d='nearest',
interpolation3d='nearest',
rendering=rendering,
depiction=depiction,
iso_threshold=0,
name=name,
metadata=metadata,
scale=scale,
translate=translate,
rotate=rotate,
shear=shear,
affine=affine,
opacity=opacity,
blending=blending,
visible=visible,
multiscale=multiscale,
cache=cache,
plane=plane,
experimental_clipping_planes=experimental_clipping_planes,
)
self.events.add(
preserve_labels=Event,
properties=Event,
n_edit_dimensions=Event,
contiguous=Event,
brush_size=Event,
selected_label=Event,
color_mode=Event,
brush_shape=Event,
contour=Event,
features=Event,
paint=Event,
)
self._feature_table = _FeatureTable.from_layer(
features=features, properties=properties
)
self._label_index = self._make_label_index()
self._n_edit_dimensions = 2
self._contiguous = True
self._brush_size = 10
self._selected_label = 1
self._selected_color = self.get_color(self._selected_label)
self.color = color
self._mode = Mode.PAN_ZOOM
self._status = self.mode
self._preserve_labels = False
self._reset_history()
# Trigger generation of view slice and thumbnail
self.refresh()
self._set_editable()
@property
def rendering(self):
"""Return current rendering mode.
Selects a preset rendering mode in vispy that determines how
lablels are displayed. Options include:
* ``translucent``: voxel colors are blended along the view ray until
the result is opaque.
* ``iso_categorical``: isosurface for categorical data.
Cast a ray until a non-background value is encountered. At that
location, lighning calculations are performed to give the visual
appearance of a surface.
Returns
-------
str
The current rendering mode
"""
return str(self._rendering)
@rendering.setter
def rendering(self, rendering):
self._rendering = LabelsRendering(rendering)
self.events.rendering()
@property
def contiguous(self):
"""bool: fill bucket changes only connected pixels of same label."""
return self._contiguous
@contiguous.setter
def contiguous(self, contiguous):
self._contiguous = contiguous
self.events.contiguous()
@property
def n_edit_dimensions(self):
return self._n_edit_dimensions
@n_edit_dimensions.setter
def n_edit_dimensions(self, n_edit_dimensions):
self._n_edit_dimensions = n_edit_dimensions
self.events.n_edit_dimensions()
@property
def contour(self):
"""int: displays contours of labels instead of shaded regions."""
return self._contour
@contour.setter
def contour(self, contour):
self._contour = contour
self.events.contour()
self.refresh()
@property
def brush_size(self):
"""float: Size of the paint in world coordinates."""
return self._brush_size
@brush_size.setter
def brush_size(self, brush_size):
self._brush_size = int(brush_size)
self.cursor_size = self._calculate_cursor_size()
self.events.brush_size()
def _calculate_cursor_size(self):
# Convert from brush size in data coordinates to
# cursor size in world coordinates
scale = self._data_to_world.scale
min_scale = np.min(
[abs(scale[d]) for d in self._slice_input.displayed]
)
return abs(self.brush_size * min_scale)
@property
def seed(self):
"""float: Seed for colormap random generator."""
return self._seed
@seed.setter
def seed(self, seed):
self._seed = seed
# invalidate _all_vals to trigger re-generation
# in _raw_to_displayed
self._all_vals = np.array([])
self._selected_color = self.get_color(self.selected_label)
self.refresh()
self.events.selected_label()
@_ImageBase.colormap.setter
def colormap(self, colormap):
super()._set_colormap(colormap)
self._selected_color = self.get_color(self.selected_label)
@property
def num_colors(self):
"""int: Number of unique colors to use in colormap."""
return self._num_colors
@num_colors.setter
def num_colors(self, num_colors):
self._num_colors = num_colors
self.colormap = label_colormap(num_colors)
self.refresh()
self._selected_color = self.get_color(self.selected_label)
self.events.selected_label()
@property
def data(self):
"""array: Image data."""
return self._data
@data.setter
def data(self, data):
data = self._ensure_int_labels(data)
self._data = data
self._update_dims()
self.events.data(value=self.data)
self._set_editable()
@property
def features(self):
"""Dataframe-like features table.
It is an implementation detail that this is a `pandas.DataFrame`. In the future,
we will target the currently-in-development Data API dataframe protocol [1].
This will enable us to use alternate libraries such as xarray or cuDF for
additional features without breaking existing usage of this.
If you need to specifically rely on the pandas API, please coerce this to a
`pandas.DataFrame` using `features_to_pandas_dataframe`.
References
----------
.. [1]: https://data-apis.org/dataframe-protocol/latest/API.html
"""
return self._feature_table.values
@features.setter
def features(
self,
features: Union[Dict[str, np.ndarray], pd.DataFrame],
) -> None:
self._feature_table.set_values(features)
self._label_index = self._make_label_index()
self.events.properties()
self.events.features()
@property
def properties(self) -> Dict[str, np.ndarray]:
"""dict {str: array (N,)}, DataFrame: Properties for each label."""
return self._feature_table.properties()
@properties.setter
def properties(self, properties: Dict[str, Array]):
self.features = properties
def _make_label_index(self) -> Dict[int, int]:
features = self._feature_table.values
label_index = {}
if 'index' in features:
label_index = {i: k for k, i in enumerate(features['index'])}
elif features.shape[1] > 0:
label_index = {i: i for i in range(features.shape[0])}
return label_index
@property
def color(self):
"""dict: custom color dict for label coloring"""
return self._color
@color.setter
def color(self, color):
if not color:
color = {}
if self._background_label not in color:
color[self._background_label] = 'transparent'
if None not in color:
color[None] = 'black'
colors = {
label: transform_color(color_str)[0]
for label, color_str in color.items()
}
self._color = colors
# `colors` may contain just the default None and background label
# colors, in which case we need to be in AUTO color mode. Otherwise,
# `colors` contains colors for all labels, and we should be in DIRECT
# mode.
# For more information
# - https://github.com/napari/napari/issues/2479
# - https://github.com/napari/napari/issues/2953
if self._is_default_colors(colors):
color_mode = LabelColorMode.AUTO
else:
color_mode = LabelColorMode.DIRECT
self.color_mode = color_mode
def _is_default_colors(self, color):
"""Returns True if color contains only default colors, otherwise False.
Default colors are black for `None` and transparent for
`self._background_label`.
Parameters
----------
color : Dict
Dictionary of label value to color array
Returns
-------
bool
True if color contains only default colors, otherwise False.
"""
if len(color) != 2:
return False
if not hasattr(self, '_color'):
return False
default_keys = [None, self._background_label]
if set(default_keys) != set(color.keys()):
return False
for key in default_keys:
if not np.allclose(self._color[key], color[key]):
return False
return True
def _ensure_int_labels(self, data):
"""Ensure data is integer by converting from bool if required, raising an error otherwise."""
looks_multiscale, data = guess_multiscale(data)
if not looks_multiscale:
data = [data]
int_data = []
for data_level in data:
# normalize_dtype turns e.g. tensorstore or torch dtypes into
# numpy dtypes
if np.issubdtype(normalize_dtype(data_level.dtype), np.floating):
raise TypeError(
trans._(
"Only integer types are supported for Labels layers, but data contains {data_level_type}.",
data_level_type=data_level.dtype,
)
)
if data_level.dtype == bool:
int_data.append(data_level.astype(np.int8))
else:
int_data.append(data_level)
data = int_data
if not looks_multiscale:
data = data[0]
return data
def _get_state(self):
"""Get dictionary of layer state.
Returns
-------
state : dict
Dictionary of layer state.
"""
state = self._get_base_state()
state.update(
{
'multiscale': self.multiscale,
'num_colors': self.num_colors,
'properties': self.properties,
'rendering': self.rendering,
'depiction': self.depiction,
'plane': self.plane.dict(),
'experimental_clipping_planes': [
plane.dict() for plane in self.experimental_clipping_planes
],
'seed': self.seed,
'data': self.data,
'color': self.color,
'features': self.features,
}
)
return state
@property
def selected_label(self):
"""int: Index of selected label."""
return self._selected_label
@selected_label.setter
def selected_label(self, selected_label):
if selected_label == self.selected_label:
return
self._selected_label = selected_label
self._selected_color = self.get_color(selected_label)
self.events.selected_label()
# note: self.color_mode returns a string and this comparison fails,
# so use self._color_mode
if self.show_selected_label:
self.refresh()
@property
def color_mode(self):
"""Color mode to change how color is represented.
AUTO (default) allows color to be set via a hash function with a seed.
DIRECT allows color of each label to be set directly by a color dict.
"""
return str(self._color_mode)
@color_mode.setter
def color_mode(self, color_mode: Union[str, LabelColorMode]):
color_mode = LabelColorMode(color_mode)
if color_mode == LabelColorMode.DIRECT:
custom_colormap, label_color_index = color_dict_to_colormap(
self.color
)
super()._set_colormap(custom_colormap)
self._label_color_index = label_color_index
elif color_mode == LabelColorMode.AUTO:
self._label_color_index = {}
super()._set_colormap(self._random_colormap)
else:
raise ValueError(trans._("Unsupported Color Mode"))
self._color_mode = color_mode
self._selected_color = self.get_color(self.selected_label)
self.events.color_mode()
self.events.colormap()
self.events.selected_label()
self.refresh()
@property
def show_selected_label(self):
"""Whether to filter displayed labels to only the selected label or not"""
return self._show_selected_label
@show_selected_label.setter
def show_selected_label(self, filter):
self._show_selected_label = filter
self.refresh()
@property
def mode(self):
"""MODE: Interactive mode. The normal, default mode is PAN_ZOOM, which
allows for normal interactivity with the canvas.
In PICK mode the cursor functions like a color picker, setting the
clicked on label to be the current label. If the background is picked it
will select the background label `0`.
In PAINT mode the cursor functions like a paint brush changing any
pixels it brushes over to the current label. If the background label
`0` is selected than any pixels will be changed to background and this
tool functions like an eraser. The size and shape of the cursor can be
adjusted in the properties widget.
In FILL mode the cursor functions like a fill bucket replacing pixels
of the label clicked on with the current label. It can either replace
all pixels of that label or just those that are contiguous with the
clicked on pixel. If the background label `0` is selected than any
pixels will be changed to background and this tool functions like an
eraser.
In ERASE mode the cursor functions similarly to PAINT mode, but to
paint with background label, which effectively removes the label.
"""
return str(self._mode)
_drag_modes = {
Mode.PAN_ZOOM: no_op,
Mode.TRANSFORM: no_op,
Mode.PICK: pick,
Mode.PAINT: draw,
Mode.FILL: draw,
Mode.ERASE: draw,
}
_move_modes = {
Mode.PAN_ZOOM: no_op,
Mode.TRANSFORM: no_op,
Mode.PICK: no_op,
Mode.PAINT: no_op,
Mode.FILL: no_op,
Mode.ERASE: no_op,
}
_cursor_modes = {
Mode.PAN_ZOOM: 'standard',
Mode.TRANSFORM: 'standard',
Mode.PICK: 'cross',
Mode.PAINT: 'circle',
Mode.FILL: 'cross',
Mode.ERASE: 'circle',
}
@mode.setter
def mode(self, mode: Union[str, Mode]):
mode, changed = self._mode_setter_helper(mode, Mode)
if not changed:
return
if mode in {Mode.PAINT, Mode.ERASE}:
self.cursor_size = self._calculate_cursor_size()
self.events.mode(mode=mode)
self.refresh()
@property
def preserve_labels(self):
"""Defines if painting should preserve existing labels.
Default to false to allow paint on existing labels. When
set to true, existing labels will be preserved during painting.
"""
return self._preserve_labels
@preserve_labels.setter
def preserve_labels(self, preserve_labels: bool):
self._preserve_labels = preserve_labels
self.events.preserve_labels(preserve_labels=preserve_labels)
@property
def contrast_limits(self):
return self._contrast_limits
@contrast_limits.setter
def contrast_limits(self, value):
# Setting contrast_limits of labels layers leads to wrong visualization of the layer
if tuple(value) != (0, 1):
raise AttributeError(
trans._(
"Setting contrast_limits on labels layers is not allowed.",
deferred=True,
)
)
self._contrast_limits = (0, 1)
def _set_editable(self, editable=None):
"""Set editable mode based on layer properties."""
if editable is None:
self.editable = not self.multiscale
if not self.editable:
self.mode = Mode.PAN_ZOOM
self._reset_history()
def _lookup_with_low_discrepancy_image(self, im, selected_label=None):
"""Returns display version of im using low_discrepancy_image.
Passes the image through low_discrepancy_image, only coloring
selected_label if it's not None.
Parameters
----------
im : array or int
Raw integer input image.
selected_label : int, optional
Value of selected label to color, by default None
"""
if selected_label:
image = np.where(
im == selected_label,
low_discrepancy_image(selected_label, self._seed),
0,
)
else:
image = np.where(im != 0, low_discrepancy_image(im, self._seed), 0)
return image
def _lookup_with_index(self, im, selected_label=None):
"""Returns display version of im using color lookup array by index
Parameters
----------
im : array or int
Raw integer input image.
selected_label : int, optional
Value of selected label to color, by default None
"""
if selected_label:
if selected_label > len(self._all_vals):
self._color_lookup_func = self._get_color_lookup_func(
im,
min(np.min(im), selected_label),
max(np.max(im), selected_label),
)
if (
self._color_lookup_func
== self._lookup_with_low_discrepancy_image
):
image = self._color_lookup_func(im, selected_label)
else:
colors = np.zeros_like(self._all_vals)
colors[selected_label] = low_discrepancy_image(
selected_label, self._seed
)
image = colors[im]
else:
try:
image = self._all_vals[im]
except IndexError:
self._color_lookup_func = self._get_color_lookup_func(
im, np.min(im), np.max(im)
)
if (
self._color_lookup_func
== self._lookup_with_low_discrepancy_image
):
# revert to "classic" mode converting all pixels since we
# encountered a large value in the raw labels image
image = self._color_lookup_func(im, selected_label)
else:
image = self._all_vals[im]
return image
def _get_color_lookup_func(self, data, min_label_val, max_label_val):
"""Returns function used for mapping label values to colors
If array of [0..max(data)] would be larger than data,
returns lookup_with_low_discrepancy_image, otherwise returns
lookup_with_index
Parameters
----------
data : array
labels data
min_label_val : int
minimum label value in data
max_label_val : int
maximum label value in data
Returns
-------
lookup_func : function
function to use for mapping label values to colors
"""
# low_discrepancy_image is slow for large images, but large labels can
# blow up memory usage of an index array of colors. If the index array
# would be larger than the image, we go back to computing the low
# discrepancy image on the whole input image. (Up to a minimum value of
# 1kB.)
min_label_val0 = min(min_label_val, 0)
# +1 to allow indexing with max_label_val
data_range = max_label_val - min_label_val0 + 1
nbytes_low_discrepancy = low_discrepancy_image(np.array([0])).nbytes
max_nbytes = max(data.nbytes, 1024)
if data_range * nbytes_low_discrepancy > max_nbytes:
return self._lookup_with_low_discrepancy_image
else:
if self._all_vals.size < data_range:
new_all_vals = low_discrepancy_image(
np.arange(min_label_val0, max_label_val + 1), self._seed
)
self._all_vals = np.roll(new_all_vals, min_label_val0)
self._all_vals[0] = 0
return self._lookup_with_index
def _raw_to_displayed(self, raw):
"""Determine displayed image from a saved raw image and a saved seed.
This function ensures that the 0 label gets mapped to the 0 displayed
pixel.
Parameters
----------
raw : array or int
Raw integer input image.
Returns
-------
image : array
Image mapped between 0 and 1 to be displayed.
"""
raw_modified = raw
if self.contour > 0:
if raw.ndim == 2:
raw_modified = np.zeros_like(raw)
struct_elem = ndi.generate_binary_structure(raw.ndim, 1)
thickness = self.contour
thick_struct_elem = ndi.iterate_structure(
struct_elem, thickness
).astype(bool)
boundaries = ndi.grey_dilation(
raw, footprint=struct_elem
) != ndi.grey_erosion(raw, footprint=thick_struct_elem)
raw_modified[boundaries] = raw[boundaries]
elif raw.ndim > 2:
warnings.warn(
trans._(
"Contours are not displayed during 3D rendering",
deferred=True,
)
)
if self._color_lookup_func is None:
self._color_lookup_func = self._get_color_lookup_func(
raw_modified, np.min(raw_modified), np.max(raw_modified)
)
if (
not self.show_selected_label
and self._color_mode == LabelColorMode.DIRECT
):
u, inv = np.unique(raw_modified, return_inverse=True)
image = np.array(
[
self._label_color_index[x]
if x in self._label_color_index
else self._label_color_index[None]
for x in u
]
)[inv].reshape(raw_modified.shape)
elif (
not self.show_selected_label
and self._color_mode == LabelColorMode.AUTO
):
image = self._color_lookup_func(raw_modified)
elif (
self.show_selected_label
and self._color_mode == LabelColorMode.AUTO
):
image = self._color_lookup_func(raw_modified, self._selected_label)
elif (
self.show_selected_label
and self._color_mode == LabelColorMode.DIRECT
):
selected = self._selected_label
if selected not in self._label_color_index:
selected = None
index = self._label_color_index
image = np.where(
raw_modified == selected,
index[selected],
np.where(
raw_modified != self._background_label,
index[None],
index[self._background_label],
),
)
else:
raise ValueError("Unsupported Color Mode")
return image
def new_colormap(self):
self.seed = np.random.rand()
def get_color(self, label):
"""Return the color corresponding to a specific label."""
if label == 0:
col = None
elif label is None:
col = self.colormap.map([0, 0, 0, 0])[0]
else:
val = self._raw_to_displayed(np.array([label]))
col = self.colormap.map(val)[0]
return col
def _get_value_ray(
self,
start_point: np.ndarray,
end_point: np.ndarray,
dims_displayed: List[int],
) -> Optional[int]:
"""Get the first non-background value encountered along a ray.
Parameters
----------
start_point : np.ndarray
(n,) array containing the start point of the ray in data coordinates.
end_point : np.ndarray
(n,) array containing the end point of the ray in data coordinates.
dims_displayed : List[int]
The indices of the dimensions currently displayed in the viewer.
Returns
-------
value : Optional[int]
The first non-zero value encountered along the ray. If none
was encountered or the viewer is in 2D mode, None is returned.