-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
vis.py
54 lines (48 loc) · 1.57 KB
/
vis.py
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
import numpy as np
def make_palette(num_classes):
"""
Maps classes to colors in the style of PASCAL VOC.
Close values are mapped to far colors for segmentation visualization.
See http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#devkit
Takes:
num_classes: the number of classes
Gives:
palette: the colormap as a k x 3 array of RGB colors
"""
palette = np.zeros((num_classes, 3), dtype=np.uint8)
for k in xrange(0, num_classes):
label = k
i = 0
while label:
palette[k, 0] |= (((label >> 0) & 1) << (7 - i))
palette[k, 1] |= (((label >> 1) & 1) << (7 - i))
palette[k, 2] |= (((label >> 2) & 1) << (7 - i))
label >>= 3
i += 1
return palette
def color_seg(seg, palette):
"""
Replace classes with their colors.
Takes:
seg: H x W segmentation image of class IDs
Gives:
H x W x 3 image of class colors
"""
return palette[seg.flat].reshape(seg.shape + (3,))
def vis_seg(img, seg, palette, alpha=0.5):
"""
Visualize segmentation as an overlay on the image.
Takes:
img: H x W x 3 image in [0, 255]
seg: H x W segmentation image of class IDs
palette: K x 3 colormap for all classes
alpha: opacity of the segmentation in [0, 1]
Gives:
H x W x 3 image with overlaid segmentation
"""
vis = np.array(img, dtype=np.float32)
mask = seg > 0
vis[mask] *= 1. - alpha
vis[mask] += alpha * palette[seg[mask].flat]
vis = vis.astype(np.uint8)
return vis