36

I am loading image with the following code

image = PIL.Image.open(file_path)
image = np.array(image)

It works, but the size of array appears to be (X, X, 4), i.e. it has 4 layers. I would like normal RGB layers. Is it possible?

UPDATE

I found that just removing 4th channel is unsufficcient. The following code was required:

image = PIL.Image.open(file_path)
image.thumbnail(resample_size)
image = image.convert("RGB")
image = np.asarray(image, dtype=np.float32) / 255
image = image[:, :, :3]

Why?

Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

39

The fourth layer is the transparency value for image formats that support transparency, like PNG. If you remove the 4th value it'll be a correct RGB image without transparency.

EDIT:

Example:

>>> import PIL.Image
>>> image = PIL.Image.open('../test.png')
>>> import numpy as np
>>> image = np.array(image)
>>> image.shape
(381, 538, 4)
>>> image[...,:3].shape
(381, 538, 3)
keredson
  • 3,019
  • 1
  • 17
  • 20
4

As mentioned by other answers, some images are saved with a 4th channel. To load image with just RGB channels without using numpy at all:

from PIL import Image
image = Image.open('../test.png').convert('RGB')
YScharf
  • 1,638
  • 15
  • 20