Search code examples
pythonnumpypython-imaging-library

Why is the greyscale & B&W images created by Pillow giving a numpy.ndarray that has a 3D shape?


Input:

import numpy as np
from PIL import Image

with Image.open("testimage.png") as img:
    img.convert('L')   # convert to greyscale 
    #img.convert('1')  # convert to B&W
    image_pil = np.asarray(img)  
print(f'{image_pil.shape=}')

Output:

image_pil.shape=(266, 485, 3)

Question:

Why is the shape of image_pil not (266, 485) or (266, 485, 1)? I was expecting a 2D greyscale image but it gave a shape of (266, 485, 3) indicate that it is still a RGB image. Also, .convert('1') had the same outcome. Why are they not shaped(266, 485)?


Solution

  • .convert doesn't change anything to your image, it returns a new image.

    bw = img.convert('L')
    image_pil = np.asarray(bw)
    print(f'{image_pil.shape=}')
    

    prints (266, 485)