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