1

PIL、Numpy、OpenCV和Tensor格式的相互转换

 1 year ago
source link: https://xugaoxiang.com/2022/09/27/pil-numpy-opencv-tensor-conversion/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
  • python 3.8
  • pillow 9.2.0
  • opencv 4.6.0.66
  • torch 1.9.1
  • torchvision 0.10.1

一般来说,我们进行图片的读写,用的是 pillowopencv 中的 APIpillow 读取的通道顺序是 RGB,而 opencv 的则是 BGRopencv 中进行图像处理的本质其实是 numpy.ndarray 的操作,而后在神经网络中,又引入了可以使用 gpu 加速计算的张量 tensor,它也是多维数组,本篇就来看看这几种数据格式的相互转换。

直接看代码

import cv2
import numpy as np
from PIL import Image
import torch
from torchvision import transforms

# 测试图片
img_path = 'C:\\Users\\Administrator\\lenna.png'

# 返回值是 PIL.Image.Image 类型
img_pil = Image.open(img_path)

# pil 转换成 numpy.ndarray
img_numpy = np.array(img_pil)
# numpy.ndarray 转化成 pil
img_pil = Image.fromarray(img_numpy)

# pil 转换成 tensor
transform = transforms.Compose([transforms.ToTensor()])
img_tensor = transform(img_pil)
# tensor 转换成 pil
img_pil = transforms.ToPILImage()(img_tensor).convert('RGB')

# pil 转换成 opencv
img_cv = cv2.cvtColor(np.asarray(img_pil), cv2.COLOR_RGB2BGR)
# opencv 转换成 pil,上面已经有了 pil 转其它格式的方法,那对应到 opencv 也是一样,就不往下继续写了
img_pil = Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB))

# tensor 转换成 numpy.ndarray
img_numpy = img_tensor.numpy()
# numpy.ndarray 转换成 tensor
img_tensor = torch.from_numpy(img_numpy)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK