Skip to content

Instantly share code, notes, and snippets.

@wllhf
Last active March 28, 2024 09:11
Show Gist options
  • Save wllhf/a4533e0adebe57e3ed06d4b50c8419ae to your computer and use it in GitHub Desktop.
Save wllhf/a4533e0adebe57e3ed06d4b50c8419ae to your computer and use it in GitHub Desktop.
Python implementation of the color map function for the PASCAL VOC data set.
"""
Python implementation of the color map function for the PASCAL VOC data set.
Official Matlab version can be found in the PASCAL VOC devkit
http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#devkit
"""
import numpy as np
from skimage.io import imshow
import matplotlib.pyplot as plt
def color_map(N=256, normalized=False):
def bitget(byteval, idx):
return ((byteval & (1 << idx)) != 0)
dtype = 'float32' if normalized else 'uint8'
cmap = np.zeros((N, 3), dtype=dtype)
for i in range(N):
r = g = b = 0
c = i
for j in range(8):
r = r | (bitget(c, 0) << 7-j)
g = g | (bitget(c, 1) << 7-j)
b = b | (bitget(c, 2) << 7-j)
c = c >> 3
cmap[i] = np.array([r, g, b])
cmap = cmap/255 if normalized else cmap
return cmap
def color_map_viz():
labels = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor', 'void']
nclasses = 21
row_size = 50
col_size = 500
cmap = color_map()
array = np.empty((row_size*(nclasses+1), col_size, cmap.shape[1]), dtype=cmap.dtype)
for i in range(nclasses):
array[i*row_size:i*row_size+row_size, :] = cmap[i]
array[nclasses*row_size:nclasses*row_size+row_size, :] = cmap[-1]
imshow(array)
plt.yticks([row_size*i+row_size/2 for i in range(nclasses+1)], labels)
plt.xticks([])
plt.show()
@JosephKJ
Copy link

JosephKJ commented Nov 8, 2017

Thanks!

@Hzzone
Copy link

Hzzone commented Jul 30, 2019

Thanks, here is some code to visualize blended image and corresponding segmentation mask:

from PIL import Image
import numpy as np
image = Image.open('VOCdevkit/VOC2012/JPEGImages/2007_000129.jpg')
target = np.array(Image.open('VOCdevkit/VOC2012/SegmentationClass/2007_000129.png'))[:, :, np.newaxis]
cmap = color_map()[:, np.newaxis, :]
new_im = np.dot(target == 0, cmap[0])
for i in range(1, cmap.shape[0]):
    new_im += np.dot(target == i, cmap[i])
new_im = Image.fromarray(new_im.astype(np.uint8))
blend_image = Image.blend(image, new_im, alpha=0.8)
blend_image.save('tmp.jpg')

output:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment