import torch
import torch.nn.functional as F
import numpy as np
x = torch.from_numpy(np.arange(8).reshape((2,4)))
print(x.shape)
xx = torch.unsqueeze(x, 1)
print('x:' + xx.shape)
xxx = F.pad(xx, [2,2])
print('pad(xx, [2,2]):' + xxx.shape)
xxx = F.pad(xx, [0,0,2,2])
print('pad(xx, [0,0,2,2]):' + xxx.shape)
xxx = F.pad(xx, [0,0,0,0,2,2])
print('pad(xx, [0,0,0,0,2,2]):' + xxx.shape)
输出:
torch.Size([2, 4])
x: torch.Size([2, 1, 4])
pad(xx, [2,2]): torch.Size([2, 1, 8])
pad(xx, [0,0,2,2]): torch.Size([2, 5, 4])
pad(xx, [0,0,0,0,2,2]): torch.Size([6, 1, 4])
要求:
import torch.nn.functional as F
import torch
from PIL import Image
import numpy as np
im=Image.open("heibai.jpg",'r')
X=torch.Tensor(np.asarray(im))
print("shape:",X.shape)
dim=(20,20,20,20)
X=F.pad(X,dim,"constant",value=0)
padX=X.data.numpy()
padim=Image.fromarray(padX)
padim=padim.convert("RGB")#这里必须转为RGB不然会
padim.save("padded.jpg","jpeg")
padim.show()
print("shape:",padX.shape)
感谢各位博主的分享。
Pytorch之torch.nn.functional.pad函数详解
pytorch 中pad函数toch.nn.functional.pad()的使用