python - 如何将标签矩阵转换为颜色矩阵以进行图像分割?

标签 python image-processing computer-vision pytorch image-segmentation

例如,我有一个 256*256 的标签矩阵。类(class)是 0-11,所以 12 个类(class)。我想将标签矩阵转换为颜色矩阵。我试过用这样的代码来做

`for i in range(256):
    for j in range(256):
        if x[i][j] == 11:
            dummy[i][j] = [255,255,255]
        if x[i][j] == 1:
            dummy[i][j] = [144,0,0]
        if x[i][j] == 2:
            dummy[i][j] = [0,255,0]    
        if x[i][j] == 3:
            dummy[i][j] = [0,0,255]
        if x[i][j] == 4:
            dummy[i][j] = [144,255,0]
        if x[i][j] == 5:
            dummy[i][j] = [144,0,255]            
        if x[i][j] == 6:
            dummy[i][j] = [0,255,255]
        if x[i][j] == 7:
            dummy[i][j] = [122,0,0]
        if x[i][j] == 8:
            dummy[i][j] = [0,122,0]
        if x[i][j] == 9:
            dummy[i][j] = [0,0,122]
        if x[i][j] == 10:
            dummy[i][j] = [122,0,122]
        if x[i][j] == 11:
            dummy[i][j] = [122,122,0]
            `

效率极低。 PS:x 的形状是 [256 256],dummy 是 [256 256 3]。有更好的方法吗?

最佳答案

您正在查看索引 RGB 图像 - 具有固定颜色“调色板”的 RGB 图像,每个像素索引到调色板的一种颜色。参见 this page获取更多信息。

from PIL import Image

img = Image.fromarray(x, mode="P")
img.putpalette([
    255, 255, 255,   # index 0
    144, 0, 0, # index 1 
    0, 255, 0, # index 2 
    0, 0, 255, # index 3 
    # ... and so on, you can take it from here.
])
img.show()

关于python - 如何将标签矩阵转换为颜色矩阵以进行图像分割?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928522/

相关文章:

c++ - 点云库 1.8 - DepthSense Grabber 似乎没有为 NaN XYZ 点提供 RGB 数据

python - 来自顶点数组的 3D 对象

python - 如何使用 Python 结合正则表达式和字符串/文件操作在文本文件中搜索模式并存储模式的实例?

c++ - 如何使用 OpenCV 在视频中查找对象

matlab - MATLAB blockproc 函数中的 'BorderSize' 和 'TrimBorder'

python - 使用Open CV删除背景并不精确,并且某些图片无法正确处理

python - Skimage regionprops 特征的(面积,euler_number)尺寸在 Python 中不正确

c++ - 仅 block 的 HoG 特征

python - 字典的字典的 JSON 编码

python - 在Python中调整base64图像的大小