Code change for histogram

2 views (last 30 days)
sandeep
sandeep on 28 Oct 2012
Hi Sir,
I was looking at the mat-lab mathworks and find out if you could help me out with this code.
Could you help me out. I was doing a histogram equalization code without directly using imhist function. I am getting both the graphs as same output graphs. Could you help me out in getting the right code. Could you let me know what is wrong in it or let me know if you could provide me a histogram equalization code which works.
clc; close all; clear all; img=imread('C:\Users\Desktop\dipproj2\lena.bmp'); [p,q]=size(img) k=1:1:256; x= ones(1,256);
for k=1:1:256 for i=1:size(p,1) for j=1:size(q,1) k=value(256,i) % if (img(i,j)==k) % x(k+1)=x(k+1)+1; x(k+1)=x(k+1)+1; end end end d=zeros(1,256); d=x*(1/(p*q)); s=sum(k+1) s(1)=d(1,1);
for i=2:256 s(i)=s(i-1)+d(1,i); end y=ones(1,256); u=y*256 %sk=255*s; z=floor(u); final=img; for k=1:256 for i=1:size(256,1) for j=1:size(256,1) if(img(i,j)==k) final(i,j)=z(1,k+1)+1; end end end end figure(1), subplot(2,1,1), title('histogram'), imagesc(final), colormap(gray); subplot(2,1,2), imhist(final); figure(2), subplot(2,1,1), title('histogram1'), imagesc(img), colormap(gray); subplot(2,1,2), imhist(img);
Thanks and Regards, Sandeep

Answers (1)

Image Analyst
Image Analyst on 28 Oct 2012
Edited: Image Analyst on 28 Oct 2012
I have "perfect" histogram equalization code in my File Exchange http://www.mathworks.com/matlabcentral/fileexchange/28972-custom-shaped-histogram You can get any shaped histogram you want. In fact, you can get a perfectly flat histogram which is the goal of histogram equalization. Nearly every other histogram equalization code you'll find just redistributes the bins to maximize the contrast but you will not end up with a perfectly flat histogram. I employ a couple of "tricks" involving random numbers to get the output histogram to be truly 100% flat. It's well commented however novices might find it a little bit challenging to follow, though the concepts are fairly simple, though clever.
Back to your code...to do the traditional, dumb, text book, non-flat histogram equalization you need to use the cumulative distribution function which you get by passing the pixelcount into cumsum(), instead of the for loops like you're doing. Then you need to "invert" it by seeing what input value gives you a desired output value. You can use intlut() for that.
Since it appears to be a homework exercise, because you're not allowed to use built in functions and this a requirement ONLY for homework assignments, you probably won't be able to do it in 2 or three lines using cumsum() and intlut() either.

Community Treasure Hunt

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

Start Hunting!