tensor如何转为图像_在Pytorch中,是如何把图片转换成tensor的?

本文介绍了如何在Pytorch中将图像转换为Tensor,主要涉及torchvision.transforms的to_tensor函数。该函数首先检查输入类型,如果是numpy数组,则进行维度调整并转化为Tensor;如果是PIL Image,会根据模式转换并进行CHW格式转置,最后除以255。源码中的一条注释指出,transpose操作占据了加载时间的80%,暗示可能的性能优化方向。
摘要由CSDN通过智能技术生成

要学会看源码啊...

最近google 上不去,就用bing来举例好了,一般来讲,看了各种example代码以后,发现transformer 里面有一个 totensor,所以直接搜索torchvision.transforms,看里面的文档,在文档里面搜索to_tensor,里面有对这个函数的解释,然后查看源码 ,源码如下:

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

if pic.ndim == 2:

pic = pic[:, :, None]

img = torch.from_numpy(pic.transp

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值