Transforms转换Tensor数据类型、归一化

目录

Transforms用来对图像进行一些变换,转换成具体格式的tensor类型数据。

一、ToTensor()使用:

python 复制代码
from PIL import Image
from torchvision import transforms

#转换成tensor数据类型
img_PIL = Image.open("dataset/train/ants_image/0013035.jpg")

#创建trans_tensor对象,用来对图片进行类型转换
tensor_trans = transforms.ToTensor()
#调用transforms对象的__call__内置函数进行数据类型转换
img_tensor = tensor_trans(img_PIL)

print(img_tensor)

二、tensor数据类型:

tensor是一个封装了神经网络所需参数的特殊数据类型。

三、Normalize()使用:

python 复制代码
from PIL import Image
from torchvision import transforms

#转换成tensor数据类型
img_PIL = Image.open("dataset/train/ants_image/0013035.jpg")

#创建trans_tensor对象,用来对图片进行类型转换
trans_tensor = transforms.ToTensor()
#调用trans_tensor对象的__call__内置函数进行数据类型转换
img_tensor = trans_tensor(img_PIL)

#创建归一化对象,需要给出三维图片上各个维度的均值和方差
trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
#调用trans_norm对象的__call__内置函数进行tensor数据的归一化
img_norm = trans_norm(img_tensor)

四、Resize()使用:

python 复制代码
from PIL import Image
from torchvision import transforms

#转换成tensor数据类型
img_PIL = Image.open("dataset/train/ants_image/0013035.jpg")

#创建trans_tensor对象,用来对图片进行类型转换
trans_tensor = transforms.ToTensor()
#调用trans_tensor对象的__call__内置函数进行数据类型转换
img_tensor = trans_tensor(img_PIL)

#创建对象,用来改变图片尺寸(长,宽)
trans_resize = transforms.Resize((512,512))
#调用trans_resize对象的__call__内置函数进行图片缩放
img_resize = trans_resize(img_PIL)

五、compose()对象:

python 复制代码
from PIL import Image
from torchvision import transforms

#转换成tensor数据类型
img_PIL = Image.open("dataset/train/ants_image/0013035.jpg")

#创建trans_tensor对象,进行图像类型变换
trans_tensor = transforms.ToTensor()
#创建trans_resize对象,宽调整为512,高不变
trans_resize = transforms.Resize(512)

#trans_compose对象用来预设执行流程,先执行trans_resize改变图像维度,再执行trans_tensor转为tensor类型
trans_compose =  transforms.Compose([trans_resize,trans_tensor])
trans_compose(img_PIL)
相关推荐
零售ERP菜鸟10 分钟前
数字系统的新角色:从管控工具到赋能平台
大数据·人工智能·职场和发展·创业创新·学习方法·业界资讯
喵手15 分钟前
Python爬虫实战:数据质量治理实战 - 构建企业级规则引擎与异常检测系统!
爬虫·python·爬虫实战·异常检测·零基础python爬虫教学·数据质量治理·企业级规则引擎
Howie Zphile17 分钟前
奇门遁甲x全面预算 # 双轨校准实务:资本化支出与经营目标设定的奇门-财务融合方案
大数据·人工智能
头发够用的程序员21 分钟前
Python 魔法方法 vs C++ 运算符重载全方位深度对比
开发语言·c++·python
加成BUFF34 分钟前
基于DeepSeek+Python开发软件并打包为exe(VSCode+Anaconda Prompt实操)
vscode·python·prompt·conda·anaconda
大模型任我行34 分钟前
腾讯:Agent视觉隐喻迁移
人工智能·语言模型·自然语言处理·论文笔记
weixin_448119941 小时前
Datawhale Easy-Vibe 202602 第1次笔记
人工智能
52Hz1181 小时前
力扣46.全排列、78.子集、17.电话号码的字母组合
python·leetcode
weixin_509138341 小时前
《智能体认知动力学导论》第7章:应用案例
人工智能·智能体·语义空间·认知动力学
子午1 小时前
【宠物识别系统】Python+深度学习+人工智能+算法模型+图像识别+TensorFlow+2026计算机毕设项目
人工智能·python·深度学习