Debian Codegraph @

imgviz/depth.py

raw symbols SCIP
1 import typing # NOQA
2
3 import matplotlib
4 import numpy as np
5
6 from .normalize import normalize
7
8
9 class Depth2RGB(object):
10 """Convert depth array to rgb.
11
12 Parameters
13 ----------
14 min_value: float, optional
15 Minimum value for colorizing.
16 max_value: float, optional
17 Maximum value for colorizing.
18 colormap: str, optional
19 Colormap, default: 'jet'.
20
21 """
22
23 def __init__(self, min_value=None, max_value=None, colormap="jet"):
24 self._min_value = min_value
25 self._max_value = max_value
26 self._colormap = colormap
27
28 @property
29 def min_value(self):
30 """Minimum value of depth."""
31 return self._min_value
32
33 @property
34 def max_value(self):
35 """Maximum value of depth."""
36 return self._max_value
37
38 def __call__(self, depth, dtype=np.uint8):
39 """Convert depth array to rgb.
40
41 Parameters
42 ----------
43 depth: numpy.ndarray, (H, W), float
44 Depth image.
45 dtype: numpy.dtype
46 Dtype of output image. default: np.uint8
47
48 Returns
49 -------
50 rgb: numpy.ndarray, (H, W, 3), np.uint8
51 Output colorized image.
52
53 """
54 assert depth.ndim == 2, "depth image must be 2 dimensional"
55 assert np.issubdtype(depth.dtype, np.floating), "depth dtype must be float"
56
57 normalized, self._min_value, self._max_value = normalize(
58 depth,
59 min_value=self._min_value,
60 max_value=self._max_value,
61 return_minmax=True,
62 )
63
64 isnan = np.isnan(normalized)
65 normalized[isnan] = 0
66
67 if isinstance(self._colormap, str):
68 if hasattr(matplotlib, "colormaps"):
69 colormap_func = matplotlib.colormaps[self._colormap]
70 else:
71 colormap_func = matplotlib.cm.get_cmap(self._colormap)
72 else:
73 colormap_func = self._colormap
74 rgb = colormap_func(normalized)[:, :, :3]
75 rgb[isnan] = (0, 0, 0)
76
77 if dtype == np.uint8:
78 rgb = (rgb * 255).round().astype(np.uint8)
79 else:
80 assert np.issubdtype(dtype, np.floating)
81 rgb = rgb.astype(dtype)
82
83 return rgb
84
85
86 def depth2rgb(
87 depth,
88 min_value=None,
89 max_value=None,
90 colormap="jet",
91 dtype=np.uint8,
92 ):
93 # type: (np.ndarray, typing.Optional[float], typing.Optional[float], str, typing.Type) -> np.ndarray # NOQA
94 """Convert depth to rgb.
95
96 Parameters
97 ----------
98 depth: numpy.ndarray, (H, W), float
99 Depth image.
100 dtype: numpy.dtype
101 Dtype of output image. default: np.uint8
102 min_value: float, optional
103 Minimum value for colorizing.
104 max_value: float, optional
105 Maximum value for colorizing.
106 colormap: str, optional
107 Colormap, default: 'jet'.
108
109 Returns
110 -------
111 rgb: numpy.ndarray, (H, W, 3), np.uint8
112 Output colorized image.
113
114 """
115 return Depth2RGB(min_value, max_value, colormap)(depth, dtype)