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

问题描述 投票:0回答:1

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

python image numpy python-imaging-library mask
1个回答
0
投票

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

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

output

© www.soinside.com 2019 - 2024. All rights reserved.