PyTorch 中如何计算图像通道的均值?
RGB 图像有三个通道,红色、绿色和蓝色。我们需要计算这些图像通道中像素值的均值。为此,我们使用了方法 torch.mean() 。但是,这种方法的输入参数是 PyTorch 张量。因此,我们首先将图像转换为 PyTorch 张量,然后再应用这个方法。它返回张量中所有元素的平均值。要查找图像通道上的平均值,我们将参数 dim = [1,2] 。
步骤
-
导入所需的库。在以下所有 Python 示例中,所需的 Python 库是 torch,torchvision,Pillow 和 OpenCV 。请确保您已经安装了它们。
-
使用 image.open() 读取输入图像,并将其分配给变量 "img" 。
-
定义一个转换,将 PIL 图像转换为 PyTorch Tensor
-
使用上述定义的转换将图像" img "转换为 PyTorch 张量,并将此张量分配给 "imgTensor" 。
-
计算 torch.mean(imgTensor, dim=[1,2]) 。它返回一个包含三个值的张量。这三个值是 RGB 三个通道的均值。您可以将这三个均值分别分配给三个新变量 "R_mean","G_mean" 和 "B_mean" 。
-
打印图像像素的三个均值 "R_mean","G_mean", 和 "B_mean" 。
输入图像
我们将使用以下图像作为两个示例中的输入。
示例 1
# Python program to find mean across the image channels
# import necessary libraries
import torch
from PIL import Image
import torchvision.transforms as transforms
# Read the input image
img = Image.open('opera.jpg')
# Define transform to convert the image to PyTorch Tensor
transform = transforms.ToTensor()
# Convert image to PyTorch Tensor (Image Tensor)
imgTensor = transform(img)
print("Shape of Image Tensor:\n", imgTensor.shape)
# Compute mean of the Image Tensor across image channels RGB
R_mean, G_mean ,B_mean = torch.mean(imgTensor, dim = [1,2])
# print mean across image channel RGB
print("Mean across Read channel:", R_mean)
print("Mean across Green channel:", G_mean)
print("Mean across Blue channel:", B_mean)
输出
Shape of Image Tensor:
torch.Size([3, 447, 640])
Mean across Read channel: tensor(0.1487)
Mean across Green channel: tensor(0.1607)
Mean across Blue channel: tensor(0.2521)
示例 2
我们也可以使用 OpenCV 读取图像。使用 OpenCV 读取的图像的类型是 numpy.ndarray 。在这个示例中,我们使用另一种方式来计算平均值。我们使用 imgTensor.mean() ,它是张量的基本操作。请查看以下示例。
# Python程序:查找图像通道的均值
# 导入必要的库
import torch
import cv2
import torchvision.transforms as transforms
# 使用cv2或PIL读取输入图像
img = cv2.imread('opera.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 定义转换以将图像转换为PyTorch Tensor
transform = transforms.ToTensor()
# 将图像转换为PyTorch Tensor(Image Tensor)
imgTensor = transform(img)
print("Image Tensor的形状:\n", imgTensor.shape)
# 计算图像通道RGB的Image Tensor的均值
# 另一种计算均值的方式是
R_mean,G_mean,B_mean = imgTensor.mean(dim = [1,2])
# 输出RGB通道的均值
print("Red通道的平均值:", R_mean)
print("Green通道的平均值:", G_mean)
print("Blue通道的平均值:", B_mean)
输出
Image Tensor的形状:
torch.Size([3, 447, 640])
Red通道的平均值:tensor(0.1487)
Green通道的平均值:tensor(0.1607)
Blue通道的平均值:tensor(0.2521)