如何使用matplotlib颜色图将NumPy数组转换为PIL图像 [英] How to convert a NumPy array to PIL image applying matplotlib colormap

查看:473
本文介绍了如何使用matplotlib颜色图将NumPy数组转换为PIL图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,但是找不到一个好的解决方案.

I have a simple problem, but I cannot find a good solution to it.

我想获取一个代表灰度图像的NumPy 2D数组,并在应用一些matplotlib色彩图的同时将其转换为RGB PIL图像.

I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps.

我可以使用pyplot.figure.figimage命令获得合理的PNG输出:

I can get a reasonable PNG output by using the pyplot.figure.figimage command:

dpi = 100.0
w, h = myarray.shape[1]/dpi, myarray.shape[0]/dpi
fig = plt.figure(figsize=(w,h), dpi=dpi)
fig.figimage(sub, cmap=cm.gist_earth)
plt.savefig('out.png')

尽管我可以对此进行修改以得到我想要的(可能使用StringIO来获取PIL图像),但我想知道是否没有更简单的方法来做到这一点,因为这似乎是图像可视化的一个非常自然的问题.假设是这样的:

Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this:

colored_PIL_image = magic_function(array, cmap)

推荐答案

非常繁忙的一线客,但这里是:

Quite a busy one-liner, but here it is:

  1. 首先确保将您的NumPy数组myarray的最大值标准化为1.0.
  2. 将颜色图直接应用于myarray.
  3. 重新调整为0-255范围.
  4. 使用np.uint8()转换为整数.
  5. 使用Image.fromarray().
  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

您已经完成:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

plt.savefig():

im.save():

这篇关于如何使用matplotlib颜色图将NumPy数组转换为PIL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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