我有一个将类映射到RGB值的字典:
label_to_color = {
0: [128, 64, 128],
1: [244, 35, 232],
2: [ 70, 70, 70],
3: [102, 102, 156],
4: [190, 153, 153],
5: [153, 153, 153]
}
我用RGB值替换图像中的类,如下所示:
def mask2pixel(image):
h,w = image.shape
im = np.zeros((h,w,3))
for i in range(h):
for j in range(w):
im[i,j,:] = label_to_color[image[i,j]]
return im.astype(int)
image = cv2.imread(im_path,-1)
print(image.shape) # 1200x720
print(image[0,0]) # 0
colormap = mask2pixel(image)
print(colormap.shape) # 1200x720x3
print(colormap[0,0]) # array([128, 64,128])
有没有更有效的方法
不要迭代像素!迭代颜色,并使用NumPy的boolean index arrays
这将是一个纯粹的NumPy解决方案:
相应的输出:
由于标签中有python-imaging-library,因此还可以选择使用枕头图像mode ^{} 创建索引图像,并提供颜色作为palette:
输出:
相关问题 更多 >
编程相关推荐