python - 从 numpy 数组转换为 RGB 图像

标签 python numpy python-imaging-library

我有三个 (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()

但是生成的图像看起来像噪声:

enter image description here

谁能告诉我我做错了什么?

例如,我的 red_arr 是一个 float 组,如下所示:

enter image description here

最佳答案

在您的评论中,您指定 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/

相关文章:

python-3.x - 使用python从屏幕像素中获取RGB值

python - 从 PIL 中绘制点线或虚线矩形

python - 添加两个带有 2D 掩码的 3D numpy 数组

python - Pandas Dataframe 列的条件计算

python - 我有 Numpy 32 位还是 64 位?

python - 使用 Python Django BeautifulSoup 和 Curl 正确抓取和显示日文字符

python - 从 SymPy 符号定义函数

python - pandas 数据框中的随机选择

python - 如何继承Django变量?

python - 使用内部命令窗口 Python 工具和 Visual Studio 2013 进行调试