Opencv,PIL,Tensor格式相互转化

  • OpenCV (BGR) -> PIL (RGB)

    • 使用cv2.cvtColor()将BGR转换为RGB。
    • 使用Image.fromarray()将NumPy数组转换为PIL图像。
  • PIL (RGB) -> PyTorch (CHW)

    • 使用transforms.ToTensor()将PIL图像转换为PyTorch张量。
  • PyTorch (CHW) -> PIL (RGB)

    • 使用transforms.ToPILImage()将PyTorch张量转换为PIL图像。
  • PIL (RGB) -> OpenCV (BGR)

    • 使用cv2.cvtColor()将RGB转换为BGR。
import cv2
from PIL import Image
import numpy as np
import torch
import torchvision.transforms as transforms

# OpenCV读取图像
cv_image = cv2.imread('path_to_image.jpg')
print(f'OpenCV图像格式 (BGR): {cv_image.shape}')  # (H, W, C)

# OpenCV的BGR格式转换为RGB格式
cv_image_rgb = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
print(f'OpenCV图像格式 (RGB): {cv_image_rgb.shape}')  # (H, W, C)

# 将OpenCV图像转换为PIL图像
pil_image = Image.fromarray(cv_image_rgb)
print(f'PIL图像格式: {np.array(pil_image).shape}')  # (H, W, C)

# 将PIL图像转换为PyTorch张量
transform = transforms.ToTensor()
tensor = transform(pil_image)
print(f'PyTorch张量格式: {tensor.shape}')  # (C, H, W)

# 将PyTorch张量转换回PIL图像
pil_image_from_tensor = transforms.ToPILImage()(tensor)
print(f'PIL图像格式 (从张量转换): {np.array(pil_image_from_tensor).shape}')  # (H, W, C)

# 将PIL图像转换为OpenCV格式 (BGR)
cv_image_from_pil = cv2.cvtColor(np.array(pil_image_from_tensor), cv2.COLOR_RGB2BGR)
print(f'OpenCV图像格式 (从PIL转换): {cv_image_from_pil.shape}')  # (H, W, C)

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值