PyTorch之图像和Tensor填充的实例
在PyTorch中可以对图像和Tensor进行填充,如常量值填充,镜像填充和复制填充等。在图像预处理阶段设置图像边界填充的方式如下:
importvision.torchvision.transformsastransforms img_to_pad=transforms.Compose([ transforms.Pad(padding=2,padding_mode='symmetric'), transforms.ToTensor(), ])
对Tensor进行填充的方式如下:
importtorch.nn.functionalasF feature=feature.unsqueeze(0).unsqueeze(0) avg_feature=F.pad(feature,pad=[1,1,1,1],mode='replicate')
这里需要注意一点的是,transforms.Pad只能对PIL图像格式进行填充,而F.pad可以对Tensor进行填充,目前F.pad不支持对2DTensor进行填充,可以通过unsqueeze扩展为4DTensor进行填充。
F.pad的部分源码如下:
@torch._jit_internal.weak_script defpad(input,pad,mode='constant',value=0): #type:(Tensor,List[int],str,float)->Tensor r"""Padstensor. Padingsize: Thenumberofdimensionstopadis:math:`\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor` andthedimensionsthatgetpaddedbeginswiththelastdimensionandmovesforward. Forexample,topadthelastdimensionoftheinputtensor,then`pad`hasform `(padLeft,padRight)`;topadthelast2dimensionsoftheinputtensor,thenuse `(padLeft,padRight,padTop,padBottom)`;topadthelast3dimensions,use `(padLeft,padRight,padTop,padBottom,padFront,padBack)`. Paddingmode: See:class:`torch.nn.ConstantPad2d`,:class:`torch.nn.ReflectionPad2d`,and :class:`torch.nn.ReplicationPad2d`forconcreteexamplesonhoweachofthe paddingmodesworks.Constantpaddingisimplementedforarbitrarydimensions. Replicatepaddingisimplementedforpaddingthelast3dimensionsof5Dinput tensor,orthelast2dimensionsof4Dinputtensor,orthelastdimensionof 3Dinputtensor.Reflectpaddingisonlyimplementedforpaddingthelast2 dimensionsof4Dinputtensor,orthelastdimensionof3Dinputtensor. ..include::cuda_deterministic_backward.rst Args: input(Tensor):`Nd`tensor pad(tuple):m-elemtuple,where:math:`\frac{m}{2}\leq`inputdimensionsand:math:`m`iseven. mode:'constant','reflect'or'replicate'.Default:'constant' value:fillvaluefor'constant'padding.Default:0 Examples:: >>>t4d=torch.empty(3,3,4,2) >>>p1d=(1,1)#padlastdimby1oneachside >>>out=F.pad(t4d,p1d,"constant",0)#effectivelyzeropadding >>>print(out.data.size()) torch.Size([3,3,4,4]) >>>p2d=(1,1,2,2)#padlastdimby(1,1)and2ndtolastby(2,2) >>>out=F.pad(t4d,p2d,"constant",0) >>>print(out.data.size()) torch.Size([3,3,8,4]) >>>t4d=torch.empty(3,3,4,2) >>>p3d=(0,1,2,1,3,3)#padby(0,1),(2,1),and(3,3) >>>out=F.pad(t4d,p3d,"constant",0) >>>print(out.data.size()) torch.Size([3,9,7,3]) """ assertlen(pad)%2==0,'Paddinglengthmustbedivisibleby2' assertlen(pad)//2<=input.dim(),'Paddinglengthtoolarge' ifmode=='constant': ret=_VF.constant_pad_nd(input,pad,value) else: assertvalue==0,'Paddingmode"{}""doesn\'ttakeinvalueargument'.format(mode) ifinput.dim()==3: assertlen(pad)==2,'3Dtensorsexpect2valuesforpadding' ifmode=='reflect': ret=torch._C._nn.reflection_pad1d(input,pad) elifmode=='replicate': ret=torch._C._nn.replication_pad1d(input,pad) else: ret=input#TODO:removethiswhenjitraisesupportscontrolflow raiseNotImplementedError elifinput.dim()==4: assertlen(pad)==4,'4Dtensorsexpect4valuesforpadding' ifmode=='reflect': ret=torch._C._nn.reflection_pad2d(input,pad) elifmode=='replicate': ret=torch._C._nn.replication_pad2d(input,pad) else: ret=input#TODO:removethiswhenjitraisesupportscontrolflow raiseNotImplementedError elifinput.dim()==5: assertlen(pad)==6,'5Dtensorsexpect6valuesforpadding' ifmode=='reflect': ret=input#TODO:removethiswhenjitraisesupportscontrolflow raiseNotImplementedError elifmode=='replicate': ret=torch._C._nn.replication_pad3d(input,pad) else: ret=input#TODO:removethiswhenjitraisesupportscontrolflow raiseNotImplementedError else: ret=input#TODO:removethiswhenjitraisesupportscontrolflow raiseNotImplementedError("Only3D,4D,5Dpaddingwithnon-constantpaddingaresupportedfornow") returnret
以上这篇PyTorch之图像和Tensor填充的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。