pythonimagenumpyscipynumpy-ndarray

Open / load image as numpy ndarray directly


I used to use scipy which would load an image from file straight into an ndarray.

from scipy import misc
img = misc.imread('./myimage.jpg')
type(img)
>>> numpy.ndarray

But now it gives me a DeprecationWarning and the docs say it will be removed in 1.2.0. and I should use imageio.imread instead. But:

import imageio
img = imageio.imread('./myimage.jpg')
type(img)
>>> imageio.core.util.Image

I could convert it by doing

img = numpy.array(img)

But this seems hacky. Is there any way to load an image straight into a numpy array as I was doing before with scipy's misc.imread (other than using OpenCV)?


Solution

  • The result of imageio.imread is already a NumPy array; imageio.core.util.Image is an ndarray subclass that exists primarily so the array can have a meta attribute holding image metadata.

    If you want an object of type exactly numpy.ndarray, you can use asarray:

    array = numpy.asarray(img)
    

    Unlike numpy.array(img), this will not copy img's data.