Pytorch的第零步:数据IO

常用的数据集在 torchvision.datasets 里都已经编码好了,用户只需要读取以及按需 transform 就好了。但如果很不幸我们拿到的是原始的一堆图片以及一堆 .txt 标签,那么对数据的准备工作量将大大增加。
首当其冲的问题就是数据读取。读取图片方式有很多,比如 matplotlib.pyplot.imread(),PIL库或者openCV等等。但这些库都需要再把读入的非 Tensor 类型转换成 Tensor 类型,比较麻烦。实际上 torchvision 提供了部分 图像、音频和视频的 IO 函数,用它们读取可直接得到 Tensor ,除了读取,还支持保存图片视频等。

如果需要用额外的包读图像,最好还是用 PIL,因为pytorch源码里就是用到了 PIL 读取图像。

读写 .JPG

import torchvision as tv

# 读
"""
torchvision.io.read_image(path: str) → torch.Tensor
>>>Reads a JPEG or PNG image into a 3 dimensional RGB Tensor. 
>>>The values of the output tensor are uint8 between 0 and 255.

**path** 
[str] – path of the JPEG or PNG image.

**output**
[tensor] – [3, image_height, image_width]  ([C, H, W])
"""
picTensor = tv.io.read_image("testpic.jpg")

# 写
"""
torchvision.io.write_jpeg(input: torch.Tensor, filename: str, quality: int = 75)
>>>Takes an input tensor in CHW layout and saves it in a JPEG file.
**input** 
Tensor : [channels, image_height, image_width] 
– int8 image tensor of C channels, where C must be 1 or 3.

**filename** 
str
– Path to save the image.

**quality** 
int
– Quality of the resulting JPEG file, it must be a number between 1 and 100. Default: 75

"""
tv.io.write_jpeg(picTensor, './outTensorPic.jpg')

其他的可自行查看 torchvision.io 的说明

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值