Sun Bear
Sun Bear

Reputation: 8297

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

Upvotes: 0

Views: 40

Answers (1)

chrslg
chrslg

Reputation: 13491

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

Upvotes: 5

Related Questions