Pytorch数组反转(数组倒序)函数flip的使用

TORCH.FLIP函数

torch.flip(input, dims) → Tensor
Reverse the order of a n-D tensor along given axis in dims.
对n维张量的指定维度进行反转(倒序)


NOTE

torch.flip makes a copy of input’s data. This is different from NumPy’s np.flip, which returns a view in constant time. Since copying a tensor’s data is more work than viewing that data, torch.flip is expected to be slower than np.flip.
注意torch.flip是反序地复制一份新的数据,这一点与NumPy不同,NumPy是返回一个view,因而使用torch.flip耗时更久。


Parameters

  • input (Tensor) – the input tensor.
  • dims (a list or tuple) – axis to flip on

Example:

>>> x = torch.arange(10).view(2, 5)
>>> x
tensor([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]])
>>> torch.flip(x, dims=[0])	# 对第0维进行反转
tensor([[5, 6, 7, 8, 9],
        [0, 1, 2, 3, 4]])
>>> torch.flip(x, dims=[1])	# 对第1维进行反转
tensor([[4, 3, 2, 1, 0],
        [9, 8, 7, 6, 5]])
>>> torch.flip(x, dims=[0, 1])	# 对第0、1维进行反转
tensor([[9, 8, 7, 6, 5],
        [4, 3, 2, 1, 0]])

>>> x.flip(dims=[0, 1])	# 对第0、1维进行反转,与上一句效果相同
tensor([[9, 8, 7, 6, 5],
        [4, 3, 2, 1, 0]])
### 如何在 PyTorch 中执行图像镜像操作 为了实现图像的镜像翻转,在 PyTorch 中可以利用 `torchvision.transforms` 提供的功能来完成这一任务。下面是一个具体的例子展示如何应用水平和垂直方向上的镜像变换: ```python from torchvision import transforms import torch from PIL import Image # 定义转换函数,这里设置随机水平翻转的概率为1,确保每次都会发生翻转 hflip_transform = transforms.RandomHorizontalFlip(p=1) # 对于垂直翻转同样适用 vflip_transform = transforms.RandomVerticalFlip(p=1) # 假设 img 是一个PIL.Image对象或者Tensor类型的图片数据 img_tensor = ... # 加载或定义输入图像张量 # 应用水平翻转变换 mirrored_img_h = hflip_transform(img_tensor) # 或者应用垂直翻转变换 mirrored_img_v = vflip_transform(img_tensor) ``` 如果希望更灵活地控制翻转行为而不依赖于随机性,则可以直接通过索引来反转张量的内容: ```python def mirror_image(image_tensor, axis='horizontal'): """ 手动实现图像沿指定轴的镜像 参数: image_tensor (Tensor): 输入的图像张量. axis ('horizontal'/'vertical'): 需要进行翻转的方向,默认为横向. 返回: Tensor: 经过处理后的图像张量. """ if axis == 'horizontal': mirrored = image_tensor.flip(2) # 横向翻转即沿着宽度维度(-1维对于四维batch来说) elif axis == 'vertical': mirrored = image_tensor.flip(1) # 纵向翻转对应高度维度(-2维对于四维batch而言) else: raise ValueError("Axis must be either 'horizontal' or 'vertical'") return mirrored ``` 上述方法提供了两种途径来进行图像的镜像操作:一种是基于预置好的工具类;另一种则是直接操纵张量本身的数据结构[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值