Skip to content

Commit 6c90dc9

Browse files
committed
Use better colormap for label maps
1 parent 9f3cbe9 commit 6c90dc9

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ dependencies = [
4949

5050
[project.optional-dependencies]
5151
csv = ["pandas>=1"]
52-
plot = ["matplotlib>=3.4"]
52+
plot = ["distinctipy>=1.3.4", "matplotlib>=3.4"]
5353

5454
[project.scripts]
5555
tiohd = "torchio.cli.print_info:app"

src/torchio/external/imports.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,7 @@ def _check_and_import(package: str, extra: str) -> ModuleType:
2020

2121
def get_pandas() -> ModuleType:
2222
return _check_and_import(package='pandas', extra='csv')
23+
24+
25+
def get_distinctipy() -> ModuleType:
26+
return _check_and_import(package='distinctipy', extra='plot')

src/torchio/visualization.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
from __future__ import annotations
2+
13
import warnings
4+
from typing import TYPE_CHECKING
25

36
import numpy as np
47
import torch
@@ -10,6 +13,9 @@
1013
from .transforms.preprocessing.spatial.to_canonical import ToCanonical
1114
from .types import TypePath
1215

16+
if TYPE_CHECKING:
17+
from matplotlib.colors import ListedColormap
18+
1319

1420
def import_mpl_plt():
1521
try:
@@ -28,6 +34,17 @@ def rotate(image, radiological=True, n=-1):
2834
return image
2935

3036

37+
def _create_categorical_colormap(data: torch.Tensor) -> ListedColormap:
38+
from .external.imports import get_distinctipy
39+
40+
mpl, _ = import_mpl_plt()
41+
distinctipy = get_distinctipy()
42+
num_classes = int(data.max())
43+
distinct_colors = distinctipy.get_colors(num_classes, pastel_factor=0.5, rng=0)
44+
colors = [(0, 0, 0), *distinct_colors] # prepend black
45+
return mpl.colors.ListedColormap(colors)
46+
47+
3148
def plot_volume(
3249
image: Image,
3350
radiological=True,
@@ -65,7 +82,7 @@ def plot_volume(
6582
slice_x, slice_y, slice_z = color_labels(slices, cmap)
6683
else:
6784
if cmap is None:
68-
cmap = 'cubehelix' if is_label else 'gray'
85+
cmap = _create_categorical_colormap(data) if is_label else 'gray'
6986
imshow_kwargs['cmap'] = cmap
7087

7188
if is_label:

0 commit comments

Comments
 (0)