Clear Filters
Clear Filters

Apply mean and standard deviation of an image to another image

2 views (last 30 days)
Hi I have an image and I calculate the mean and standard deviation like this
meanint=mean(mean(tmpimg));
stdint=std(std(tmpimg));
Now I have another image and I try to make it have the same mean and standard deviation as the previous image. That's what I do
if (meanint2>meanint(1))
tmpimg = imsubtract(tmpimg,meanint2);
tmpimg = imadd(tmpimg,meanint);
tmpimg = imdivide(tmpimg,stdint2);
tmpimg = immultiply(tmpimg,stdint);
elseif (meanint2<meanint(1))
tmpimg = imadd(tmpimg,meanint);
tmpimg = imsubtract(tmpimg,meanint2);
tmpimg = immultiply(tmpimg,stdint);
tmpimg = imdivide(tmpimg,stdint2);
end
But I don't have the result I want. Does anyone knows why?

Accepted Answer

Guillaume
Guillaume on 11 Oct 2016
Edited: Guillaume on 11 Oct 2016
Really, this can be done with just one operation, with much less error accumulation and chance of truncation (if integer images):
meanreference = mean2(referenceimage);
stdreference = std2(referenceimage);
meantoscale = mean2(imagetoscale);
stdtoscale = std2(imagetoscale);
adjustedimage = imlincomb(stdreference / stdtoscale, imagetoscale, ...
meanreference - meantoscale * stdreference / stdtoscale);
If the image is double I wouldn't even bother with the imlincomb:
adjustedimage = meanreference + (imagetoscale - meantoscale) * stdreference / stdtoscale;
  6 Comments
Adam
Adam on 11 Oct 2016
Edited: Adam on 11 Oct 2016
The problem of standard deviation not being the same is that you calculate it wrongly in the code in the question. Mean is a separable operation that you can do as you are doing (though there is no need to do so), std is not.
std2 as Guillaume uses works correctly or as I usually do more generically, just
std( tmpimg(:) )
since it is a statistical operation and the structure of the data in a 2d matrix rather than 1d is not relevant.

Sign in to comment.

More Answers (1)

Adam
Adam on 11 Oct 2016
tmpimg = imsubtract(tmpimg,meanint2);
tmpimg = imdivide(tmpimg,stdint2);
tmpimg = immultiply(tmpimg,stdint);
tmpimg = imadd(tmpimg,meanint);
seems a more appropriate ordering and gives me the same mean.
  2 Comments
Efstathios Kontolatis
Efstathios Kontolatis on 11 Oct 2016
Edited: Efstathios Kontolatis on 11 Oct 2016
For which of the two if? Also, the standard deviation is not the same.
Adam
Adam on 11 Oct 2016
I don't see the need for two cases, why is the code different depending whether the mean is greater or smaller?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!