从numpy数组转换为RGB图像 [英] Converting from numpy arrays to a RGB image

查看:2477
本文介绍了从numpy数组转换为RGB图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个(241,241)numpy数组,我想将它们视为图像的红色,绿色和蓝色分量.

I have three (241, 241) numpy arrays which I would like to treat as the Red, Green and Blue components of an image.

我已经尝试过了:

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

但是生成的图像看起来像是杂色:

But the resulting image just looks like noise:

有人可以告诉我我在做什么错吗?

Can anyone tell me what I am doing wrong please?

例如,我的red_arr是一个如下所示的浮点数组:

As an example, my red_arr is an array of floats that looks like this:

推荐答案

在您的注释中,指定red_arr等是-4000到4000范围内的数组.

In your comment you specify that the red_arr, etc. are arrays of the range -4000 to 4000.

但是,如果我们看一下

But if we take a look at the specifications of the Image.from_array modes, then we see that it expects a matrix of three bytes (values from zero to 255).

但这本身不是问题:我们可以执行:

This is however not per se a problem: we can perform:

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到25​​5的范围,然后将该数组输入PIL.

So first we rescale to a range 0 to 255, and then we feed that array to the PIL.

我们也可能希望以相同的方式缩放红色,绿色和蓝色.在这种情况下,我们可以使用:

It is also possible that we want to scale red, green and blue the same way. In that case we can use:

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

这篇关于从numpy数组转换为RGB图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆