why am i getting NaN from my function
1 view (last 30 days)
Show older comments
tomer orenshtein
on 26 Jan 2020
Commented: tomer orenshtein
on 26 Jan 2020
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 Comments
Accepted Answer
Thiago Henrique Gomes Lobato
on 26 Jan 2020
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 Comments
Thiago Henrique Gomes Lobato
on 26 Jan 2020
Edited: Thiago Henrique Gomes Lobato
on 26 Jan 2020
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(:));
More Answers (0)
See Also
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!