PyTorch – 如何以给定概率随机反转图像颜色?
**RandomInvert()** 变换以给定概率随机反转图像的颜色。**torchvision.transforms** 模块提供了许多重要的变换,可用于对图像数据执行不同类型的操作。
**RandomInvert()** 接受 PIL 图像和张量图像或张量图像批次。张量图像是一个形状为 [**3, H, W**] 的 PyTorch 张量,其中 H 是图像高度,W 是图像宽度。张量图像批次也是一个 torch 张量,形状为 [**B, 3, H, W**],其中 B 是批次中的图像数量。
语法
torchvision.transforms.RandomInvert(p)(img)
它以给定概率 p 返回随机颜色反转的图像。
如果 **p** = 1,则返回颜色反转的图像。
如果 **p** = 0,则返回原始图像。
如果 **p** 在 (0,1) 范围内,则返回随机颜色反转图像的概率为 p。
img 是输入的 PIL 图像或张量图像。
步骤
我们可以使用以下步骤以给定概率随机反转输入图像的颜色:
导入所需的库。在以下所有示例中,所需的 Python 库为 **torch、Pillow** 和 **torchvision**。确保你已安装它们。
import torch import torchvision import torchvision.transforms as T from PIL import Image
读取输入图像。输入图像为 PIL 图像或 torch 张量。
img = Image.open('stairs.jpg')定义一个变换,以给定概率 p 随机反转原始输入图像的颜色。
transform = T.RandomInvert(p = 0.25)
将上述定义的变换应用于输入图像以反转输入图像的颜色。
inverted_img = transform(img)
显示随机颜色反转的图像。
inverted_img.show()
输入图像
此图像在以下所有示例中用作输入文件。

示例 1
在此程序中,我们将概率设置为 1,以便输出肯定是一张颜色反转的图像。
# import the required libraries
import torch
import torchvision.transforms as T
from PIL import Image
# read the input image
img = Image.open('stairs.jpg')
# define a transform to randomly invert
# the color with probability=1
transform = T.RandomInvert(p=1)
# apply the above transform on input image
img = transform(img)
img.show()输出
它将产生以下输出:
.jpg)
示例 2
让我们来看另一个例子:
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
# read the input image
img = Image.open('stairs.jpg')
# define transform with probability = 0.25
transform = T.RandomInvert(p=0.25)
# apply the transform four times
invert_imgs = [transform(img) for _ in range(4)]
fig = plt.figure(figsize=(7,4))
rows, cols = 2,2
for j in range(0, len(invert_imgs)):
fig.add_subplot(rows, cols, j+1)
plt.imshow(invert_imgs[j])
plt.xticks([])
plt.yticks([])
plt.show()输出
它将产生以下输出:
.jpg)
在上面的输出中,注意,在四张图像中,至少有一张图像的颜色被反转,因为我们将概率设置为 0.25。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP