Code issue with custom imhist() function

13 Ansichten (letzte 30 Tage)
Davide
Davide am 12 Dez. 2022
Kommentiert: Davide am 13 Dez. 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.

Akzeptierte Antwort

Jan
Jan am 13 Dez. 2022
Bearbeitet: Jan am 13 Dez. 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 Kommentare
Jan
Jan am 13 Dez. 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 am 13 Dez. 2022
Ok, thanks again. Will definitely try it and do some experiments.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Images finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by