如何将标签矩阵转换为颜色矩阵以进行图像分割? [英] How to convert a Label matrix to colour matrix for image segmentation?

查看:26
本文介绍了如何将标签矩阵转换为颜色矩阵以进行图像分割?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个 256*256 的标签矩阵.班级是 0-11,所以 12 个班级.我想将标签矩阵转换为颜色矩阵.我试着用这样的代码来做

I have a label matrix of 256*256 for example. And the classes are 0-11 so 12 classes. I want to convert the label matrix to colour matrix. I tried do it in a code like this

`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].有什么更好的方法吗?

It is highly inefficient. PS: the shape of x is [256 256] and dummy is [256 256 3]. Is there any better way to do it ?

推荐答案

您正在研究索引 RGB 图像 - RGB 图像,其中有固定的颜色调色板",每个像素索引调色板的一种颜色.请参阅此页面了解更多信息.

You are looking into indexed RGB images - an RGB image where you have a fixed "pallet" of colors, each pixel indexes to one of the colors of the pallet. See this page for more information.

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()

这篇关于如何将标签矩阵转换为颜色矩阵以进行图像分割?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆