# Is it possible to get per channel mean and variance for images in pytorch?

Is it possible to get per channel mean and variance and use on images in pytorch?

I want to center(by subtracting the mean) and normalizing(by dividing by the standard deviation) of an image with 3 channels(RGB) in Pytorch.
Is my approach below correct?

`centered_images = images - images.mean()`
`normalized_images = images/images.std()`

images.mean() returns only a value for the batch. Is this correct?

Calling images.mean() (or std) like this will take the mean of the entire tensor, producing a single value, not the per channel mean (or std) that you would like.

One way to get the mean for each channel, you could do the following (assuming your image is shaped like (L, W, 3)):

``````mean_c1 = images[:, :, :, 0].mean()
mean_c2 = images[:, :, :, 1].mean()
mean_c3 = images[:, :, :, 2].mean()
``````

Then to centre the image you could do:

``````
centred_images[:, :, :, 0] = images[:, :, :, 0] - mean_c1
centred_images[:, :, :, 1] = images[:, :, :, 1] - mean_c2
centred_images[:, :, :, 2] = images[:, :, :, 2] - mean_c3
``````

Alternatively, you can search for `torchvision.transforms.` `Normalize` here

1 Like

Thank you @sdv4 , do I apply the same approach for standard deviation. Lastly, images is a batch. would the code snippet given above work?

I modified the above answer to include the batch index (and fixed a typo). You can use the same approach for standard deviation.

Lastly, recall that you should calculate the mean and standard deviation from your training set only. You then apply those values to your validation and test set.