如何将灰度Matplotlib图保存到numpy数组 [英] How to save a greyscale matplotlib plot to numpy array
问题描述
例如,我使用matplotlib绘制图形,如下所示:
For example, I plot a figure using matplotlib as follows:
plt.figure(figsize=(10,10))
plt.imshow(output_fig, zorder=0,cmap="gray")
plt.scatter(x,y,color='k')
如果我使用:
plt.savefig(figname,fotmat=figtype)
我将其另存为图形文件.但是,我希望将其保存到矩阵或numpy数组中,以便每个元素都保存图形中每个像素的比例值.我怎样才能做到这一点?我找到了保存RGB值的解决方案.但是我希望保存一个灰度图.谢谢大家的帮助!
I will save it as a figure file. However, I want so save it to a matrix, or numpy array, such that each element saves the scale value of each pixel of the figure. How can I do this? I find solutions saving the RGB values. But I hope to save a greyscale figure. Thank you all for helping me!
推荐答案
一旦有了绘制的数据(下面是自包含的示例):
Once you have a ploted data (self contained example bellow):
import numpy as np
import matplotlib.pyplot as plt
from skimage import data, color
img = data.camera()
x = np.random.rand(100) * img.shape[1]
y = np.random.rand(100) * img.shape[0]
fig = plt.figure(figsize=(10,10))
plt.imshow(img,cmap="gray")
plt.scatter(x, y, color='k')
plt.ylim([img.shape[0], 0])
plt.xlim([0, img.shape[1]])
可以使用 fig.canvas
(matplotlib的画布)将基础数据恢复为数组.首先触发其绘制:
The underlying data can be recovered as array by using fig.canvas
(the matplotlib's canvas). First trigger its drawing:
fig.canvas.draw()
获取数据作为数组:
width, height = fig.get_size_inches() * fig.get_dpi()
mplimage = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)
如果您希望数组与原始图像具有相同的形状,则必须使用 plt.figure()的
. figsize
和 dpi
属性进行播放
If you want your array to be the same shape as the original image you will have to play with figsize
and dpi
properties of plt.figure()
.
最后,如果需要灰度,matplotlib将返回RGB图像:
Last, matplotlib returns an RGB image, if you want it grayscale:
gray_image = color.rgb2gray(mplimage)
这篇关于如何将灰度Matplotlib图保存到numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!