Skip to content
Advertisement

Viewing .npy images

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

Advertisement

Answer

.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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement