Skip to main content
 首页 » 编程设计

python之将图像转换为 numpy 数组,然后立即将其转换回图像会给出两种不同的结果

2024年11月24日6dflying

正如标题所述,我正在将图像转换为 numpy 数组,然后再将其转换回来。这是我的代码:

import os 
import numpy as np 
from PIL import Image 
img = Image.open(os.path.join(no_black_border, png_files[0])) 
img.show() 
 
np_arr = np.asarray(img) 
img1 = Image.fromarray(np_arr) 
img1.show() 

这是我的 before converting it 这是我的 after converting it back

请您参考如下方法:

您的图像不是 RGB,而是调色板图像。这意味着它在每个像素位置都没有红色、绿色和蓝色值,而是在每个位置都有一个 8 位调色板索引,PIL 使用它来了解颜色。转换为 Numpy 数组时,您会丢失调色板。

您有 2 个选择。

打开图像时将图像转换为 RGB,所有 3 个值都将传送到 Numpy:

# Load image and make RGB 
im = Image.open(...).convert('RGB') 
 
# Convert to Numpy array and process 
numpyarray = np.array(im) 

或者,按照您当前的操作,但在转换回 PIL 图像后重新应用原始图像的调色板:

# Load image 
im = Image.open() 
 
# Convert to Numpy array 
numpyarray = np.array(im) 
 
... do Numpy stuff ... 
 
# Convert back to PIL Image and re-apply original palette 
r = Image.fromarray(numpyarray,mode='P')  
r.putpalette(im.getpalette()) 
 
# Optionally save 
r.save('result.png') 

查看答案 here以及随附的评论。