Skip to content Skip to sidebar Skip to footer

Store A Numpy.ndarray As An Image, And Then Save The Pixel Values

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

Solution 1:

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 imagefrom skimage import data
camera = data.camera()
print(camera.shape) # (512, 512)# array sampleprint(camera[0:5, 0:5])

[[156157160159158]
 [156157159158158]
 [158157156156157]
 [160157154154156]
 [158157156156157]]

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

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.

Post a Comment for "Store A Numpy.ndarray As An Image, And Then Save The Pixel Values"