PIL转tensor 以及 Torch.new()方法使用记录 to_Tensor()和as_Tensor()的区别

from PIL import Image
import matplotlib.pyplot as plt
img_b = Image.new("RGB",(32,32))
plt.imshow(img_b)
plt.show()

在这里插入图片描述
PIL转tensor方法:

  1. 先转numpy,再用torch.from_numpy();
img_b_tensor = torch.from_numpy(np.asarray(img_b))
img_b_tensor.size()
Out[36]: torch.Size([32, 32, 3])
  1. 使用torchvision.transforms
transs = transforms.ToTensor()
img_b_tensor_two = transs(img_b)
img_b_tensor_two.size()
Out[37]: torch.Size([3, 32, 32])

注意:
3. ToTensor()函数会制动将图像size变为chw;
4. 查看ToTensor()函数可知,其思路也是转换成numpy。只不过ToTensor中加入了除以255的步骤,对图像进行了归一化。

class ToTensor(object):
    """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.

    Converts a PIL Image or numpy.ndarray (H x W x C) in the range
    [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
    """

    def __call__(self, pic):
        """
        Args:
            pic (PIL Image or numpy.ndarray): Image to be converted to tensor.

        Returns:
            Tensor: Converted image.
        """
        return F.to_tensor(pic)

    def __repr__(self):
        return self.__class__.__name__ + '()'

def to_tensor(pic):
    """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.

    See ``ToTensor`` for more details.

    Args:
        pic (PIL Image or numpy.ndarray): Image to be converted to tensor.

    Returns:
        Tensor: Converted image.
    """
    if not(_is_pil_image(pic) or _is_numpy_image(pic)):
        raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))

    if isinstance(pic, np.ndarray):
        # handle numpy array
        img = torch.from_numpy(pic.transpose((2, 0, 1)))
        # backward compatibility
        if isinstance(img, torch.ByteTensor):
            return img.float().div(255)
        else:
            return img

    if accimage is not None and isinstance(pic, accimage.Image):
        nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
        pic.copyto(nppic)
        return torch.from_numpy(nppic)

    # handle PIL Image
    if pic.mode == 'I':
        img = torch.from_numpy(np.array(pic, np.int32, copy=False))
    elif pic.mode == 'I;16':
        img = torch.from_numpy(np.array(pic, np.int16, copy=False))
    elif pic.mode == 'F':
        img = torch.from_numpy(np.array(pic, np.float32, copy=False))
    elif pic.mode == '1':
        img = 255 * torch.from_numpy(np.array(pic, np.uint8, copy=False))
    else:
        img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))
    # PIL image mode: L, P, I, F, RGB, YCbCr, RGBA, CMYK
    if pic.mode == 'YCbCr':
        nchannel = 3
    elif pic.mode == 'I;16':
        nchannel = 1
    else:
        nchannel = len(pic.mode)
    img = img.view(pic.size[1], pic.size[0], nchannel)
    # put it from HWC to CHW format
    # yikes, this transpose takes 80% of the loading time/CPU
    img = img.transpose(0, 1).transpose(0, 2).contiguous()
    if isinstance(img, torch.ByteTensor):
        return img.float().div(255)
    else:
        return img

Torch.new()方法用于创建一个新的Tensor,该Tensor的type和device都和原有Tensor一致,且无内容

tensor_two = img_b_tensor.new((5,32,32,3))

tensor_one = img_b_tensor.new(*(5,32,32,3))

tensor_two.size()
Out[43]: torch.Size([4])

tensor_one.size()
Out[44]: torch.Size([5, 32, 32, 3])

tensor_three = img_b_tensor.new()

tensor_three.size()
Out[46]: torch.Size([0])

这在使用的时候,需要加入size参数,注意*(参数)与(参数)导致的新建tensor的size区别
(参数):返回tensor维度是len((维度))
*(参数):返回tensor维度是(参数)
无size参数则为空

to_Tensor()和as_Tensor()的区别
一个会设置/255,一个不会设置
一般用在自定义数据集中的def getitem()函数中,对image数据和labe数据进行处理,to_Tensor用于image,给image进行归一化, as_Tensor用于labe,保持原有标签

a = cv2.imread('图像路径')

b = torch.as_tensor(a.copy(), dtype=torch.int64)

b.max()
Out[32]: tensor(199)

c = F.to_tensor(a.copy())

c.max()
Out[34]: tensor(0.7804)

a.max()
Out[35]: 199
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用中提到,默认情况下,返回的Tensor具有与原始张量相同的torch.dtype和torch.device。也就是说,torch.to_tensor()函数会返回一个具有与输入张量相同数据类型和设备的新张量。 但是需要注意的是,torch.to_tensor()并不是PyTorch中的一个内置函数。实际上,正确的函数名应该是torch.Tensor(),它用于将输入数据换为张量对象。 示例代码如下: ```python import torch # 将Python列表换为张量 data = [1, 2, 3, 4, 5] tensor = torch.Tensor(data) print(tensor) # 将NumPy数组换为张量 import numpy as np data_np = np.array([1, 2, 3, 4, 5]) tensor_np = torch.Tensor(data_np) print(tensor_np) ``` 注意,如果输入数据是多维的,则换后的张量也会具有相应的形状。 所以,torch.to_tensor()并不是正确的函数名,正确的函数名应该是torch.Tensor(),用于将输入数据换为张量对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [【PyTorch系例】torch.Tensor详解和常用操作](https://blog.csdn.net/sazass/article/details/109304327)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [【Pytorch基础教程39】torch常用tensor处理函数](https://blog.csdn.net/qq_35812205/article/details/130442457)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值