PyTorch – torchvision.transforms – RandomVerticalFlip()
我们使用**RandomVerticalFlip()**变换以给定概率随机垂直翻转图像。它是**torchvision.transforms**模块提供的众多变换之一。此模块包含许多重要的变换,可用于对图像数据执行不同类型的操作。
**RandomVerticalFlip()**接受PIL图像和张量图像。张量图像是一个形状为[C, H, W]的torch张量,其中C是通道数,H是图像高度,W是图像宽度。
语法
torchvision.transforms.RandomVerticalFlip(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('mountain.jpg')定义一个变换,以给定概率p随机垂直翻转图像。这里p = 0.25意味着任何输入图像被垂直翻转的概率为25%。
transform = T.RandomVerticalFlip(p = 0.25)
将上述定义的变换应用于输入图像以垂直翻转图像。
vflipped_img = transform(img)
显示输出图像。
vflipped_img.show()
输入图像
此图像用作以下所有示例中的输入文件。

示例1
在这个程序中,我们将p设置为1,因此输出图像将是垂直翻转的图像。
# import the required libraries
import torch
import torchvision.transforms as T
from PIL import Image
# read the input image
img = Image.open('mountain.jpg')
# define a transform with probability = 1
# to vertically flip an image
transform = T.RandomVerticalFlip(p=1)
# apply the transform on input image
img = transform(img)
# display the flipped image
img.show()输出
它将产生以下输出:
.jpg)
请注意,由于我们将概率p设置为1,因此输出图像是垂直翻转的图像。
示例2
在这个示例中,我们将概率p设置为0.25,因此任何图像被垂直翻转的概率为25%。
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
# read the input image
img = Image.open('mountain.jpg')
# define a transform with probability = 0.25
transform = T.RandomVerticalFlip(p=0.25)
# save four output images applying the above transform
imgs = [transform(img) for _ in range(4)]
# display these four output images
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)
请注意,在四个输出图像中,至少有一个图像被垂直翻转。您可能会得到不同数量的垂直翻转图像。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP