@@ -146,7 +146,44 @@ def labels(self, value):
146
146
raise ValueError (f'labels expected LabelLookup object, but got object of type { value .__class__ .__name__ } ' )
147
147
else :
148
148
self ._metadata ['labels' ] = value .copy ()
149
+
150
+ def compact_labels (self , update_labels = False ):
151
+ """
152
+ Returns a LabelLookup object containing only the values from the lookup
153
+ table that are present in the label volume.
154
+
155
+ This expects that `self.data` contains only int-like values corresponding
156
+ to indices in the default `FreeSurferColorLUT.txt`.
157
+
158
+ Parameters
159
+ ----------
160
+ update_labels : bool
161
+ If True, updates `self.labels` to the new compacted label lookup.
149
162
163
+ Returns
164
+ -------
165
+ LabelLookup
166
+ A label lookup containing only the labels present in the segmentation.
167
+ """
168
+ # ensure self.labels is not None
169
+ assert self .labels is not None , "self.labels is None, must be a LabelLookup"
170
+ # ensure we're working with a label volume, containing int-like data
171
+ assert np .issubdtype (self .data .dtype , np .integer ), "self.data must be a label volume to compact labels"
172
+
173
+ # create empty LabelLookup
174
+ compact_labels = LabelLookup ()
175
+ uniq = np .unique (self .data )
176
+
177
+ # populate empty LabelLookup with labels present in the volume
178
+ for i , l_idx in enumerate (uniq ):
179
+ compact_labels [i ] = self .labels [l_idx ]
180
+
181
+ if update_labels :
182
+ self .labels = compact_labels
183
+
184
+ return compact_labels
185
+
186
+
150
187
@property
151
188
def basedim (self ):
152
189
"""
0 commit comments