pytorch -- 常见的transform包方法

1. 基础

PIL Image -> Image.open
tensor -> ToTensor() [Convert a PIL Image or ndarray to tensor]
ndarray -> cv2.imread

2. 常见方法

(1)ToTensor
将PIL/numpy ndarry转化为tensor

from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
img_path = "dataset/train/bees/36900412_92b81831ad.jpg"
writer = SummaryWriter("logs")
img = Image.open(img_path)
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
# writer.add_image("Totensor",img_tensor)
# writer.close()

(2)Normalize归一化

trans_norm = transforms.Normalize([0.3,0.3,0.3],[0.1,0.2,0.3])
img_norm = trans_norm(img_tensor)
writer.add_image("Normalize",img_norm)
writer.close()

(3)Resize

trans_resize = transforms.Resize((512,512))
# PIL image => PIL image
img_resize = trans_resize(img)
# PIL image => tensor
img_resize = trans_totensor(img_resize)
writer.add_image("Resize",img_resize,0)
writer.close()

(4)Compose 组合多个tranforms

transforms.Compose([
    transforms.CenterCrop(10),
    transforms.ToTensor()
])

例子

trans_resize_2 = transforms.Resize(512)
trans_compose = transforms.Compose([trans_resize_2,trans_totensor])
img_resize_2 = trans_compose(img)
writer.add_image("Resize",img_resize_2,1)
writer.close()

(5)RandomCrop 随机裁剪

trans_randomCrop =  transforms.RandomCrop((100,100))
trans_compose_2 = transforms.Compose([trans_randomCrop,trans_totensor])
for i in range(10):
    img_crop = trans_compose_2(img)
    writer.add_image("RandomCrop",img_crop,i)
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值