Code issue with custom imhist() function

13 views (last 30 days)
Davide
Davide on 12 Dec 2022
Commented: Davide on 13 Dec 2022
Hi everyone, recently my classes required me to write a function to create a histogram of a greyscale image without using the built in function imhist().
I came up with this but there's something I don't understand.
function out_hist = myhistogram(image)
[rows, cols] = size(image);
out_hist = zeros(256, 1);
for i = 1 : rows
for j = 1 : cols
value = image(i, j);
% code here
end
end
end
With just this expression (to replace in "code here") when you encounter a 255 value it gets added to the 255th position instead of the 256th.
out_hist(value + 1) = out_hist(value + 1) + 1;
While this, which does the exact same thing, works perfectly.
if (value == 255)
out_hist(256) = out_hist(256) + 1;
else
out_hist(value + 1) = out_hist(value + 1) + 1;
end
Now I want to ask: am I missing something? Don't they produce the excact same result?
Thanks in advance for the answers.

Accepted Answer

Jan
Jan on 13 Dec 2022
Edited: Jan on 13 Dec 2022
You observe the effect of a saturated integer class:
x = uint8(0);
x = x + 254
x = uint8 254
x = x + 1
x = uint8 255
x = x + 1 % !!!
x = uint8 255
An UINT8 cannot contain a value greater than 255. In Matlab all greater values are stored as maximum value. The same effect occurs for too small values:
x = x - 256
x = uint8 0
If the image is stored as UINT8, value=image(i,j) creates value as an UINT8 also.
A solution is to use a class for the index, which has a higher capability:
value = double(image(i, j));
out_hist(value + 1) = out_hist(value + 1) + 1;
The manual treatment of this exception is fine also:
if (value == 255)
out_hist(256) = out_hist(256) + 1;
Here the number 256 is treated as double automatically, because this is the defult in Matlab.
  4 Comments
Jan
Jan on 13 Dec 2022
@Davide: Fell free to try it:
x = uint8(1);
class(x)
class(1)
class(x + 1)
class(1 + x)
class(1 + 17)
% etc.
Or maybe less useful: yes, yes, yes.
Davide
Davide on 13 Dec 2022
Ok, thanks again. Will definitely try it and do some experiments.

Sign in to comment.

More Answers (0)

Categories

Find more on Images in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!