I am trying to write a function that computes CDF of an image, but the output I get is always zero. what am I doing wrong?

function cdf = CDF(im,j)
rows = size(im,1);
cols = size(im,2);
s=double(rows^cols);
sum=double(0);
cd
for i=0:j
for r=1: rows
for co=1: cols
pixel=im (r,co);
if (pixel==i)
sum=sum+1;
end
end
end
end
cdf = double(sum/s);

3 Comments

It looks like lots of things. But let's get some information first. What is im - a gray scale image, a color image, or a binary image? What is (the very badly-named) j - its value and it's purpose? Are you just trying to count the number of pixels in the image that have value j? Is cdf the cumulative distribution function? If so, why not simply call histcounts() and cumsum()? Why are you using sum - a very important built-in function - as the name of your variable?
...
if (pixel==i)
sum=sum+1;
end
will only sum if the value of the image itself is an integer equal to the particular value of i on that pass thru the outer loop.
What is j and what is the normalization for the image? If it were scaled, the values wouldn't ever match which would cause the symptom.
You're not going to get a CDF anyway, because you're only going to return a single value.
my image is a uint8 grayscale image. no, i'm not trying to count the pixels with value of j. j is a parameter that the user has to set value to. for example if the user sets j to 20, the function is supposed to count the pixels in the picture that have the intensity of 0 plus the pixels with intensity of 1 ,...., plus the pixels with intensity of 20.
the function above does show the value of sum correctly, but when I try to get the value of cdf, which is sum/s, it becomes zero.
I believe the problem is that the value is smaller than 1, and the type of my parameter cdf or s or sum isn't correctly initialized and it floors the value to the integer 0.

Sign in to comment.

Answers (2)

I think you should use histcounts or histogram. Since you want the CDF you'd specify that as the 'Normalization' in your histcounts or histogram call.
Basically if u want to calculate cdf of image, then you have to follow three step,
1.Histogram
2.Normalized Histogram
3.CDF
Here you have a code of histogram using for loops (but you can use "Hist" function).
if true
function [hist hist_P]=histor_g(im)
hist=zeros(1,256);
[r c]=size(im);
s=r*c;
for i=1:r
for j=1:c
int_val=im(i,j);
hist(int_val+1)=hist(int_val+1)+1;
end
end
hist_P=hist./s; %Normalized Histogram(PDF)
end
end
As using this function you van get PDF(Normalized Histogram)
then you can calculate CDF.
if true
function [c_hist]=cum_h(hp)
[r c]=size(hp);
c_hist=zeros(1,256);
for j=1:c
if(j ==1)
c_hist(j)=hp(j);
else
c_hist(j)=hp(j)+c_hist(j-1);
end
end
end
Hopefully you get it thanks.

Asked:

on 24 Oct 2018

Edited:

on 25 Oct 2018

Community Treasure Hunt

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

Start Hunting!