Search code examples
pythonnumpypython-imaging-library

How to convert PIL image to numpy array?


When I do np.asarray(my_img) or array(my_img).shape it returns (2412L, 3600L, 3L) on a jpg image,but I just want a 2D (2412L, 3600L) array, so how to convert it correctly? Thanks in advance.

my_image = "AI.jpg"

from matplotlib.pyplot import imread
from PIL import Image

fname = "images/" + my_image
image = Image.open(fname) 
print(image.size)    # output: (3600, 2412)
print(np.asarray(image).shape) # output: (2412L, 3600L, 3L)
print(np.array(image).shape) # output: (2412L, 3600L, 3L)

Solution

  • If your image dimensions have a 3 for the final axis, that normally means you have a 3-channel RGB image.

    If you want a single channel image, you will lose the RGB colour and just have a greyscale image. You can do that like this:

    grey = Image.open(fname).convert('L')