PIL、cv2、numpy,和pytorch(torch)之间的转换

发布时间:2024年01月20日

在图像处理和深度学习中,经常需要在PIL(Python Imaging Library)、OpenCV(cv2)、NumPy和PyTorch之间进行图像数据的转换。下面是这些库之间常见的转换方法。

1. PIL和numpy之间的转换

import numpy as np
from PIL import Image


image_path = "./"
pil_image = Image.open(image_path)
numpy_image = np.array(pil_image)
#从PIL转换到numpy
pil_image = Image.fromarray(numpy_image)
#从numpy转换到PIL

2. cv2和numpy之间的转换

import cv2
import numpy as np


image_path = "./"
opencv_image = cv2.imread(image_path)
numpy_image = np.array(opencv_image)
#从cv2到numpy的转换
opencv_image = cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)  
# 从numpy到cv2的转换。
#如果是RGB图像,要进行颜色空间转换

3.numpy和pytorch之间的转换

import torch
import numpy as np

numpy_image = np.array()  
# NumPy数组
torch_image = torch.from_numpy(numpy_image)
#从numpy到torch的转换
numpy_image = torch_image.numpy()
#从torch到numpy的转换

4.PIL和torch之间的转换

import torch
from PIL import Image
import torchvision.transforms as transforms


image_path = "./"
pil_image = Image.open(image_path)

# 定义转换操作
transform = transforms.ToTensor()

# 应用转换操作
torch_image = transform(pil_image)
#从PIL到torch的转换
pil_image = transforms.ToPILImage()(torch_image)
#从torch到PIL的转换

5.cv2和pytorch之间的转换

import torch
import cv2
import numpy as np
import torchvision.transforms as transforms

image_path = "./"
cv2_image = cv2.imread(image_path)
cv2_image = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2RGB)  
# 转换为RGB格式

# 定义转换操作
transform = transforms.Compose([
    transforms.ToTensor(),
])

torch_image = transform(cv2_image)
# 将NumPy数组转换为PyTorch张量
cv2_image = cv2.cvtColor(torch_image, cv2.COLOR_RGB2BGR)
# 将torch转换为cv2

6.PIL和cv2之间的转换

import cv2
from PIL import Image

image_path ="./"
pil_image = Image.open(image_path)

# PIL图像转换为cv2图像
cv2_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
# cv2图像转换为PIL图像
pil_image = Image.fromarray(cv2.cvtColor(cv2_image, cv2.COLOR_BGR2RGB))

文章来源:https://blog.csdn.net/kuailezzf/article/details/135684494
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。