python中图片读取与转化

cv2、PIL、Pytorch对图片的读取及转化

本博客参考了https://blog.csdn.net/qq_33221533/article/details/105873307,因为是篇基础的语法博客,因此未进行排版,只是简略的将代码粘贴到博客中。

在这里插入代码片
import cv2
import numpy as np
from PIL import Image
import torch
import torchvision.transforms as transforms

img_path = r"test.jpg"

# RGB
pil_img = Image.open(img_path)
# pil_img.show()

# cv2读取的图片默认通道是BGR,数据类型为numpy.ndarray,尺寸为HWC
cv_img = cv2.imread(img_path, flags=1)  # cv2读取图片
# cv2.imshow("img", cv_img)  # 展示图片
# cv2.waitKey(0)  # 等待按键

# PIL转np,尺寸为HWC
np_img = np.array(pil_img)

# np转PIL
pil_img2 = Image.fromarray(cv_img) 

#np转tensor, 尺寸为HWC
torch_img = torch.from_numpy(cv_img)
# torch_img = torch.tensor(cv_img)

#PIL与tensor互转
"""
    此处的torch_img与trnsor_img内部的数值不一样,trnsor_img为0-1的数据
"""
tenor_transforms = transforms.Compose([transforms.ToTensor(), ])
trnsor_img = tenor_transforms(pil_img)
pil_transforms = transforms.Compose([transforms.ToPILImage(), ])
pil_img3 = pil_transforms(trnsor_img)



你可能感兴趣的