我有三个 (241, 241) 个 numpy 数组,我想将它们视为图像的红色、绿色和蓝色分量。
我试过这个:
import numpy as np
from PIL import Image
arr = np.zeros((len(x), len(z), 3))
arr[:,:,0] = red_arr
arr[:,:,1] = green_arr
arr[:,:,2] = blue_arr
img = Image.fromarray(arr, 'RGB')
img.show()
但是生成的图像看起来像噪声:
谁能告诉我我做错了什么?
例如,我的 red_arr 是一个 float 组,如下所示:
最佳答案
在您的评论中,您指定 red_arr
等是 -4000 到 4000 范围内的数组。
但是如果我们看一下 Image.from_array
modes 的规范, 然后我们看到它需要一个包含三个 字节 的矩阵(值从零到 255)。
但这本身不是问题:我们可以执行:
def rescale(arr):
arr_min = arr.min()
arr_max = arr.max()
return (arr - arr_min) / (arr_max - arr_min)
red_arr_b = 255.0 * rescale(red_arr)
green_arr_b = 255.0 * rescale(green_arr)
blue_arr_b = 255.0 * rescale(blue_arr)
arr[:,:,0] = red_arr_b
arr[:,:,1] = green_arr_b
arr[:,:,2] = blue_arr_b
img = Image.fromarray(arr.astype(int), 'RGB')
因此,首先我们重新缩放到 0 到 255 的范围,然后将该数组提供给 PIL。
我们也可能希望以相同的方式缩放红色、绿色和蓝色。在这种情况下,我们可以使用:
def rescale(arr):
arr_min = arr.min()
arr_max = arr.max()
return (arr - arr_min) / (arr_max - arr_min)
arr[:,:,0] = red_arr
arr[:,:,1] = green_arr
arr[:,:,2] = blue_arr
arr = 255.0 * rescale(arr)
img = Image.fromarray(arr.astype(int), 'RGB')
关于python - 从 numpy 数组转换为 RGB 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571486/