在图像处理和深度学习中,经常需要在PIL(Python Imaging Library)、OpenCV(cv2)、NumPy和PyTorch之间进行图像数据的转换。下面是这些库之间常见的转换方法。文章来源地址https://www.toymoban.com/news/detail-822317.html
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://www.toymoban.com/news/detail-822317.html
到了这里,关于PIL、cv2、numpy,和pytorch(torch)之间的转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!