Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 339
Nic Avatar asked May 10 '18 19:05

Nic


1 Answers

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.

like image 200
user2357112 supports Monica Avatar answered Sep 22 '22 00:09

user2357112 supports Monica