How to find mean across the image channels in PyTorch?
Published January 03, 2022The RGB color model has three primary components: red, blue, and green, which necessitates computing the mean of the picture pixel values across these image channels. In this article, we'll look at how to determine the mean across picture channels in PyTorch.
How to: Using PyTorch, determine the mean of all picture channels.
In PyTorch, we often use torch.mean to determine the mean across all picture channels (). On the other hand, this technique accepts the PyTorch tensor as input. This indicates that the picture is first turned into a PyTorch tensor, after which the procedure is applied, and the values of all the tensor members are output.
Check out the easy steps below to see how this procedure works:
Step 1: First, import all of the required libraries, such as OpenCV, Pillow, TorchVision, and torch.
Step 2: Read the input picture using the image.
· then open () and add it to the variable "image."
Step 3: In PyTorch, convert the PIL picture to a Tensor.
Step 4: Determine the average (img tensor, dim = [1,2]). This function will return the RGB's three mean values: "R mean," "G mean," and "B mean." These values may be assigned independently.
Step 5: Print the three average picture pixel values.
Example
This example accepts the stone.jpg picture as input and produces the image channel's mean value
import torch from PIL import Image import torchvision.transforms as transforms img = Image.open('stones.jpg') transform = transforms.ToTensor() imgTensor = transform(img) print("Shape of Image Tensor:\n", imgTensor.shape) R_mean, G_mean ,B_mean = torch.mean(imgTensor, dim = [1,2]) print("Mean across Read channel:", R_mean) print("Mean across Green channel:", G_mean) print("Mean across Blue channel:", B_mean)
|
Output:
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)
|
Article Contributed By :
|
|
|
|
606 Views |