get_annot_tsv.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
  2. # vi: set ft=python sts=4 ts=4 sw=4 et:
  3. #
  4. # Copyright 2024 The NiPreps Developers <nipreps@gmail.com>
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. # We support and encourage derived works from this project, please read
  19. # about our expectations at
  20. #
  21. # https://www.nipreps.org/community/licensing/
  22. #
  23. from pathlib import Path
  24. import click
  25. import numpy as np
  26. import pandas as pd
  27. import nibabel as nb
  28. @click.command()
  29. @click.argument("input_annot", type=click.Path(exists=True))
  30. @click.argument("output_tsv", type=click.Path())
  31. def run(input_annot, output_tsv):
  32. vert_lab, reg_ctable, reg_names = nb.freesurfer.read_annot(input_annot)
  33. df = pd.DataFrame(
  34. reg_ctable.byteswap().newbyteorder(),
  35. columns={
  36. "red": np.uint8,
  37. "green": np.uint8,
  38. "blue": np.uint8,
  39. "transparency": np.uint8,
  40. "index": np.uint32,
  41. }
  42. )
  43. df["name"] = [n.decode() for n in reg_names]
  44. df["alpha"] = 255 - df.transparency
  45. df["color"] = df.loc[:, ("red", "green", "blue", "alpha")].apply(
  46. lambda r: "#{:02x}{:02x}{:02x}{:02x}".format(*r),
  47. axis=1
  48. )
  49. df[["index", "name", "color"]].to_csv(output_tsv, sep="\t", index=None)
  50. if __name__ == '__main__':
  51. run()