以下代码可以直接运行(同目录下需先放一张 dog.jpg 的图片)
from PIL import Image
import numpy as np
import cv2 as cv
from torchvision.io import image
import matplotlib.pyplot as plt
path = 'dog.jpg'
# 🌟1.使用 PIL 打开图片
img_PIL = Image.open(path) # <class 'PIL.PngImagePlugin.PngImageFile'>
img_PIL_numpy = np.array(img_PIL) # numpy (H, W, C)
# 🌟2.使用 OpenCV 打开图片
img_CV = cv.imread(path) # numpy (H, W, C)通道顺序为 BGR
img_CV_RGB = cv.cvtColor(img_CV, code=cv.COLOR_BGR2RGB) # BGR -> RGB
# 🌟3.使用 torchvision.io 打开图片
img_TOI = image.read_image(path) # ByteTensor (C, H, W)
img_TOI_float = img_TOI.float()
# ❤️开始画图
# 🦄️使用PIL库方法展示PIL类型图片,方式为弹出式窗口
# img_PIL.show()
# 🦄️使用 matplotlib展示numpy图片,需(H, W, C),且仅支持float(0,1)或int(0,255),其他情况显示全白
plt.imshow(img_PIL_numpy)
plt.title('img_PIL_numpy', fontsize=16) # 设置图片标题
plt.show()
plt.imshow(img_CV)
plt.title('img_CV', fontsize=16) # 设置图片标题
plt.show()
plt.imshow(img_CV_RGB)
plt.title('img_CV_RGB', fontsize=16) # 设置图片标题
plt.show()
img_TOI = img_TOI.permute(1, 2, 0) # 调整为(H, W, C)
plt.title('img_TOI', fontsize=16) # 设置图片标题
plt.imshow(img_TOI)
plt.show()
img_TOI_float = img_TOI_float.permute(1, 2, 0) # 调整为(H, W, C)
plt.title('img_TOI_float', fontsize=16) # 设置图片标题
plt.imshow(img_TOI_float.int())
plt.show()
结果展示: