%直方图均衡化
%第一种方法:
I = imread('rice.png');%读取原始图像
[height,width] = size(I);
figure,
subplot(221);
imshow(I);%显示原始图像
subplot(222);
imhist(I)%显示原始图像直方图
%进行像素灰度统计;
NumPixel = zeros(1,256);%统计各灰度数目,共256个灰度级;zeros生成零矩阵,zeros([m n]):生成m×n全零阵。
for i = 1:height
for j = 1: width
NumPixel(I(i,j) + 1) = NumPixel(I(i,j) + 1) + 1;%对应灰度值像素点数量增加一
end
end
%计算灰度分布密度
ProbPixel = zeros(1,256);
for i = 1:256
ProbPixel(i) = NumPixel(i) / (height * width * 1.0);
end
%计算累计直方图分布
CumuPixel = zeros(1,256);
for i = 1:256
if i == 1
CumuPixel(i) = ProbPixel(i);
else
CumuPixel(i) = CumuPixel(i - 1) + ProbPixel(i);
end
end
%累计分布取整
CumuPixel = uint8(255 .* CumuPixel + 0.5);%matlab读入图像的数据是uint8,而matlab中数值一般采用double型(64位)存储和运算。所以要先将图像转为double格式的才能运算
%对灰度值进行映射(均衡化)
for i = 1:height
for j = 1: width
I(i,j) = CumuPixel(I(i,j));
end
end
subplot(223)
imshow(I)%显示原始图像
subplot(224)
imhist(I)%显示原始图像直方图
%第二种方法:
close all;clear all;clc;
%函数histeq()进行直方图均衡化处理
I=imread('tire.tif');
J=histeq(I); %直方图均衡化
figure,
subplot(121),imshow(uint8(I));
title('原图')
subplot(122),imshow(uint8(J));
title('均衡化后')
figure,
subplot(121),imhist(I,64);
title('原图像直方图');
subplot(122),imhist(J,64);
title('均衡化后的直方图');