Skip to content

Commit c018ab1

Browse files
authored
Merge pull request #763 from effigies/fix/write_annot_bug
FIX: Correctly write .annot files with duplicate labels
2 parents 2379b01 + 929dbc3 commit c018ab1

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

nibabel/freesurfer/io.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,7 @@ def write_string(s):
561561
write(-2)
562562

563563
# maxstruc
564-
write(np.max(labels) + 1)
564+
write(max(np.max(labels) + 1, ctab.shape[0]))
565565

566566
# File of LUT is unknown.
567567
write_string('NOFILE')

nibabel/freesurfer/tests/test_io.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from nose.tools import assert_true
1414
import numpy as np
15-
from numpy.testing import assert_equal, assert_raises, dec, assert_allclose
15+
from numpy.testing import assert_equal, assert_raises, dec, assert_allclose, assert_array_equal
1616

1717
from .. import (read_geometry, read_morph_data, read_annot, read_label,
1818
write_geometry, write_morph_data, write_annot)
@@ -356,3 +356,22 @@ def test_label():
356356
labels, scalars = read_label(label_path, True)
357357
assert_true(np.all(labels == label))
358358
assert_true(len(labels) == len(scalars))
359+
360+
361+
def test_write_annot_maxstruct():
362+
"""Test writing ANNOT files with repeated labels"""
363+
with InTemporaryDirectory():
364+
nlabels = 3
365+
names = ['label {}'.format(l) for l in range(1, nlabels + 1)]
366+
# max label < n_labels
367+
labels = np.array([1, 1, 1], dtype=np.int32)
368+
rgba = np.array(np.random.randint(0, 255, (nlabels, 4)), dtype=np.int32)
369+
annot_path = 'c.annot'
370+
371+
write_annot(annot_path, labels, rgba, names)
372+
# Validate the file can be read
373+
rt_labels, rt_ctab, rt_names = read_annot(annot_path)
374+
# Check round-trip
375+
assert_array_equal(labels, rt_labels)
376+
assert_array_equal(rgba, rt_ctab[:, :4])
377+
assert_equal(names, [n.decode('ascii') for n in rt_names])

0 commit comments

Comments
 (0)