简体   繁体   English

从二维整数数组中生成具有固定颜色的彩色图像

[英]generating colored image with fixed colors out of a 2D array of integers

Segmentation output gives me a 2D array with each pixel having a unique integer value corresponding to a class.分割输出给了我一个二维数组,每个像素都有一个对应于一个类的唯一整数值。 I want to create a coloured image from this array with fixed colours for every class.我想从这个数组中为每个类创建一个具有固定颜色的彩色图像。 Please help.请帮忙。 If I just stack up the 2D array to create 3 channel image, the image is only different shades of grey for different classes.如果我只是堆叠 2D 数组来创建 3 通道图像,则图像对于不同的类别只有不同的灰色阴影。

You can check the following code and modify according to your need:您可以检查以下代码并根据需要进行修改:

import numpy as np
import matplotlib.pyplot as plt

arr = np.array([[2,6,8,9], [1,2,7,8], [4,5,1,7]]) # this may be your array
unique_values = set(np.unique(arr).tolist()) # getting unique classes
colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_values))] # generating random colors for each unique classes

Rarr = np.zeros_like(arr, dtype = 'float64') # Red
Garr = np.zeros_like(arr, dtype = 'float64') # Green
Barr = np.zeros_like(arr, dtype = 'float64') # Blue
for val, col in zip(unique_values, colors):
    Rarr[arr == val ] = col[0]
    Garr[arr == val ] = col[1]
    Barr[arr == val ] = col[2]

rgb = np.dstack((Rarr,Garr,Barr)) # Combining three channels


plt.subplot(1, 4, 1)
plt.imshow(Rarr, 'Reds')
plt.subplot(1, 4, 2)
plt.imshow(Garr, 'Greens')
plt.subplot(1, 4, 3)
plt.imshow(Garr, 'Blues')
plt.subplot(1, 4, 4)
plt.imshow(rgb)
plt.show()

输出

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

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