使用 matplotlib 显示彩色图像

详细说明见代码注释

"""
介绍如何使用 matplotlib 输入、输出 彩色图像,并简要介绍如何将数组表示形式的图像数据显示为图像
"""
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

# 读入一幅彩色图片
img_path = 'demo.jpg'   # 读入当前文件目录下的 demo.jpg
img = Image.open(img_path)

# 显示图片
plt.figure("Image")     # 图像窗口名称
plt.imshow(img)
plt.axis('on')  # 关掉坐标轴为 off
plt.title('image')  # 图像题目
plt.show()

# --------------------------------一般神经网络中对图像的处理(部分)--------------------------------------------------
# 打印图像的PTL存储形式
print(img)
# 将图片转成numpy数组(这是图像处理过程中必然使用的一步),并将原来的int像素值改成float类型
img = np.asarray(img, dtype=float)
print(img)  # 打印numpy的存储形式
# 转换3通道图像的数组格式 : transpose (H, W, C) -> (C, H, W)
img = img.transpose((2, 0, 1))
print(img)  # 打印转换通道之后的存储形式
# ----------------------------------------------------------------------------------

# 讲过上面处理过后,通常得到一副图像的数组表示形式,如:[3, 375, 500] 分别表示图形的通道数、高、宽
# 但图像一般的存储格式为:[375, 500, 3] 及高、宽、通道数
# 所以要对数组形式做一定的改变才能正常显示
# 首先转换数据类型:float -> int
img = np.asarray(img, dtype=int)
# 然后转换存储格式
img = img.transpose((1, 2, 0))    # transpose (C, H, W) -> (H, W, C)
# 之后便可正常显示图片
plt.imshow(img)
# plt.show()    移到最后,防止下面存储图片时得到空白图

# 有些公布的开源神经网络代码中可能无法使用 matplotlib 输出显示图片,但可以直接将图片存储下来
# 存储图片
# 但是要注意,在存储图片之前,一定要保留住图片的信息,比如不能使用 plt.show() ,否则图片信息被输出,则会得到一张空白图
plt.savefig('{}_save.jpg'.format(img_path.split('.')[0]))

plt.show()
原文地址:https://www.cnblogs.com/zishu/p/11665141.html