简体   繁体   English

将灰度值映射到图像中的RGB值

[英]map grayscale values to RGB values in image

Let us consider a grayscale value with values in the range of [0, 255]. 让我们考虑一个灰度值,其值在[0,255]范围内。 How can we efficiently map each value to a RGB value? 我们如何有效地将每个值映射到RGB值?

So far, I have come up with the following implementation: 到目前为止,我已经提出了以下实现:

# 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

However, as you can see it is not efficient as there are two "for" loops. 但是,如您所见,它效率不高,因为有两个“ for”循环。

This question was also asked in Convert grayscale value to RGB representation? 在“ 将灰度值转换为RGB表示形式”中也提出了这个问题 , but no efficient implementation was suggested. ,但未提出有效的实施建议。

A more efficient way of doing that instead of a double for loop over all pixels could be: 一个更有效的方法是,而不是在所有像素上使用double for循环:

rgb_img = np.zeros((*img.shape, 3)) 
for key in label_to_color.keys():
    rgb_img[img == key] = label_to_color[key]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM