Coverage for src/bioimageio/core/_utils/color.py: 55%

21 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 09:46 +0000

1from __future__ import annotations 

2 

3from typing import cast 

4 

5 

6def hex_to_rgb(value: str): 

7 value = value.lstrip("#") 

8 if len(value) == 3: 8 ↛ 9line 8 didn't jump to line 9 because the condition on line 8 was never true

9 value = "".join(v * 2 for v in value) 

10 

11 if len(value) not in (6, 8): 11 ↛ 12line 11 didn't jump to line 12 because the condition on line 11 was never true

12 raise ValueError(f"Invalid hex color: {value}") 

13 

14 ret = tuple(int(value[i : i + 2], 16) for i in range(0, len(value), 2)) 

15 assert len(ret) in (3, 4) 

16 return cast(tuple[int, int, int] | tuple[int, int, int, int], ret) 

17 

18 

19def get_default_channel_colors(n_channels: int) -> list[str]: 

20 """Get default channel colors for visualization purposes. 

21 

22 - For < 8 channels: colorblind-friendly palette from https://www.nature.com/articles/nmeth.1618 (without black) 

23 - For < 21 channels: discrete matplotlib colormap 'tab20b' (redistributed for more even color distribution < 20 channels) 

24 - For >= 21 channels: sample colors from continuous matplotlib colormap 'cividis' 

25 

26 Returns: 

27 List of hex color strings. 

28 """ 

29 if n_channels < 8: 29 ↛ 41line 29 didn't jump to line 41 because the condition on line 29 was always true

30 # use colorblind-friendly palette from https://www.nature.com/articles/nmeth.1618 

31 # (without black) 

32 channel_colors = [ 

33 "#E69F00", 

34 "#56B4E9", 

35 "#009E73", 

36 "#F0E442", 

37 "#0072B2", 

38 "#D55E00", 

39 "#CC79A7", 

40 ][:n_channels] 

41 elif n_channels < 21: 

42 # use discrete matplotlib colormap 'tab20b' 

43 # (redistributed for more even color distribution < 20 channels) 

44 channel_colors = [ 

45 "#393b79", 

46 "#8ca252", 

47 "#e7ba52", 

48 "#e7969c", 

49 "#7b4173", 

50 "#5254a3", 

51 "#b5cf6b", 

52 "#e7cb94", 

53 "#843c39", 

54 "#a55194", 

55 "#6b6ecf", 

56 "#cedb9c", 

57 "#8c6d31", 

58 "#d6616b", 

59 "#ce6dbd", 

60 "#9c9ede", 

61 "#637939", 

62 "#bd9e39", 

63 "#ad494a", 

64 "#de9ed6", 

65 ][:n_channels] 

66 else: 

67 # sample colors from continuous matplotlib colormap 'cividis' 

68 import matplotlib.colors 

69 import matplotlib.pyplot as plt 

70 

71 cmap = plt.colormaps["cividis"].resampled(n_channels) 

72 channel_colors = [matplotlib.colors.to_hex(cmap(i)) for i in range(n_channels)] 

73 

74 return channel_colors