why am i getting NaN from my function

1 次查看(过去 30 天)
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!

采纳的回答

Thiago Henrique Gomes Lobato
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 个评论
Thiago Henrique Gomes Lobato
编辑: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 个)

类别

Help CenterFile Exchange 中查找有关 Descriptive Statistics 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by