Skip to content

Commit 0ab851a

Browse files
authored
Merge pull request #57 from jnolan14/compact_labels
Compact labels
2 parents 83e4e29 + eab899f commit 0ab851a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

surfa/core/framed.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,44 @@ def labels(self, value):
146146
raise ValueError(f'labels expected LabelLookup object, but got object of type {value.__class__.__name__}')
147147
else:
148148
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.
149162
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+
150187
@property
151188
def basedim(self):
152189
"""

0 commit comments

Comments
 (0)