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

分段输出为我提供了一个2D数组,每个像素具有对应于类的唯一整数值​​。我想从此数组为每个类创建具有固定颜色的彩色图像。请帮忙。如果我只是堆叠2D数组以创建3通道图像,那么对于不同的类,该图像只是不同的灰度阴影。

rxwywy 回答:从2D整数数组中生成具有固定颜色的彩色图像

您可以检查以下代码并根据需要进行修改:

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,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,2)
plt.imshow(Garr,'Greens')
plt.subplot(1,3)
plt.imshow(Garr,'Blues')
plt.subplot(1,4)
plt.imshow(rgb)
plt.show()

output

本文链接:https://www.f2er.com/3012851.html

大家都在问