【Python】三种读取图片和显示图片的方法 pillow opencv torchvision

以下代码可以直接运行(同目录下需先放一张 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()

结果展示:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值