栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytorch中transforms和Compose理解

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytorch中transforms和Compose理解

概述

torchvision.transforms主要是用于常见的一些图形变换(裁剪、旋转等)
Compose就是定义对图片的多个变换的操作,从上往下依次执行。

操作

阅读源码下面这么多操作,这里就不写了,官网和其他博客有写具体用法和含义,按需求找就好了。

__all__ = ["Compose", "ToTensor", "PILToTensor", "ConvertImageDtype", "ToPILImage", "Normalize", "Resize", "Scale",
           "CenterCrop", "Pad", "Lambda", "RandomApply", "RandomChoice", "RandomOrder", "RandomCrop",
           "RandomHorizontalFlip", "RandomVerticalFlip", "RandomResizedCrop", "RandomSizedCrop", "FiveCrop", "TenCrop",
           "LinearTransformation", "ColorJitter", "RandomRotation", "RandomAffine", "Grayscale", "RandomGrayscale",
           "RandomPerspective", "RandomErasing", "GaussianBlur", "InterpolationMode", "RandomInvert", "RandomPosterize",
           "RandomSolarize", "RandomAdjustSharpness", "RandomAutocontrast", "RandomEqualize"]

例子1-transforms操作的使用
from torchvision import transforms
from PIL import Image
# 读取文件
img = Image.open('test.jpg')
print(type(img))
print(img.size)
#定义transforms的操作
padding_img = transforms.Pad(padding=10, fill=0)
#使用操作
padded_img = padding_img(img)
print(type(padded_img))
print(padded_img.size)

test.jpg

输出结果


(30, 30)

(50, 50) #由于上下左右都要填充10个像素,所以填充后的size是(30+10+10,30+10+10)
例子2-Compose的使用
from torchvision import transforms
from PIL import Image
# 读取文件
img = Image.open('test.jpg')
print(type(img))
print(img.size)
#定义transforms的操作
padding_img = transforms.Compose([
    transforms.Pad(padding=10,fill=0),
    transforms.Resize((40,40)),
    transforms.ToTensor()
])
#使用操作
padded_img = padding_img(img)
print(type(padded_img))
print(padded_img.size())

输出结果


(30, 30)

torch.Size([3, 40, 40])

可以看到将50,50的图片变为40,40的图片,并转化为tensor类型,由于RGB图片,为三通道,所以torch.Size为([3, 40, 40])

例子3-Compose结合lambda表示式的使用
from torchvision import transforms
from PIL import Image
#定义transforms的操作
padding_img = transforms.Compose([
    # lambda表达式读取文件,string path -> image
    lambda x: Image.open(x).convert('RGB'),
    transforms.Pad(padding=10,fill=0),
    transforms.Resize((40,40)),
    transforms.ToTensor()
])
#使用操作
padded_img = padding_img('test.jpg')
print(type(padded_img))
print(padded_img.size())

输出结果


torch.Size([3, 40, 40])

可以看到lambda表达式得到图片后,会传递给下面的操作继续执行,而此时也只需要根据lambda表示x的类型,输入相应的值,即可。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/618952.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号