Python 如何将 RGB PIL 图像转换为具有 3 个通道的 numpy 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44955656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert RGB PIL image to numpy array with 3 channels?
提问by Dims
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?
它可以工作,但数组的大小似乎是(X, X, 4)
,即它有 4 层。我想要普通的 RGB 层。是否可以?
UPDATE
更新
I found that just removing 4th channel is unsufficcient. The following code was required:
我发现仅仅删除第 4 个通道是不够的。需要以下代码:
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?
为什么?
回答by keredson
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.
第四层是支持透明度的图像格式的透明度值,如 PNG。如果您删除第 4 个值,它将是一个没有透明度的正确 RGB 图像。
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)