File size: 9,937 Bytes
854f0d0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
import os.path as osp
import os
import matplotlib.pyplot as plt
import torch
import cv2
import math
import numpy as np
import tqdm
from cv2 import findContours
from dl_ext.primitive import safe_zip
from dl_ext.timer import EvalTime
def plot_confidence(confidence):
n = len(confidence)
plt.plot(np.arange(n), confidence)
plt.show()
def image_grid(
images,
rows=None,
cols=None,
fill: bool = True,
show_axes: bool = False,
rgb=None,
show=True,
label=None,
**kwargs
):
"""
A util function for plotting a grid of images.
Args:
images: (N, H, W, 4) array of RGBA images
rows: number of rows in the grid
cols: number of columns in the grid
fill: boolean indicating if the space between images should be filled
show_axes: boolean indicating if the axes of the plots should be visible
rgb: boolean, If True, only RGB channels are plotted.
If False, only the alpha channel is plotted.
Returns:
None
"""
evaltime = EvalTime(disable=True)
evaltime('')
if isinstance(images, torch.Tensor):
images = images.detach().cpu()
if len(images[0].shape) == 2:
rgb = False
if images[0].shape[-1] == 2:
# flow
images = [flow_to_image(im) for im in images]
if (rows is None) != (cols is None):
raise ValueError("Specify either both rows and cols or neither.")
if rows is None:
rows = int(len(images) ** 0.5)
cols = math.ceil(len(images) / rows)
gridspec_kw = {"wspace": 0.0, "hspace": 0.0} if fill else {}
if len(images) < 50:
figsize = (10, 10)
else:
figsize = (15, 15)
evaltime('0.5')
plt.figure(figsize=figsize)
# fig, axarr = plt.subplots(rows, cols, gridspec_kw=gridspec_kw, figsize=figsize)
if label:
# fig.suptitle(label, fontsize=30)
plt.suptitle(label, fontsize=30)
# bleed = 0
# fig.subplots_adjust(left=bleed, bottom=bleed, right=(1 - bleed), top=(1 - bleed))
evaltime('subplots')
# for i, (ax, im) in enumerate(tqdm.tqdm(zip(axarr.ravel(), images), leave=True, total=len(images))):
for i in range(len(images)):
# evaltime(f'{i} begin')
plt.subplot(rows, cols, i + 1)
if rgb:
# only render RGB channels
plt.imshow(images[i][..., :3], **kwargs)
# ax.imshow(im[..., :3], **kwargs)
else:
# only render Alpha channel
plt.imshow(images[i], **kwargs)
# ax.imshow(im, **kwargs)
if not show_axes:
plt.axis('off')
# ax.set_axis_off()
# ax.set_title(f'{i}')
plt.title(f'{i}')
# evaltime(f'{i} end')
evaltime('2')
if show:
plt.show()
# return fig
def depth_grid(
depths,
rows=None,
cols=None,
fill: bool = True,
show_axes: bool = False,
):
"""
A util function for plotting a grid of images.
Args:
images: (N, H, W, 4) array of RGBA images
rows: number of rows in the grid
cols: number of columns in the grid
fill: boolean indicating if the space between images should be filled
show_axes: boolean indicating if the axes of the plots should be visible
rgb: boolean, If True, only RGB channels are plotted.
If False, only the alpha channel is plotted.
Returns:
None
"""
if (rows is None) != (cols is None):
raise ValueError("Specify either both rows and cols or neither.")
if rows is None:
rows = len(depths)
cols = 1
gridspec_kw = {"wspace": 0.0, "hspace": 0.0} if fill else {}
fig, axarr = plt.subplots(rows, cols, gridspec_kw=gridspec_kw, figsize=(15, 9))
bleed = 0
fig.subplots_adjust(left=bleed, bottom=bleed, right=(1 - bleed), top=(1 - bleed))
for ax, im in zip(axarr.ravel(), depths):
ax.imshow(im)
if not show_axes:
ax.set_axis_off()
plt.show()
def hover_masks_on_imgs(images, masks):
masks = np.array(masks)
new_imgs = []
tids = list(range(1, masks.max() + 1))
colors = colormap(rgb=True, lighten=True)
for im, mask in tqdm.tqdm(safe_zip(images, masks), total=len(images)):
for tid in tids:
im = vis_mask(
im,
(mask == tid).astype(np.uint8),
color=colors[tid],
alpha=0.5,
border_alpha=0.5,
border_color=[255, 255, 255],
border_thick=3)
new_imgs.append(im)
return new_imgs
def vis_mask(img,
mask,
color=[255, 255, 255],
alpha=0.4,
show_border=True,
border_alpha=0.5,
border_thick=1,
border_color=None):
"""Visualizes a single binary mask."""
if isinstance(mask, torch.Tensor):
from anypose.utils.pn_utils import to_array
mask = to_array(mask > 0).astype(np.uint8)
img = img.astype(np.float32)
idx = np.nonzero(mask)
img[idx[0], idx[1], :] *= 1.0 - alpha
img[idx[0], idx[1], :] += [alpha * x for x in color]
if show_border:
contours, _ = findContours(
mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# contours = [c for c in contours if c.shape[0] > 10]
if border_color is None:
border_color = color
if not isinstance(border_color, list):
border_color = border_color.tolist()
if border_alpha < 1:
with_border = img.copy()
cv2.drawContours(with_border, contours, -1, border_color,
border_thick, cv2.LINE_AA)
img = (1 - border_alpha) * img + border_alpha * with_border
else:
cv2.drawContours(img, contours, -1, border_color, border_thick,
cv2.LINE_AA)
return img.astype(np.uint8)
def colormap(rgb=False, lighten=True):
"""Copied from Detectron codebase."""
color_list = np.array(
[
0.000, 0.447, 0.741,
0.850, 0.325, 0.098,
0.929, 0.694, 0.125,
0.494, 0.184, 0.556,
0.466, 0.674, 0.188,
0.301, 0.745, 0.933,
0.635, 0.078, 0.184,
0.300, 0.300, 0.300,
0.600, 0.600, 0.600,
1.000, 0.000, 0.000,
1.000, 0.500, 0.000,
0.749, 0.749, 0.000,
0.000, 1.000, 0.000,
0.000, 0.000, 1.000,
0.667, 0.000, 1.000,
0.333, 0.333, 0.000,
0.333, 0.667, 0.000,
0.333, 1.000, 0.000,
0.667, 0.333, 0.000,
0.667, 0.667, 0.000,
0.667, 1.000, 0.000,
1.000, 0.333, 0.000,
1.000, 0.667, 0.000,
1.000, 1.000, 0.000,
0.000, 0.333, 0.500,
0.000, 0.667, 0.500,
0.000, 1.000, 0.500,
0.333, 0.000, 0.500,
0.333, 0.333, 0.500,
0.333, 0.667, 0.500,
0.333, 1.000, 0.500,
0.667, 0.000, 0.500,
0.667, 0.333, 0.500,
0.667, 0.667, 0.500,
0.667, 1.000, 0.500,
1.000, 0.000, 0.500,
1.000, 0.333, 0.500,
1.000, 0.667, 0.500,
1.000, 1.000, 0.500,
0.000, 0.333, 1.000,
0.000, 0.667, 1.000,
0.000, 1.000, 1.000,
0.333, 0.000, 1.000,
0.333, 0.333, 1.000,
0.333, 0.667, 1.000,
0.333, 1.000, 1.000,
0.667, 0.000, 1.000,
0.667, 0.333, 1.000,
0.667, 0.667, 1.000,
0.667, 1.000, 1.000,
1.000, 0.000, 1.000,
1.000, 0.333, 1.000,
1.000, 0.667, 1.000,
0.167, 0.000, 0.000,
0.333, 0.000, 0.000,
0.500, 0.000, 0.000,
0.667, 0.000, 0.000,
0.833, 0.000, 0.000,
1.000, 0.000, 0.000,
0.000, 0.167, 0.000,
0.000, 0.333, 0.000,
0.000, 0.500, 0.000,
0.000, 0.667, 0.000,
0.000, 0.833, 0.000,
0.000, 1.000, 0.000,
0.000, 0.000, 0.167,
0.000, 0.000, 0.333,
0.000, 0.000, 0.500,
0.000, 0.000, 0.667,
0.000, 0.000, 0.833,
0.000, 0.000, 1.000,
0.000, 0.000, 0.000,
0.143, 0.143, 0.143,
0.286, 0.286, 0.286,
0.429, 0.429, 0.429,
0.571, 0.571, 0.571,
0.714, 0.714, 0.714,
0.857, 0.857, 0.857,
1.000, 1.000, 1.000
]
).astype(np.float32)
color_list = color_list.reshape((-1, 3))
if not rgb:
color_list = color_list[:, ::-1]
if lighten:
# Make all the colors a little lighter / whiter. This is copied
# from the detectron visualization code (search for 'w_ratio').
w_ratio = 0.4
color_list = (color_list * (1 - w_ratio) + w_ratio)
return color_list * 255
def vis_layer_mask(masks, save_path=None):
masks = torch.as_tensor(masks)
tids = masks.unique().tolist()
tids.remove(0)
for tid in tqdm.tqdm(tids):
show = save_path is None
image_grid(masks == tid, label=f'{tid}', show=show)
if save_path:
os.makedirs(osp.dirname(save_path), exist_ok=True)
plt.savefig(save_path % tid)
plt.close('all')
def show(x, **kwargs):
if isinstance(x, torch.Tensor):
x = x.detach().cpu()
plt.imshow(x, **kwargs)
plt.show()
def vis_title(rgb, text, shift_y=30):
tmp = rgb.copy()
shift_x = rgb.shape[1] // 2
cv2.putText(tmp, text,
(shift_x, shift_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), thickness=2, lineType=cv2.LINE_AA)
return tmp
|