3-Matlab自带函数和自编写的函数对图像直方图均衡化对比
%函数功能,画出图像的直方图,并对图像进行直方图均衡 %图像增强clear allclose allimage=imread( sea.jpg ); %读入图片tu=rgb2gray(image);% %将彩色图片转换为灰度图 240*497 元素取值 0-255 J=histeq(tu);perGray=zeros(1,256); %设置矩阵大小 原直方图各灰度级个数 perGrayperGrayPro=zeros(1,256); %原直方图累计灰度级个数new_perGray=zeros(1,256);new_perGrayPro=zeros(1,256);[h w]=size(tu);% 240*497new_tu=zeros(h,w);%计算原始直方图各灰度级像素个数 perGrayfor x=1:hfor y=1:wperGray(1,tu(x,y))=perGray(1,tu(x,y))+1;%endend%计算原始直方图 perGrayPro,原直方图各灰度级像素个数归一化perGrayPro=perGray./sum(perGray);%将原图个各灰度级的频数归一化作为频率subplot(1,2,1);plot(perGrayPro);title( 原图的灰度直方图 );xlabel( 灰度值 );ylabel( 像素的概率密度 );subplot(1,2,2);imhist(tu);title( hist 得到的原始图像的直方图 ) ;axis([0 255 0 2500]);%%%计算原始累计直方图%利用累积分布函数作为映射关系,建立原图到新图的映射for i=2:256perGrayPro(1,i)=perGrayPro(1,i)+perGrayPro(1,i-1);end%计算和原始灰度对应的新的灰度 t[],建立映射关系 %重点步骤for i=1:256t(1,i)=floor(254*perGrayPro(1,i)+0.5); %将原图累计直方图元素 化为 0-255 作为新图的像素值end%%%统计新直方图各灰度级像素个数 new_perGrayfor i=1:256new_perGray(1,t(1,i)+1)=new_perGray(1,t(1,i)+1)+perGray(1,i);end%计算新的灰度直方图 new_perGrayPronew_perGrayPro=new_perGray./sum(new_perGray);figure();subplot(1,2,1);plot(new_perGrayPro);title( 均衡化后的灰度直方图 );xlabel( 灰度值 );ylabel( 像素的概率密度 );subplot(1,2,2);imhist(J);title( 用 histeq 得到的均衡化的的直方图 ); axis([0 255 0 2500]);%%%计算直方图均衡后的新图 new_tufor x=1:hfor y=1:wnew_tu(x,y)=t(1,tu(x,y));endend%%%输出原图和均衡后的图像figure();subplot(3,1,1);imshow(tu,[]);title( 原图灰度图 );subplot(3,1,2);imshow(new_tu,[]);title( 直方图均衡化后的图 );subplot(3,1,3);imshow(J);title( 用 histeq 得到的均衡化的图像 )