Normalizing 3D volumes

Hi, I have a silly question. Is the following class the right normalization for 3D grayscale images?

    def __init__(self):  
        pass
    def __call__(self,vol):
        vol = vol-vol.mean()/vol.std()
        return(vol) ```

If so, should I expect after applying this nor,alization the mean of transformed image ill be zero and std will be one?

You should wrap the subtraction into parentheses, otherwise you would scale the mean value by the inverse std.
If that’s fixed, your output should have a zero mean (or something around 1e-6) and a unit variance.

It was solved. Thank you @ptrblck. The variance also is near 1, not exactly 1, is that true?

How large is the difference between the calculated variance and the theoretical 1.?

This is mean 1.3271347e-07 and this is std 0.9999998.

This seems to be alright, as the difference is in the floating point precision limits.

Thank you for your answer.

Correct me if I am wrong, but he could also use normalize from torchvision.transforms.functional.

from torchvision.transforms.functional import normalize
normalize(x, mean, std)

Although the normalize function is used for 2D images, by looking on the source code, if you pass just scalars, then it is equivalent to:

(x - mean) / std

Yes, it should work today, but note that the original question is from July 2020 while transformations on tensors were introduced in torchvision==0.8.0 in Dec. 2020 as seen in the release notes.

1 Like

hi, I am trying to normalize my 3d grayscale image dataset. Should I use the mean and std values of the dataset or the particular image? If I try to normalize with the mean and std values of the whole dataset not every image has zero mean and one std so I am confused.