在保留分辨率的同时保存类似imshow的图像 [英] Saving an imshow-like image while preserving resolution
问题描述
我有一个一直用matplotlib.pyplot.imshow
可视化的(n,m)数组.我想将此数据保存在某种类型的光栅图形文件(例如png)中,以便:
I have an (n, m) array that I've been visualizing with matplotlib.pyplot.imshow
. I'd like to save this data in some type of raster graphics file (e.g. a png) so that:
- 颜色是用
imshow
显示的颜色
- 基础数组的每个元素恰好是保存的图像中的一个像素-意味着如果基础数组是(n,m)个元素,则图像为NxM像素. (我对
imshow
中的interpolation='nearest'
不感兴趣.) - 在保存的图像中,除了与数组中的数据相对应的像素以外,没有任何其他内容. (即,边缘,轴等周围没有空格)
- The colors are the ones shown with
imshow
- Each element of the underlying array is exactly one pixel in the saved image -- meaning that if the underlying array is (n, m) elements, the image is NxM pixels. (I'm not interested in
interpolation='nearest'
inimshow
.) - There is nothing in the saved image except for the pixels corresponding to the data in the array. (I.e. there's no white space around the edges, axes, etc.)
我该怎么做?
我已经看到一些代码可以通过使用interpolation='nearest'
并强制matplotlib(勉强地)关闭轴,空格等来实现此目的.但是,必须有某种方法可以更直接地做到这一点-也许与PIL?毕竟,我有基础数据.如果可以为基础数组的每个元素获取RGB值,则可以使用PIL保存它.有什么方法可以从imshow
中提取RGB数据吗?我可以编写自己的代码以将数组值映射为RGB值,但是我不想重新发明轮子,因为该功能已经存在于matplotlib中.
I've seen some code that can kind of do this by using interpolation='nearest'
and forcing matplotlib to (grudgingly) turn off axes, whitespace, etc. However, there must be some way to do this more directly -- maybe with PIL? After all, I have the underlying data. If I can get an RGB value for each element of the underlying array, then I can save it with PIL. Is there some way to extract the RGB data from imshow
? I can write my own code to map the array values to RGB values, but I don't want to reinvent the wheel, since that functionality already exists in matplotlib.
推荐答案
您已经猜到不需要创建图形了.您基本上需要三个步骤.标准化您的数据,应用颜色图,保存图像. matplotlib提供所有必要的功能:
As you already guessed there is no need to create a figure. You basically need three steps. Normalize your data, apply the colormap, save the image. matplotlib provides all the necessary functionality:
import numpy as np
import matplotlib.pyplot as plt
# some data (512x512)
import scipy.misc
data = scipy.misc.lena()
# a colormap and a normalization instance
cmap = plt.cm.jet
norm = plt.Normalize(vmin=data.min(), vmax=data.max())
# map the normalized data to colors
# image is now RGBA (512x512x4)
image = cmap(norm(data))
# save the image
plt.imsave('test.png', image)
虽然上面的代码解释了单个步骤,但是您也可以让imsave
执行所有三个步骤(类似于imshow
):
While the code above explains the single steps, you can also let imsave
do all three steps (similar to imshow
):
plt.imsave('test.png', data, cmap=cmap)
结果(test.png):
Result (test.png):
这篇关于在保留分辨率的同时保存类似imshow的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!