torch.roll 解读
torch.roll顾名思义,就是让张量滚动的意思。
形参形式:
1 torch.roll(input, shifts, dims=None) → Tensor
1. input为输入张量.
2. shifts表示要滚动的方向。负数表示左上方向,正数表示右下方向。dims表示要滚动的维度。
如果shifts是一个元祖(如 shifts=(x,y)),dims必须是一个相同大小的元祖(例如dims=(a,b)),相当于在第a维度移x位,在b维度上移y位。
比如,我要把一张图片从左边换到右边:torch.roll(img, (-120,-120))。效果如下:

看这个例子大概就能明白torch.roll在做一件什么事了。
代码如下:
import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('cat.jpeg')
print(img.shape)
x=torch.from_numpy(img)
shifted_x = torch.roll(x, shifts=(-120, -120), dims=(0, 1))
plt.figure(figsize=(16,8))
plt.subplot(1,2,1)
plt.imshow(x)
plt.title("orgin_img")
plt.subplot(1,2,2)
plt.imshow(shifted_x)
if torch.equal(shifted_x, x):
plt.title("non_shifted")
else:
plt.title("shifted_img")
plt.show()
plt.pause(5)
plt.close()
参考连接:
https://blog.csdn.net/leviopku/article/details/120822635
https://blog.csdn.net/weixin_42899627/article/details/116095067
https://github.com/microsoft/Swin-Transformer/issues/38

浙公网安备 33010602011771号