将numpy.ndarray存储为图像,然后保存像素值

时间:2017-04-27 01:51:59

标签: python image numpy matplotlib colormap

我目前正在寻找可以将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)

第一张图片如下所示: enter image description here 第二张图片如下所示:

enter image description here

为什么这么乱?

1 个答案:

答案 0 :(得分:0)

这是一种采用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)

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 ]]

除标准pyplot方法外,您可以考虑查看skimage模块。那里有一堆图像处理方法,它们都是为了与numpy一起玩而构建的。希望有所帮助。