How to Convert a Pillow (PIL) Image to a Numpy Array FAST!
There are a few ways to convert a pillow (PIL) image to a numpy array. If you’re working with large images or a high number of images, you really want to make sure you’re using the fastest and memory efficient conversion.
I’ll keep this one short and sweet. You want to use numpy.asarray
and just pass your image object right into it. Avoid anything that
involves lists or Image.getdata
. Here’s an example:
import numpy as np
from PIL import Image
img = Image.open(filepath)
# datatype is optional, but can be useful for type conversion
data = np.asarray(img, dtype=np.uint8)