Mati Codes
# _  _ ____ ___ _    ____ ____ ___  ____ ____ #
# |\/| |__|  |  |    |    |  | |  \ |___ [__  #
# |  | |  |  |  |    |___ |__| |__/ |___ ___] #
#                                             #
# _  _ ____ ___ _    ____ ____ ___  ____ ____ #
# |\/| |__|  |  |    |    |  | |  \ |___ [__  #
# |  | |  |  |  |    |___ |__| |__/ |___ ___] #
#                                             #

Dec. 22, 2020

HOW TO CONVERT PILLOW (PIL) IMAGE TO 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)
>>>

Tags

python, computer graphics, pillow, numpy, image manipulation, PIL

Comments

Leave a Reply

>>>
>>>
>>>
>>>
cancel