Subtracting two numbers gives 0 as answer

조회 수: 1 (최근 30일)
Kostantinos Thanasis
Kostantinos Thanasis 2020년 10월 30일
댓글: Ameer Hamza 2020년 10월 30일
I have two matrices that represent a picture in the gray scale. Values 0-255.
I want to calculate a metric called MSE which uses the formula
where p1(w,h) coresponds to the value of the pixel (w,h) in the first picture. Same for p2. Then all of that squared. For simplicity i used to for loops to iterate the matrices. Each iteration a find the difference,then to the power of 2 then add it to the total.
The problem is that,let's say for the first iteration the p1(w,h) = 156 and the p2(w,h) = 169. When i subtract them i do not get -13. I get 0.
May be this is a silly question but im new to this and have been trying to solve this for hours.
ΝΟΤΕ: I was always getting a 0 in return so i did one operation per line to find the issue.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 10월 30일
편집: Ameer Hamza 2020년 10월 30일
You are getting zero because the images are probably in uint8 format and negative results are given a value of zero in that case
>> uint8(10)-uint8(1)
ans =
uint8
9
>> uint8(1)-uint8(10)
ans =
uint8
0
The solution is to convert the matrices to double() before subtraction. At beginning of your function, add the lines
startingImage = double(startingImage);
compressedImage = double(compressedImage);
mse = 0; ...
...
Also note that you can do these things without loop.
startingImage = double(startingImage);
compressedImage = double(compressedImage);
mse = mean((startingImage-compressedImage).^2, 'all')
or if you are using an older version of MATLAB
mse = mean((startingImage(:)-compressedImage(:)).^2)
  댓글 수: 2
Kostantinos Thanasis
Kostantinos Thanasis 2020년 10월 30일
Do not know the policy for commenting here(in respect to the stack overflow one) but thank you very much. You explained the issue i was facing very well so i could have solved it on my own but also also provided me with the solution.
I am gratefull.
Ameer Hamza
Ameer Hamza 2020년 10월 30일
I am glad to be of help! :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by