PyTorch自定义Transform模块(torchvision)-深度学习

torchvision的使用(transforms用法介绍) 介绍 torchvision是pytorch的一个图形库,它服务于PyTorch深度学习框架的,主要用来构建计算机视觉模型。torchvision.transforms主要是用于常见的一些图形变换。以下是torchvision的构成: torchvision.datasets: 一些加载数据的函数及常用的数据集接口; torchvision.models: 包含常用的模型结构(含预训练模型),例如AlexNet、VGG、ResNet等; torchvision.transforms: 常用的图片变换,例如 阅读详情

版权归属:

更多关注:

1 问题

PyTorch实现image-to-image时,需要对image pair进行相同参数的transform(i.e. sync),torchvision已经实现了多种针对single image的transform,但是在使用时input image与target image的transform不一致,上网查阅没有发现好的方法,因此只能自己实现。查看了TorchVision的Transform代码,自己也是可以仿照实现。

2 Random Scale and Crop原理

在这里插入图片描述
将原始图片放大scale=r倍,为了满足crop后的图片中间的蓝色区域没有被分割遗漏,就需要满足crop size > min crop size,进而得到r > 2n/(m+n)。
如果将n=256, m=172带入,r大概1.2左右。反过来如果令r在[1.0, 1.2]之间那么m=170.6,实际中取m=170 or 172。

3 实现代码

Talk is cheap, show me the code.

#coding=utf-8
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
import random
import numpy as np
from PIL import Image
import numbers
import collections
import sys

if sys.version_info < (3, 3):
    Sequence = collections.Sequence
    Iterable = collections.Iterable
else:
    Sequence = collections.abc.Sequence
    Iterable = collections.abc.Iterable



def get_sync_transform(opt):
    transform_list = []

    osize = [opt.loadSize, opt.loadSize]
    transform_list.append(Resize(osize, Image.BILINEAR))
    transform_list.append(RandomScaleCrop())

    if opt.isTrain and not opt.no_flip:
        transform_list.append(transforms.RandomHorizontalFlip())

    transform_list += [ToTensor(),
                       Normalize(<
torchvision中Transform的normalize参数含义 比如原来的tensor是三个维度的,值在0到1之间,经过以下变换之后就到了-1到1区间。 transforms.Normalize((.5,.5,.5),(.5,.5,.5)) transforms的源码中解释: input[channel] = (input[channel] - mean[channel]) / std[channel] 假设你数据的范围是图片的数据范围四[0,1],那么如果... 阅读详情

相关推荐

pytorch中的torchvision.transforms模块详解

torchvision.transforms torchvision.transforms是pytorch中的图像预处理包,包含了很多种对图像数据进行变换的函数,这些都是在我们进行图像数据读入步骤中必不可少的。 data_transforms = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTens

qq_28505705的博客 2108

pytorch中torchvision数据集的使用——CIFAR-10dataset数据集

pytorch中torchvision数据集的使用

m0_54291751的博客 5377

PyTorch与torchvision版本匹配:原理、查询与安装全指南

在深度学习与计算机视觉开发中,环境配置的稳定性是项目成功的基石。其核心原理在于确保核心框架与扩展工具包之间的二进制兼容性和API一致性。PyTorch作为主流深度学习框架,其官方视觉库torchvision高度依赖特定版本的PyTorch底层接口。版本不匹配会直接导致二进制扩展模块链接错误、API调用失败或CUDA运行时冲突,严重影响开发效率。从工程实践角度看,这涉及ABI兼容性、Python API演变及CUDA工具链绑定等关键技术点。尤其在模型训练、部署及复现等应用场景中,精确的版本对应是保证代码可复现

weixin_30457551的博客 517

【Python深度学习】零基础掌握Pytorch转换Transforms

通过这篇教程学习了如何使用ToTensor()和来处理的图像数据。就像学习一门新语言一样,一开始可能会觉得有点复杂,但是一旦掌握了基本的转换技巧,就能更轻松地与深度学习模型进行交流了。ToTensor()帮把图像转换成了计算机更容易理解的张量格式,就好比把文字从书本上转录到电脑上。而则更像是一个多功能的翻译器,无论有多奇怪的要求,它都能帮实现,比如把彩色图变成黑白图,或者进行其他更复杂的操作。掌握这些数据转换的技巧,对于学习和应用深度学习非常重要。

Mr数据杨 751

pytorch中的transforms模块实例详解

今天小编就为大家分享一篇pytorch中的transforms模块实例详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

Android投屏开发实战:手把手教你用Miracast实现Sink端功能(附完整代码)

本文是一份Android投屏Sink端开发的实战指南,详细讲解了如何利用Miracast协议和Wi-Fi P2P技术,从零构建一个功能完整的屏幕接收器。内容涵盖环境搭建、通过反射启用WFD Sink模式、RTSP协议协商、RTP流接收与解析,以及最终使用IjkPlayer进行音视频解码播放的全过程,并附有核心代码示例。

cherry的博客 881

PaddleOCR转ONNX模型实战:5分钟搞定中文OCR推理部署(附完整代码)

本文详细介绍了将PaddleOCR模型转换为ONNX格式并进行高效推理部署的完整实战方案。通过Paddle2ONNX工具实现模型转换,利用ONNX Runtime构建跨平台推理引擎,涵盖环境配置、模型优化、批量处理及多平台部署等关键步骤,显著提升中文OCR在边缘设备上的推理性能。

weixin_29051811的博客 617

实战演练:用wvp-GB28181-pro + ZLMediaKit搭建一个可用的国标视频监控测试环境(附设备模拟器对接)

本文详细介绍了如何使用wvp-GB28181-pro和ZLMediaKit在Ubuntu系统上搭建GB28181视频监控测试环境。从环境准备、组件解析到核心服务部署与设备模拟器对接,提供完整的实战指南,帮助开发者快速构建可验证的监控系统。

weixin_42692935的博客 580

ADS与Cadence中Verilog-A文件的编译与调用实战指南

本文详细介绍了在ADS与Cadence平台中Verilog-A文件的编译与调用实战指南,涵盖开发环境配置、模型创建与编译、仿真设置技巧以及跨平台协作与调试等内容。通过具体案例和优化策略,帮助工程师高效完成混合信号仿真设计,提升电路建模与验证效率。

weixin_29196315的博客 498

02 HCM CPI SF集成-组织集成(一)

将员工主数据和组织数据从SAP Successfactors Employee CentraI复制到SAPERP或SAP S/4HANA,SAP SF CPI HCM集成

SAP CPI 130

95.qt qml-诺谦通用可扩展多功能QML界面

如下图所示:自带一个功能界面,可以通过功能界面添加不同功能,并且可以固定到顶部水平导航栏中,对于N多小功能的项目而言,非常方便,这样用户就可以根据自己喜好来使用自己常用的功能了。

抵抗时间扭曲,坚持做一件有意义的事 3048

基于opencv的鱼群检测和数量统计识别鱼群密度带界面

摘要:本项目利用OpenCV图像处理技术实现了视频鱼类自动检测计数系统。通过背景减除、形态学处理和轮廓检测等方法,在视频帧中标记鱼类并统计数量。系统包含视频读取、前景提取、轮廓分析、中心点跟踪等核心功能,可实时显示计数结果。适用于水产养殖、生态监测等领域,具有实用价值。未来可通过参数优化、引入深度学习和多目标跟踪技术进一步提升准确性。(147字)

1720

YOLOv11改进 | Neck篇 | 双向特征金字塔网络BiFPN助力YOLOv11有效涨点

本文给大家带来的改进机制是BiFPN双向特征金字塔网络,其是一种特征融合层的结构,也就是我们本文改进YOLOv11模型中的Neck部分,它的主要思想是通过多层级的特征金字塔和双向信息传递来提高精度。本文给大家带来的结构可以让大家自行调节网络结构大小,同时能够达到一定的轻量化效果,为什么发BiFPN呢因为它算是YOLO系列改进中的常青树了,大家可以借鉴它的双向特征思想来创新自己的Neck结构本文的BiFPN通过yaml文件配置可以让大家自行调配其结构。

Snu77的博客 9104

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

上一篇: 一个RandomCrop方案-深度学习
下一篇: 一个神奇的优快云繁体版盗版网站 - 台部落(https://www.twblogs.net/u/5b8f102c2b71771883499d6b)
chanhal
博客等级 码龄9年 30粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值