Code issue with custom imhist() function
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Davide
el 12 de Dic. de 2022
Comentada: Davide
el 13 de Dic. de 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.
0 comentarios
Respuesta aceptada
Jan
el 13 de Dic. de 2022
Editada: Jan
el 13 de Dic. de 2022
You observe the effect of a saturated integer class:
x = uint8(0);
x = x + 254
x = x + 1
x = x + 1 % !!!
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
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.
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!