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

查看:54
本文介绍了如何应用 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)

推荐答案

很忙的单行,但它是:

  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天全站免登陆