Wrong answer being given when adding whole numbers
Show older comments
I am currently working on a problem in which I apply a 3x3 smoothing filter to an image. However, the actual error I have is in a simple mathematical error where Matlab is outputing a wrong answer for a simple addition. When adding 156 and 159, the result it gives is 255, not 314. Below is my code and the output showing this happening.
% This image comes with Matlab, should be universally available
image=imread('cameraman.tif');
imshow(image);
figure
imshow(filter3x3(image));
% Apply 3x3 smoothing filter to image
function image = filter3x3(image)
% Find height and width of image
imageSize = size(image);
H = imageSize(1);
W = imageSize(2);
% Save copy of image
imageOriginal = image;
% Iterate through every pixel except the outmost ones
for i = 2:H-1
for j = 2:W-1
sum = 0;
% For the eight pixels dirrectly adjacent to pixel and the
% pixel itself
for x = -1:1
for y = -1:1
% Fetch pixel and save it to a sum
pixel = imageOriginal(i + x, j + y);
fprintf("Pixel value: %d\n", pixel);
fprintf("Sum before new pixel: %d\n", sum);
sum = pixel + sum; % <----------------------------------- Error happens at this equation
fprintf("Sum with new pixel: %d\n", sum);
end
end
% Find the result of the filter for the pixel
filterResult = round(sum/9.0);
% Apply result to pixel
image(i,j) = filterResult;
end
end
end
Output for first two pixels:
Pixel value: 156
Sum before new pixel: 0
Sum with new pixel: 156
Pixel value: 159
Sum before new pixel: 156
Sum with new pixel: 255
The answer for this opperation is clearly wrong, and for the life of me I can not understand why such a simple operation I literally can do in my head is off by almost 19% of the correct answer. Why is this happening, and is there a way to get the correct answer?
2 Comments
Matthew Wilcox
on 22 Nov 2021
Stephen23
on 25 Nov 2021
The documentation here:
explains various operations on intger classes, including this section:
"Arithmetic Operations on Integer Classes"
"MATLAB can perform integer arithmetic on the following types of data:"
- "Integers or integer arrays of the same integer data type. This yields a result that has the same data type as the operands..."
- "Integers or integer arrays and scalar double-precision floating-point numbers. This yields a result that has the same data type as the integer operands..."
and procedes to give examples. This explains exactly the behavior that you observe. This has always been the behavior of MATLAB arithmetic operations involving integer types (and is occasionally discussed on this forum).
The source which told you that integer types are enlarged/expanded to prevent loss is incorrect.
Accepted Answer
More Answers (0)
Categories
Find more on Computer Vision with Simulink in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!