将numpy.ndarray作为图像存储,然后保存像素值
问题描述:
我目前正在寻找可以在其中存储numpy.ndarray
作为图像,然后保存该图像,并将图像的像素值提取到numpy.ndarray
。具有像素值的numpy.ndarray的维度应与用于创建该图的numpy.ndarray相同。将numpy.ndarray作为图像存储,然后保存像素值
我想是这样的:
def make_plot_store_data(name, data):
plt.figure()
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.savefig(name+".png")
plt.close()
convert = plt.get_cmap(cm.jet)
numpy_output_interweawed = convert(data.T)
为什么会这样搞砸了?
答
这里有一种方法需要512x512 ndarray
,将其显示为图像,将其存储为图像对象,保存图像文件并生成与原始图像形状相同的标准化像素数组。
import numpy as np
# sample numpy array of an image
from skimage import data
camera = data.camera()
print(camera.shape) # (512, 512)
# array sample
print(camera[0:5, 0:5])
[[156 157 160 159 158]
[156 157 159 158 158]
[158 157 156 156 157]
[160 157 154 154 156]
[158 157 156 156 157]]
# display numpy array as image, save as object
img = plt.imshow(camera)
# save image to file
plt.savefig('camera.png')
# normalize img object pixel values between 0 and 1
normed_pixels = img.norm(camera)
# normed_pixels array has same shape as original
print(normed_pixels.shape) # (512, 512)
# sample data from normed_pixels numpy array
print(normed_pixels[0:5,0:5])
[[ 0.61176473 0.6156863 0.627451 0.62352943 0.61960787]
[ 0.61176473 0.6156863 0.62352943 0.61960787 0.61960787]
[ 0.61960787 0.6156863 0.61176473 0.61176473 0.6156863 ]
[ 0.627451 0.6156863 0.60392159 0.60392159 0.61176473]
[ 0.61960787 0.6156863 0.61176473 0.61176473 0.6156863 ]]
你可能会考虑寻找到skimage
模块,除了标准pyplot
方法。这里有一些图像处理方法,它们都是为了与numpy
配合而打造的。希望有所帮助。
当您提供[最小化,完整和可验证的示例](https://*.com/help/mcve)时,它更容易提供帮助。另外,目前还不清楚为什么你的'ndarray'只是因为它被渲染为图像而改变形状。看到我的答案下面的工作示例。 –
另外,你的'convert()'将标量映射到RGBA,如果给定一个'[N×N]'输入数组,它将返回一个'[N,N,4]'矩阵。有关更多信息,请参见['Colormap'文档](http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap)。 –
与此相同的问题:http://*.com/questions/43646838/why-is-image-stored-different-than-the-one-imshowed – ImportanceOfBeingErnest