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