1

I'm doing image histogram equalization . The code works fine for an image with 256 bin histogram, but, when I try to convert histogram to 32 bin,the image quality detoriates. Any ideas how to fix that?

My Code:

I=imread('D:\came.jpg');
subplot(2,2,1); 
imshow(I);
title('Original Image');
subplot(2,2,2); 
input=rgb2gray(I);
imhist(input);
title('Histogram: Before Histogram equalization');
for j=1:3
R=I(:,:,j);
channel=j;
GIm=R;
numofpixels=size(GIm,1)*size(GIm,2);
HIm=uint8(zeros(size(GIm,1),size(GIm,2)));
freq=zeros(256,1);
probf=zeros(256,1);
probc=zeros(256,1);
cum=zeros(256,1);
output=zeros(256,1);
%freq counts the occurrence of each pixel value.
%The probability of each occurrence is calculated by probf.
for i=1:size(GIm,1)
    for j=1:size(GIm,2)
        value=GIm(i,j);
        freq(value+1)=freq(value+1)+1;
        probf(value+1)=freq(value+1)/numofpixels;
    end

end

sum=0;
no_bins=32;% it works fine for 256 values but not for 32 values
%The cumulative distribution probability is calculated. 
for i=1:size(probf)
   sum=sum+freq(i);
   cum(i)=sum;
   probc(i)=cum(i)/numofpixels;
   output(i)=round(probc(i)*no_bins);
end

for i=1:size(GIm,1)
    for j=1:size(GIm,2)
            HIm(i,j)=output(GIm(i,j)+1);
    end
end

if(channel==1) HIm1=uint8(HIm); 
elseif(channel==2) HIm2=uint8(HIm);
elseif(channel==3) HIm3=uint8(HIm);    
end


end

subplot(2,2,3); 
finalimage = cat(3,HIm1,HIm2, HIm3);
imshow(finalimage);
title('After Histogram equalization');
subplot(2,2,4); 
input=rgb2gray(finalimage);
imhist(input);
title('Histogram: After Histogram equalization');


end

My Output: enter image description here

Minhas Kamal
  • 20,752
  • 7
  • 62
  • 64
  • If you take a look at the spread of your histogram, the intensities are concentrated between `[0,32]`. Try multiplying all of your pixels by 8 to spread out your pixels to `[0,255]` and see your results. In fact, this is how histogram equalization works. Once you figure out how many bins you want, you still need to normalize your data so that it falls between `[0,255]`. Histogram equalization is supposed to try and flatten your histogram, and this obviously is not your intended result. – rayryeng Sep 14 '14 at 02:19
  • Yes, when i change the bins to 256 it works perfect. But I was curious to show that my final image after equalization have 32 different values in each channel. –  Sep 14 '14 at 02:28
  • 2
    By multiplying by 8, you will **still** have 32 bins, but you're increasing the contrast so you can visually see what the result is. You're not changing the equalization. You're changing it so you can **see** the results better. In terms of equalization, your code is mathematically performing it correctly, but I would personally do it vectorized, and you can do it in three lines of code. – rayryeng Sep 14 '14 at 02:31

0 Answers0