Image.open读取PNG文件变成灰度图片

项目场景:

用Image.open读取PNG图片,做深度学习的训练,:

问题描述:

原来的是读取JPG图片,本来的想法是直接应用模型就可以了,发现Image.open会将PNG图片降维成灰度图像,导致模型出错:

解决方案

先用cv2.imread导入读取,再转换为PIL的格式。

下面的代码论证上述的问题过程

import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
%matplotlib inline

path1 = r'E:\DQL\small_intestine\1\1.png'
path2 = r'D:\Python\PyTorch-GAN-master\PyTorch-GAN-master\data\img_align_celeba_sub1\000004.jpg'
I1=cv2.imread(path1)
I2 = cv2.imread(path2)
print('用cv读取的格式大小:')
print('PNG图=',I1.shape,'JPG图=',I2.shape)

I1_cvt2pil = Image.fromarray(cv2.cvtColor(I1,cv2.COLOR_BGR2RGB))  
I2_cvt2pil = Image.fromarray(cv2.cvtColor(I2,cv2.COLOR_BGR2RGB))  

I1_array = np.array(I1_cvt2pil)
I2_array = np.array(I2_cvt2pil)

print('\ncv读取,转换为PIL格式之后:')
print(I1_array.shape,I2_array.shape)

I1_pil = Image.open(path1)
I2_pil = Image.open(path2)
I1_array1 = np.array(I1_pil)
I2_array1 = np.array(I2_pil)

print('\n直接用PIL读取:')
print(I1_array1.shape, I2_array1.shape)

# 展示效果
plt.subplot(1,2,1),plt.imshow(I1_pil)
plt.axis('off')
plt.subplot(1,2,2),plt.imshow(I2_pil)
plt.axis('off')

Image.open读取PNG文件变成灰度图片_第1张图片

你可能感兴趣的:(python,学习记录)