# How to Generate a vector map for histogram equalization

Assuming I have a gray scale image Im with $0:255$ levels of gray, I want to generate a vector map that will preform a histogram equalization on the image. I have read the wiki entry on the subject as well as the matlab function section and yet to understand. (Note that I need to mathematically generate the vector and extracting it from [J,T] = histeq(I); does not answer my problem)

I am assuming I am wrong but it is my understanding that I should use the following code:

mapVec=imhist(Im);
EqVecMap=mapVec;
for i = 1:size(mapVec)
EqVecMap(i)=0;
for j = 1:i
EqVecMap(i)=EqVecMap(i)+mapVec(i);
end
end
mapVec=EqVecMap;


What is the correct process for generating this vector?

Your code is halfway correct; it creates the cumulative distribution function (CDF), but the map isnt quite there yet.

First you get the histogram using imhist(), but we want to convert this to probabilities (the likelihood that each greyscale value occurs at a pixel). mapVec gives us integer counts, so just divide by the number of pixels in the image.

mapVec=imhist(Im);
mapVec=mapVec / prod(size(Im));
EqVecMap = mapVec;


The next part calculating the CDF is correct (except for mapVec(i), I changed that to mapVec(j))

for i = 1:size(mapVec)
EqVecMap(i)=0;
for j = 1:i
EqVecMap(i)=EqVecMap(i)+mapVec(j);
end
end


But we're not done yet. EqVecMap is a CDF, so it's a double vector with max value is 1. However, our pixel values are INTEGERS with max value 255. So just

mapVec=round(EqVecMap*255);


mapVec is now a mapping function from old greyscale value (index 'i') to a new value (mapVec(i)).

** I just saw havakok's answer (but I cant comment bc reputation), and I think it does basically the same thing. Only difference is you need to multiply by 255, not 256, since our max greylevel is 255 (the range includes 0, remember).

Found This cute algorithm to solve this.

%original histogram
Hist=imhist(Im);
%Create probabilty vector for each grayscale value
mapVec=zeros(1,256);
for i = 1:size(Im,1)
for j = 1:size(Im,2)
%add one to representing bin for each value of
%grayscale found in the image
mapVec(Im(i,j)+1)=mapVec(Im(i,j)+1)+1;
end
end
%Generate the cumulative histogram
sum=0;
for i=1:size(mapVec,2)
sum=sum+mapVec(i);
mapVec(i)=sum;
end
%divide by number of Pixels to find CDF
mapVec=mapVec/(size(Im,1)*size(Im,2));
%round the result times number of bins
mapVec=round(mapVec*256);