ToPILImage && ToTensor

在Pytorch创建数据集时,常常会有transform.ToPILImagetransform.ToTensor两个函数,前一个函数是将numpy转变为PILImage形式,第二个函数是将PILImage形式转变为tensor形式方便计算,转换时需要注意以下几点

图片一共有三种形式,PILImage形式,tensor形式以及numpy形式

  • numpy必须为uint8形式,范围为[0, 255]
  • tensor必须为FloatTensor形式,范围为[0, 1]
  • tensor如果要转换为numpy需要乘上255,最好归一化
  • tensor的数据形式为CHW,numpy则为HWC,使用array.transpose(1, 2, 0)进行转化
  • PILImage以及tensor的通道形式均为RGB,而opencv(numpy)的则为BGR,转化时需要用cv2.cvtColor(img,cv2.COLOR_xxx)来进行转化,否则图片颜色会变化
  • PILImage形式的图片显示时用img.show()即可;numpy形式可用opencv进行显示,cv2.imshow("image", array),而tensor形式的图片则需要转化为numpy用opencv显示(可见下面代码)
import cv2
import torchvision.transforms as transforms
import numpy as np
import torch
import matplotlib.pyplot as plt
from PIL import Image


'''PIL image'''
image = Image.open("./food-11/0000.jpg")
print(image)  # <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=384x512 at 0x7F1CFE47DD60>
image2 = transforms.ToTensor()(image)  # to simplify computation
print(image2)  # tensor.data[0, 1]
print(image2.dtype)  # tensor.float32
print(image2.shape)  # tensor.Size([3, 512, 384])
# if you want opencv to support tensor image, you should know below
# opencv support numpy format, dtype is uint8, pixle range [0, 255]
# when use ToTensor, tensor range is [0, 1], dtype is FloatTensor
# channel: PIL && torch:RGB   opencv:BGR
# dimensional: torch: CHW  numpy: HWC
# show tensor
tensor_ = image2
array_ = tensor_.numpy()  # convert tensor to numpy
max = array_.max()
array_ = array_*255/max  # expand pixel from [0, 1] to [0, 255], then normalization
array_convert = np.uint8(array_)  # opencv only support uint8 numpy.array
print("array_convert:", array_convert.shape)  # array_convert: (3, 512, 384)
array_convert = array_convert.transpose(1, 2, 0)  # array_convert: (512, 384, 3)
cv2.imshow("image", array_convert)  # different from the original image
cv2.waitKey()
array_convert = cv2.cvtColor(array_convert, cv2.COLOR_RGB2BGR)  # convert RGB to BGR
cv2.imshow("image2", array_convert)  # the same to the original image
cv2.waitKey()



'''opencv'''
img = cv2.imread("./food-11/0000.jpg")
print(img)  # np.array.data[0, 255]
print(type(img))  # <class 'numpy.ndarray'>
print(img.dtype)  # uint8
print(img.shape)  # (512, 384, 3)
cv2.imshow("img", img)
cv2.waitKey()
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # if don't convert, the image will distort
img2 = transforms.ToPILImage()(img)
img2.show()

如果图片为numpy类型的浮点数float32,可以直接用skimage.img_as_ubyte将其转换为255范围的uint8类型,img=skimage.img_as_ubyte(img)

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
toPIL = transforms.ToPILImage()是一个函数,它可以将张量(tensor)转换为PIL.Image类型的图像。这个函数可以用于将torch.Tensor或numpy.ndarray类型的图像转换为PIL.Image类型的图像。在使用这个函数时,你需要注意指定图像的模式(mode)。\[2\]\[3\] #### 引用[.reference_title] - *1* [Pytorch图像数据格式之间的转换](https://blog.csdn.net/weixin_46081348/article/details/124152484)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [pytorch 张量tensor和图片相互转化](https://blog.csdn.net/qq_43592640/article/details/126443681)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [transforms模块—PyTorch图像处理与数据增强方法](https://blog.csdn.net/chb4715/article/details/128541997)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值