PyTorch – torchvision.transforms – RandomHorizontalFlip()
为了以给定的概率随机水平翻转图像,我们应用**RandomHorizontalFlip()**变换。它是**torchvision.transforms**模块提供的众多变换之一。此模块包含许多重要的变换,可用于对图像数据执行不同类型的操作。
**RandomHorizontalFlip()**接受PIL图像和张量图像。张量图像是一个形状为**[C, H, W]**的PyTorch张量,其中C是通道数,H是图像高度,W是图像宽度。
语法
torchvision.transforms.RandomHorizontalFlip(p)(img)
如果p = 1,则返回水平翻转的图像。
如果p = 0,则返回原始图像。
如果p在(0,1)范围内,则返回水平翻转图像的概率为p。
它以给定的概率p随机返回水平翻转的图像。
步骤
我们可以使用以下步骤以给定的概率随机水平翻转图像:
导入所需的库。在以下所有示例中,所需的Python库为**torch、Pillow**和**torchvision**。请确保您已安装它们。
import torch import torchvision import torchvision.transforms as T from PIL import Image
读取输入图像。输入图像是PIL图像或张量图像。
img = Image.open('building.jpg')定义一个变换,以给定的概率**p**随机水平翻转图像。这里**p = 0.25**表示任何输入图像被水平翻转的概率为25%。
transform = T.RandomHorizontalFlip(p = 0.25)
将上述定义的变换应用于输入图像以水平翻转图像。
hflipped_img = transform(img)
显示输出图像。
hflipped_img.show()
输入图像
此图像用作以下所有示例中的输入。

示例1
在这个程序中,我们将p设置为1,所以它肯定会水平翻转图像。
# import required libraries
import torch
import torchvision.transforms as T
from PIL import Image
# read the input image
img = Image.open('building.jpg')
# define a transform to horizontally flip an image
# randomly with a given probability
transform = T.RandomHorizontalFlip(p=1)
# apply the above defined transform on the input image
img = transform(img)
# display the image
img.show()输出
它将产生以下输出:
.jpg)
请注意,由于我们将概率p设置为1,因此我们的输出图像被水平翻转了。
示例2
在这个程序中,我们将p设置为0.25。
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('building.jpg')
transform = T.RandomHorizontalFlip(p=0.25)
imgs = [transform(img) for _ in range(4)]
fig = plt.figure(figsize=(7,3))
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)
请注意,在4个输出图像中,有一个被水平翻转了。您可能会得到不同数量的翻转图像。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP