torch.roll顾名思义,就是让张量滚动的意思。
官方文档:https://pytorch.org/docs/master/generated/torch.roll.html
形参形式:

torch.roll(input, shifts, dims=None) → Tensor

input为输入张量,shifts表示要滚动的方向。负数表示左上,正数表示右下。dims表示要滚动的维度。
比如,我要把一张图片从左边变换到右边:torch.roll(img, (-120, -120))

26.png

看这个栗子大概就能明白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/weixin_42899627/article/details/116095067