why am i getting NaN from my function

i was asked to write a function that gets b&w image and returns its entropy. im not allowed to use im_hist or entrtopy (obviously).
this is the function i wrote:
function [Entropy] = EntropyCalc(image)
image_hist = histogram(image);
values = image_hist.Values;
[size_x, size_y] = size(image);
total = size_x * size_y;
p = values./total;
Entropy = - sum(p.*log2(p));
end
but i keep getting NaN.
any ideas??
thanks!

2 件のコメント

David Goodmanson
David Goodmanson 2020 年 1 月 26 日
Hi tomer, don't forget 0*log(0) = nan
tomer orenshtein
tomer orenshtein 2020 年 1 月 26 日
thanks! missed that

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

 採用された回答

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020 年 1 月 26 日

0 投票

As David said your log2(p) is not safe, you can solve this problem by using this line of code:
Entropy = - sum(p.*log2(p+eps));

3 件のコメント

tomer orenshtein
tomer orenshtein 2020 年 1 月 26 日
thank you! that solved that. now i need to find out why the answer is different than the built in entropy function.
thanks!
Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020 年 1 月 26 日
編集済み: Thiago Henrique Gomes Lobato 2020 年 1 月 26 日
The difference is in the histogram function, you need to explicitely define the number of bins to 256 (make sure image is uint8) so it has the same result.
image_hist = histogram(image,256);
Or faster:
values = imhist(image(:));
tomer orenshtein
tomer orenshtein 2020 年 1 月 26 日
that was the thing... didnt know this option. (cant ust imhist in this hw). thanks again! helped me a lot!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeInterpolation of 2-D Selections in 3-D Grids についてさらに検索

製品

リリース

R2019b

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by