Debian Codegraph @

imgviz/label.py

raw symbols SCIP
1 import numbers
2
3 import numpy as np
4
5 from . import color as color_module
6 from . import draw as draw_module
7 from . import utils
8
9
10 def label_colormap(n_label=256, value=None):
11 """Label colormap.
12
13 Parameters
14 ----------
15 n_labels: int
16 Number of labels (default: 256).
17 value: float or int
18 Value scale or value of label color in HSV space.
19
20 Returns
21 -------
22 cmap: numpy.ndarray, (N, 3), numpy.uint8
23 Label id to colormap.
24
25 """
26
27 def bitget(byteval, idx):
28 shape = byteval.shape + (8,)
29 return np.unpackbits(byteval).reshape(shape)[..., -1 - idx]
30
31 i = np.arange(n_label, dtype=np.uint8)
32 r = np.full_like(i, 0)
33 g = np.full_like(i, 0)
34 b = np.full_like(i, 0)
35
36 i = np.repeat(i[:, None], 8, axis=1)
37 i = np.right_shift(i, np.arange(0, 24, 3)).astype(np.uint8)
38 j = np.arange(8)[::-1]
39 r = np.bitwise_or.reduce(np.left_shift(bitget(i, 0), j), axis=1)
40 g = np.bitwise_or.reduce(np.left_shift(bitget(i, 1), j), axis=1)
41 b = np.bitwise_or.reduce(np.left_shift(bitget(i, 2), j), axis=1)
42
43 cmap = np.stack((r, g, b), axis=1).astype(np.uint8)
44
45 if value is not None:
46 hsv = color_module.rgb2hsv(cmap.reshape(1, -1, 3))
47 if isinstance(value, float):
48 hsv[:, 1:, 2] = hsv[:, 1:, 2].astype(float) * value
49 else:
50 assert isinstance(value, int)
51 hsv[:, 1:, 2] = value
52 cmap = color_module.hsv2rgb(hsv).reshape(-1, 3)
53 return cmap
54
55
56 def label2rgb(
57 label,
58 image=None,
59 alpha=0.5,
60 label_names=None,
61 font_size=30,
62 thresh_suppress=0,
63 colormap=None,
64 loc="rb",
65 font_path=None,
66 ):
67 """Convert label to rgb.
68
69 Parameters
70 ----------
71 label: numpy.ndarray, (H, W), int
72 Label image.
73 image: numpy.ndarray, (H, W, 3), numpy.uint8
74 RGB image.
75 alpha: float, or list or dict of float
76 Alpha of RGB (default: 0.5).
77 If given as a list or dict, it is treated as alpha for each class
78 according to the index or key.
79 label_names: list or dict of string
80 Label id to label name.
81 font_size: int
82 Font size (default: 30).
83 thresh_suppress: float
84 Threshold of label ratio in the label image.
85 colormap: numpy.ndarray, (M, 3), numpy.uint8
86 Label id to color.
87 By default, :func:`~imgviz.label_colormap` is used.
88 loc: string
89 Location of legend (default: 'rb').
90 'centroid', 'lt' and 'rb' are supported.
91 font_path: str
92 Font path.
93
94 Returns
95 -------
96 res: numpy.ndarray, (H, W, 3), numpy.uint8
97 Visualized image.
98
99 """
100 if colormap is None:
101 colormap = label_colormap()
102
103 if label.dtype == bool:
104 label = label.astype(np.int32)
105
106 res = colormap[label]
107
108 random_state = np.random.RandomState(seed=1234)
109
110 mask_unlabeled = label < 0
111 res[mask_unlabeled] = random_state.rand(*(mask_unlabeled.sum(), 3)) * 255
112
113 unique_labels = np.unique(label)
114 max_label_id = unique_labels[-1]
115
116 if isinstance(alpha, numbers.Number):
117 alpha = np.array([alpha for _ in range(max_label_id + 1)])
118 elif isinstance(alpha, dict):
119 alpha = np.array(
120 [alpha.get(label_id, 0.5) for label_id in range(max_label_id + 1)]
121 )
122 else:
123 alpha = np.asarray(alpha)
124 assert alpha.ndim == 1
125 assert ((0 <= alpha) & (alpha <= 1)).all()
126 alpha = alpha[label][:, :, None]
127
128 if image is not None:
129 if image.ndim == 2:
130 image = color_module.gray2rgb(image)
131 res = (1 - alpha) * image.astype(float) + alpha * res.astype(float)
132 res = np.clip(res.round(), 0, 255).astype(np.uint8)
133
134 if label_names is None:
135 return res
136
137 unique_labels = unique_labels[unique_labels != -1]
138 if isinstance(label_names, dict):
139 unique_labels = [
140 label_id for label_id in unique_labels if label_names.get(label_id)
141 ]
142 else:
143 unique_labels = [
144 label_id for label_id in unique_labels if label_names[label_id]
145 ]
146 if len(unique_labels) == 0:
147 return res
148
149 if loc == "centroid":
150 res = utils.numpy_to_pillow(res)
151 for label_i in unique_labels:
152 mask = label == label_i
153 if 1.0 * mask.sum() / mask.size < thresh_suppress:
154 continue
155 y, x = np.array(_center_of_mass(mask), dtype=int)
156
157 if label[y, x] != label_i:
158 Y, X = np.where(mask)
159 point_index = np.random.randint(0, len(Y))
160 y, x = Y[point_index], X[point_index]
161
162 text = label_names[label_i]
163 height, width = draw_module.text_size(
164 text, size=font_size, font_path=font_path
165 )
166 color = color_module.get_fg_color(res.getpixel((x, y)))
167 draw_module.text_(
168 res,
169 yx=(y - height // 2, x - width // 2),
170 text=text,
171 color=color,
172 size=font_size,
173 font_path=font_path,
174 )
175 elif loc in ["rb", "lt"]:
176 text_sizes = np.array(
177 [
178 draw_module.text_size(
179 label_names[label_id], font_size, font_path=font_path
180 )
181 for label_id in unique_labels
182 ]
183 )
184 text_height, text_width = text_sizes.max(axis=0)
185 legend_height = text_height * len(unique_labels) + 5
186 legend_width = text_width + 20 + (text_height - 10)
187
188 height, width = label.shape[:2]
189 if loc == "rb":
190 aabb2 = np.array([height - 5, width - 5], dtype=float)
191 aabb1 = aabb2 - (legend_height, legend_width)
192 elif loc == "lt":
193 aabb1 = np.array([5, 5], dtype=float)
194 aabb2 = aabb1 + (legend_height, legend_width)
195 else:
196 raise ValueError("unexpected loc: {}".format(loc))
197
198 alpha = 0.5
199 y1, x1 = aabb1.round().astype(int)
200 y2, x2 = aabb2.round().astype(int)
201 res[y1:y2, x1:x2] = alpha * res[y1:y2, x1:x2] + alpha * 255
202
203 res = utils.numpy_to_pillow(res)
204 for i, label_id in enumerate(unique_labels):
205 box_aabb1 = aabb1 + (i * text_height + 5, 5)
206 box_aabb2 = box_aabb1 + (text_height - 10, text_height - 10)
207 draw_module.rectangle_(
208 res, aabb1=box_aabb1, aabb2=box_aabb2, fill=colormap[label_id]
209 )
210 draw_module.text_(
211 res,
212 yx=aabb1 + (i * text_height, 10 + (text_height - 10)),
213 text=label_names[label_id],
214 size=font_size,
215 font_path=font_path,
216 )
217 else:
218 raise ValueError("unsupported loc: {}".format(loc))
219
220 return utils.pillow_to_numpy(res)
221
222
223 def _center_of_mass(mask):
224 assert mask.ndim == 2 and mask.dtype == bool
225 mask = 1.0 * mask / mask.sum()
226 dx = np.sum(mask, 0)
227 dy = np.sum(mask, 1)
228 cx = np.sum(dx * np.arange(mask.shape[1]))
229 cy = np.sum(dy * np.arange(mask.shape[0]))
230 return cy, cx