【发布时间】:2018-05-08 16:01:35
【问题描述】:
让我们考虑一个灰度值,其值在 [0, 255] 范围内。我们如何有效地将每个值映射到一个 RGB 值?
到目前为止,我已经想出了以下实现:
# function for colorizing a label image:
def label_img_to_color(img):
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],
6: [250,170, 30],
7: [220,220, 0],
8: [107,142, 35],
9: [152,251,152],
10: [ 70,130,180],
11: [220, 20, 60],
12: [255, 0, 0],
13: [ 0, 0,142],
14: [ 0, 0, 70],
15: [ 0, 60,100],
16: [ 0, 80,100],
17: [ 0, 0,230],
18: [119, 11, 32],
19: [81, 0, 81]
}
img_height, img_width = img.shape
img_color = np.zeros((img_height, img_width, 3))
for row in range(img_height):
for col in range(img_width):
label = img[row, col]
img_color[row, col] = np.array(label_to_color[label])
return img_color
但是,正如您所见,它效率不高,因为有两个“for”循环。
Convert grayscale value to RGB representation?也有人问过这个问题,但没有建议有效的实现方式。
【问题讨论】:
-
拥有两个 for 循环并不是低效的。如果没有两个 for 循环,在逻辑上不可能对二维数据结构进行索引。效率低下的是将每个 label_to_color 列表转换为 np.array inside for 循环。为什么不在
label_img_to_color函数中使用 np.array 对象(而不是 Python 列表)初始化您的label_to_color列表? -
实际上事实证明有一种有效的方法可以做到这一点。请查看接受的答案。
-
实际上,我相信我在答案中提供的代码在较低级别上实现了某种双 for 循环。但是,与使用 numpy 布尔索引相比,python 中的 for 循环效率非常低。
标签: python image mapping rgb grayscale