将图像(png和jpg)转换为多维列表,然后在python中向后转换

问题描述 投票:3回答:1

我使用PIL将图像转换为单色,然后转换为列表列表,但我不知道如何使用rgb图像。

有人可以给我一个方向如何将图像转换为多维列表并向后转换python?

python image-processing python-imaging-library
1个回答
5
投票

让我们从一个已知的样本图像开始。这是一个小的3x2实际工作和一个更大的一个,所以你可以看到它:

小:

enter image description here

大:

enter image description here

你可以打开一个图像,并将其变成一个高效,快速的numpy多维数组,如下所示:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Open image from disk
im = Image.open('image.png')
na = np.array(im)

这将是这样的:

array([[[255,   0,   0],                      # Red
        [  0, 255,   0],                      # Green
        [  0,   0, 255]],                     # Blue

       [[  0,   0,   0],                      # Black
        [255, 255, 255],                      # White
        [126, 126, 126]]], dtype=uint8)       # Mid-grey

并将其转换回PIL图像并像这样保存(只需将此代码附加到上面的代码中):

# Convert array back to Image
resultim = Image.fromarray(na)
resultim.save('result.png')

一些说明:

注1

如果你期望并想要一个RGB888图像,并且你正在打开一个PNG图像,你可能得到一个没有每个像素RGB值的palettised图像,而是每个像素的调色板都有一个索引,一切都会出错!

举例来说,这里是与上面相同的图像,但是当生成应用程序将其保存为palettised图像时:

array([[0, 1, 2],
       [3, 4, 5]], dtype=uint8)

这里是从im.getpalette()返回的:

[255,
 0,
 0,
 0,
 255,
 0,
 0,
 0,
 255,
 0,
 0,
 0,
 255,
 255,
 255,
 126,
 126,
 126,
 ...
 ...

所以,故事的寓意是......如果您期待RGB888图像,请使用:

Image.open('image.png').convert('RGB')

笔记2

同样,如果你打开一个包含透明度的PNG文件,它将有4个通道,最后一个是alpha / transparency,如果你想丢弃alpha通道,你应该调用convert('RGB')

注3

如果您不想要中间图像,可以将加载和保存缩写为单行:

# Load and make array in one go
na = np.array(Image.open('image.png').convert('RGB'))

# Convert back to PIL Image and save in one go
Image.fromarray(na).save('result.png')

关键词:图像,图像处理,numpy,数组,ndarray,PIL,Pillow,Python,Python3,调色板,PNG,JPG

© www.soinside.com 2019 - 2024. All rights reserved.