PyTorch – 如何旋转图像?
**RandomRotation()** 函数可以将图像随机旋转一个角度。选择的随机角度来自给定的角度范围(度)。**RandomRotation()** 是 **torchvision.transforms** 模块提供的许多重要变换之一。**RandomRotation()** 变换接受 PIL 图像和张量图像。
张量图像是一个形状为 [C, H, W] 的 Torch 张量,其中 C 是通道数,H 是图像高度,W 是图像宽度。如果图像既不是 PIL 图像也不是张量图像,则我们首先将其转换为张量图像,然后应用变换。
语法
torchvision.transforms.RandomRotation(degree)(img)
其中 **degree** 是所需的度数范围。它是一个序列,例如 (min, max)。图像将以从该范围内随机选择的角度旋转。
步骤
我们可以使用以下步骤以随机角度旋转图像:
导入所需的库。在以下所有示例中,所需的 Python 库是 **torch、Pillow** 和 **torchvision**。确保您已经安装了它们。
import torch import torchvision import torchvision.transforms as T from PIL import Image
读取输入图像。输入图像可以是 PIL 图像或 Torch 张量。
img = Image.open('desert.jpg')定义一个变换来以随机角度旋转图像。给出所需的度数范围。
transform = T.RandomRotation((30,70))
将上述定义的变换应用于输入图像,以随机角度旋转输入图像。
rotated_img = transform(img)
显示输出图像。
rotated_img.show()
输入图像
此图像用作以下所有示例中的输入文件。

示例 1
在此示例中,我们将角度范围设置为 (30,60)。输入图像旋转的角度将从此范围内随机选择。
# import required libraries
import torch
import torchvision.transforms as T
from PIL import Image
# read the input image
img = Image.open('desert.jpg')
# define a transform to rotate he input image
transform = T.RandomRotation(degrees=(30,60))
# rotate the input image using above defined trasnform
img = transform(img)
# dispaly the rotated image
img.show()输出
它将产生以下输出:
.jpg)
请注意,输入图像旋转的角度来自范围 (30,60)。
示例 2
在此示例中,我们将演示如何以不同的角度旋转输入图像。
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
# read the input image
img = Image.open('desert.jpg')
# define a transform to rotate the image
transform = T.RandomRotation(degrees = (0,180))
# save four output images applying the above transform
imgs = [transform(img) for _ in range(4)]
fig = plt.figure(figsize=(7,4))
rows, cols = 2,2
for j in range(0, len(imgs)):
fig.add_subplot(rows, cols, j+1)
plt.imshow(imgs[j])
plt.xticks([])
plt.yticks([])
plt.show()输出
它将产生以下输出:
.jpg)
请注意,所有四个输出图像都以不同的角度旋转。角度范围设置为 (0,180)。每个图像都以 (0,180) 范围内的角度旋转。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP