将numpy.ndarray存储为图像,然后保存像素值 [英] Store a numpy.ndarray as an image, and then save the pixel values
问题描述
我目前正在寻找可以将numpy.ndarray
作为图像存储,然后保存该图像,并将图像的像素值提取到numpy.ndarray
中的位置.具有像素值的numpy.ndarray的尺寸应与用于创建绘图的numpy.ndarray的尺寸相同.
I am currently looking for at in which i can store a numpy.ndarray
as an image, then save that image, and extract the pixel values of the image into a numpy.ndarray
. The dimension of the numpy.ndarray with the pixel values should be the same as the numpy.ndarray what was used to create the plot.
我尝试过这样的事情:
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)
第一个图像如下所示: 第二张图片如下所示:
The first image looks like this: The second image looks like this:
为什么这么乱呢?
推荐答案
这是采用512x512 ndarray
的一种方法,将其显示为图像,将其存储为图像对象,保存图像文件并生成规范化与原始形状相同的像素阵列.
Here's one approach that takes a 512x512 ndarray
, displays it as an image, stores it as an image object, saves an image file, and generates a normalized pixel array of the same shape as the original.
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
一起很好地玩.希望有帮助.
You might consider looking into the skimage
module, in addition to standard pyplot
methods. There are a bunch of image manipulation methods there, and they're all built to play nice with numpy
. Hope that helps.
这篇关于将numpy.ndarray存储为图像,然后保存像素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!