Code issue with custom imhist() function

8 ビュー (過去 30 日間)
Davide
Davide 2022 年 12 月 12 日
コメント済み: Davide 2022 年 12 月 13 日
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.

採用された回答

Jan
Jan 2022 年 12 月 13 日
編集済み: Jan 2022 年 12 月 13 日
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 件のコメント
Jan
Jan 2022 年 12 月 13 日
@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 2022 年 12 月 13 日
Ok, thanks again. Will definitely try it and do some experiments.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeImages についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by