Viewing .npy images

Question:

How can I view images stored with a .npy extension and save my own files in that format?

Asked By: Joshua Jenkins

||

Answers:

.npy is the file extension for numpy arrays – you can read them using numpy.load:

import numpy as np

img_array = np.load('filename.npy')

One of the easiest ways to view them is using matplotlib’s imshow function:

from matplotlib import pyplot as plt

plt.imshow(img_array, cmap='gray')
plt.show()

You could also use PIL or pillow:

from PIL import Image

im = Image.fromarray(img_array)
# this might fail if `img_array` contains a data type that is not supported by PIL,
# in which case you could try casting it to a different dtype e.g.:
# im = Image.fromarray(img_array.astype(np.uint8))

im.show()

These functions aren’t part of the Python standard library, so you may need to install matplotlib and/or PIL/pillow if you haven’t already. I’m also assuming that the files are either 2D [rows, cols] (black and white) or 3D [rows, cols, rgb(a)] (color) arrays of pixel values.

enter image description here

Answered By: ali_m

Thanks Ali_m. In my case I inspect the npy file to check how many images was in the file with:

from PIL import Image
import numpy as np
data = np.load('imgs.npy')

data.shape

then I plotted the images in a loop:

from matplotlib import pyplot as plt

for i in range(len(data)):
  plt.imshow(data[i], cmap='gray')
  plt.show()
Answered By: Vinícius Junior
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.