【图像处理】[::-1]替代方法,及图片旋转(rotate)固定角度

Motivation

在早期版本的pytorch中,torchvision.transforms.functional.rotate()只支持输入是PILimage格式,不支持tensor格式。如果你试图把tensor转成PILimage,网络里又会给你报出各种各样奇奇怪怪的错误。比如:pic should be Tensor or ndarray. Got <class 'torch.Tensor'>.、需要把tensor从GPU里copy出来等。所以干脆心一横,自己写一个吧…

[::-1]替代方法

对于python列表来说,实现旋转90度只需要对列表做一个转置,然后list[::-1]把矩阵行的位置换一下,就可以实现旋转90度的效果。但是对于tensor,如果使用这个方法,会报错ValueError: negative step not yet supported。那么怎么实现这个操作呢?

引用一个大神的写法:https://github.com/pytorch/pytorch/issues/229

inv_idx = torch.arange(tensor.size(0)-1, -1, -1).long()
# or equivalently torch.range(tensor.size(0)-1, 0, -1).long()
inv_tensor = tensor.index_select(0, inv_idx)
# or equivalently
inv_tensor = tensor[inv_idx]

实现旋转固定角度

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   my_rot90.py    
@Contact :   moyanxuanliu@126.com
@License :   (C)Copyright 2021-2022, ZongfangLiu

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2022/4/1 20:42   zfliu      1.0         None
'''

# Implementation of rot90 for earlier version pytorch which dosen't have.
import torch

def rot90(img, clockwise = True):
    '''
    :param img: img to rotate (type must be tensor)
    :param clockwise: clockwise if True else anticlockwise
    :return:
    '''
    inv_index = torch.arange(img.size(0)-1, -1, -1 )
    img_transposed = img.t()
    # 顺时针旋转就把第一个维度颠倒,逆时针旋转就把第二个维度颠倒
    img_rot90 = img_transposed[inv_index] if clockwise else img_transposed[:, inv_index]

    return img_rot90
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小丫么小阿豪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值