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.
I tried something like this:
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:
Why is this so messed up?
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 ]]
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.