Using Spyder / Python to Open .npy File

95,888

Solution 1

*.npy files are binary files to store numpy arrays. They are created with

import numpy as np

data = np.random.normal(0, 1, 100)
np.save('data.npy', data)

And read in like

import numpy as np
data = np.load('data.npy')

Solution 2

Given that you asked for Spyder, you need to do two things to import those files:

  1. Select the pane called Variable Explorer
  2. Press the import button (shown below), select your .npy file and present Ok.

    import button

Then you can work with that file in your current Python or IPython console.

Solution 3

import numpy as np
from matplotlib import pyplot as plt
import matplotlib
import glob


for filename in glob.glob("*.*"):
    if '.npy' in filename:
        img_array = np.load(filename, allow_pickle=True)
        plt.imshow(img_array, cmap="gray")
        img_name = filename+".png"
        matplotlib.image.imsave(img_name, img_array)
        print(filename)

creates a png file for each image in the current directory that is of the format .npy. For example, I have this RGB image enter image description here and its depth image is in .npy format. Converting it to png gives me so: enter image description here

Solution 4

.npy files are binary files. Do not try to open it with Spyder or any text editor; what you see may not make sense to you.

Instead, load the .npy file using the numpy module (reference: http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.load.html).

Code sample:

First, import numpy. If you do not have it, install (here's how: http://docs.scipy.org/doc/numpy/user/install.html)

>>> import numpy as np

Let's set a random numpy array as variable array.

>>> array = np.random.randint(1,5,10)
>>> print array
[2 3 1 2 2 3 1 2 3 3]

To export to .npy file, use np.save(FILENAME, OBJECT) where OBJECT = array

>>> np.save('test.npy', array)

You can load the .npy file using np.load(FILENAME)

>>> array_loaded = np.load('test.npy')

Let's compare the original array vs the one loaded from file (array_loaded)

>>> print 'Loaded:  ', array_loaded
Loaded:   [2 3 1 2 2 3 1 2 3 3]

>>> print 'Original:', array
Original: [2 3 1 2 2 3 1 2 3 3]

Solution 5

Just use the full path of the .npy file. For example,

import numpy as np
data = np.load('/home/user/npyfolder/npyfile.npy')
print(data)
# Or Either save it to the text file or something.

I was also having the path issue, but When I changed the path from relative to an absolute path, It worked.!

Share:
95,888
iron2man
Author by

iron2man

Updated on February 05, 2021

Comments

  • iron2man
    iron2man about 3 years

    Sorry. I'm just now learning Python and everything there is to do with data analysis.

    How on earth do I open a .npy file with Spyder? Or do I have to use another program? I'm using a Mac, if that is at all relevant.