2017-04-27 79 views
0

我目前正在尋找可以在其中存儲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) 

第一圖像看起來是這樣的: enter image description here 第二圖像看起來是這樣的:

enter image description here

爲什麼會這樣搞砸了?

+0

當您提供[最小化,完整和可驗證的示例](https://stackoverflow.com/help/mcve)時,它更容易提供幫助。另外,目前還不清楚爲什麼你的'ndarray'只是因爲它被渲染爲圖像而改變形狀。看到我的答案下面的工作示例。 –

+0

另外,你的'convert()'將標量映射到RGBA,如果給定一個'[N×N]'輸入數組,它將返回一個'[N,N,4]'矩陣。有關更多信息,請參見['Colormap'文檔](http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap)。 –

+1

與此相同的問題:http://stackoverflow.com/questions/43646838/why-is-image-stored-different-than-the-one-imshowed – ImportanceOfBeingErnest

回答

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

你可能會考慮尋找到skimage模塊,除了標準pyplot方法。這裏有一些圖像處理方法,它們都是爲了與numpy配合而打造的。希望有所幫助。