我想将每个 2D 数组转换为 RGB 图像并将该 RGB 图像返回到另一个函数,我该怎么做。我尝试通过
PIL
和 plt
做到这一点,但它对我不起作用。我尝试了 2 个多星期来寻找如何做到这一点。
如有任何帮助,我们将不胜感激。
for c in [cD5,cD4,cD3,cD2,cD1]:
x = np.linspace(0, 3844, len(c))
f = interp1d(x, c)
result.append(f(common_x))
normalized_result = preprocessing.normalize(result)
我认为这个问题已经解决了,记住如果你想要一个 RGB 图像,你需要 3 个通道,这意味着一个形状为 (NxMx3) 的矩阵。
干杯!
编辑:
这是一个示例,说明如何将 2D 数组堆叠成具有所需形状的 3D 数组。
import numpy as np
#some random arrays i just created for test
r = np.array([3,3,3])
g = np.array([6,6,6])
b = np.array([9,9,9])
bl = np.array([12,12,12])
#create the stacked arrays
stacked = np.dstack((r,g,b,bl))
#check the shape
print(np.shape(stacked))
要从 ndarray 制作 RGB 图像,您必须:1)通过将最大和最小强度分成 3 组等方法将每个 RGB 通道分离为不同的数组,根据原始或 RGB 最小值/最大值来表示像素颜色强度,然后使用 plt.imshow/plt.imsave 显示/保存它们:
from matplotlib.colors import Normalize
from PIL import Image
# example data
arr = np.array([4,3,2,1,-1,-2,-3,-4])
# producing RGB variants by slicing intensity of the data into 3 equal sections
R = np.percentile(arr,100 - 100/3)
B = np.percentile(arr,100/3)
arr_R = np.where(arr >= R, arr, 0)
arr_B = np.where(arr <= B, arr, 0)
arr_G = np.where((arr > B) & (arr < R), arr, 0)
# normalizing arr_RGB to have values between 0-255
def normRGB(a):
mynorm = Normalize(vmin=np.min(a), vmax=np.max(a))
return mynorm(a)
# #Run below if you prefer original array's minimum and maximum
# arr = normRGB(abs(arr)) # absolute values help acknowledging negative values' intensity, exclude them if you mean otherwise
# # otherwise run below if you prefer RGB channels' minimums and maximums
arr_R = normRGB(abs(arr_R)) # absolute values help acknowledging negative values' intensity, exclude them if you mean otherwise
arr_G = normRGB(abs(arr_G))
arr_B = normRGB(abs(arr_B))
# stacking RGB into one ndarray
arr_RGB = np.dstack((arr_R,arr_G,arr_B))
plt.imshow(arr_RGB)
plt.show()
print(arr_RGB)
通过使用相同的 np.dstack() 函数将 arr_RGB 添加在一起,也可以将结果图像堆叠到更高维度的数组(如相册)中。例如:
N = 22 # if there are 22 images
album = np.zeros((N))
for n in range(N):
### Here should be written all above operation with an i index that updates new arr_RGB from dataset[i] during each iteration ###
if n == 0: # if it is the first iteration
album = np.copy(arr_RGB)
elif n > 0: # now that album has been created, it can be stacked on its previous records
album = np.dstack(album, arr_RGB)
print(np.shape(album))