【问题标题】:map grayscale values to RGB values in image将灰度值映射到图像中的 RGB 值
【发布时间】: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


【解决方案1】:

一种更有效的方法是:

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

【讨论】:

  • 颜色图是固定的,因此使用 OpenCV 中的颜色图不是解决方案。您的解决方案将灰度图像转换为 RGB。没有根据 label_to_color 表转换像素值。
  • 我编辑了我的答案,如果这回答了你的问题,请告诉我
  • 哇!非常感谢。你让我今天一整天都感觉很好。它超级快。只有 Python 抱怨 *img.shape 说这是一个语法错误,所以我改用了 img_height, img_width = img.shape rgb_img = np.zeros((img_height, img_width, 3))。
猜你喜欢
  • 2019-09-22
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2014-09-17
  • 2011-01-17
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
相关资源
最近更新 更多