Code issue with custom imhist() function

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.

 Réponse acceptée

Jan
Jan le 13 Déc 2022
Modifié(e) : Jan le 13 Déc 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 commentaires

Davide
Davide le 13 Déc 2022
Oh I see. Thanks for the explanation.
Just to clarify: when I do value+1 as the out_hist argument, does a temp variable get created to store the addition ? Does it automatically gets set to an uint8? Is this the reason it was capped at 255?
Steven Lord
Steven Lord le 13 Déc 2022
Your image variable (which you may want to rename, BTW, as image already has a meaning in MATLAB) is an array of class uint8. Adding a uint8 (the value element you extracted from image) and a scalar double (1) results in a uint8. See the section on arithmetic operators on this documentation page.
@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 le 13 Déc 2022
Ok, thanks again. Will definitely try it and do some experiments.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Images dans Centre d'aide et File Exchange

Produits

Version

R2022b

Question posée :

le 12 Déc 2022

Commenté :

le 13 Déc 2022

Community Treasure Hunt

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

Start Hunting!

Translated by