MATLAB--数字图像处理图像直⽅图均衡化
图像直⽅图均衡化
⾸先,我们要理解什么是图像直⽅图均衡化:
把原始图像的灰度直⽅图从⽐较集中的某个灰度区间变成在全部灰度范围内的均匀分布。直⽅图均衡化就是对图像进⾏⾮线性拉伸,重新分配图像像素值,使⼀定灰度范围内的像素数量⼤致相同。直⽅图均衡化就是把给定图像的直⽅图分布改变成“均匀”分布直⽅图分布,具体见下图(说的简单点,就是把原来的图像的灰度分配均匀,使得0-255都有⼀定的取值,这样对⽐度相对⼤⼀些,视觉上更好看⼀点):
这⾥我们可以直接利⽤histeq()、adapthisteq()函数对图像进⾏均衡化
H= imread('a1.jpg');
if length(size(H))>2
H=rgb2gray(H);
end
subplot(3,2,1);
imshow(H); title('原图');
subplot(3,2,2);
imhist(H); title('原图直⽅图');
subplot(3,2,3);
H1=adapthisteq(H);
imshow(H1); title('adapthisteq均衡后图');
subplot(3,2,4);
imhist(H1);title('adapthisteq均衡后直⽅图');
subplot(3,2,5);
H2=histeq(H);
imshow(H2); title('histeq均衡后图');
subplot(3,2,6);
imhist(H1); title('histeq均衡后直⽅图');
效果图:
当然,我们也可以⾃⼰编写均衡化函数,⾸先就要了解均衡化的(这⾥我就不多说了)上代码:
H= imread('a1.jpg');
%判断是否为三通道彩⾊图⽚若是则将其灰度化
if length(size(H))>2
H=rgb2gray(H);
end
%获取图⽚的尺⼨便于计算总像素数即m*n [m,n]=size(H);
%⽣成⼀个⼀⾏256列的矩阵
p=zeros(1,256);
% 统计各灰度的像素个数
%find(H==i) 是在图像矩阵⾥⾯寻灰度为i的点坐标% 因为矩阵是从1开始的所以为p(i+1)
for i=0:255
p(i+1)=length(find(H==i))/(m*n);
end
subplot(2,2,1);
imshow(H);
title('原图');
subplot(2,2,2);
% 显⽰原图的直⽅图
bar(0:255,p,'b');
title('原图直⽅图');
% 利⽤循环累加概率值
s=zeros(1,256);
for i=1:256
for j=1:i
s(i)=p(j)+s(i);
end
end
%对s中的数先乘以255,再取整
a=round(s*255);
b=H;
%更新原图像的灰度
for i=0:255
b(find(H==i))=a(i+1);
end
subplot(2,2,3);
imshow(b)
title('均衡化后图像');
%统计更新后的概率
for i=0:255
GPeq(i+1)=sum(p(find(a==i)));
end
subplot(2,2,4);
bar(0:255,GPeq,'b'); title('均衡化后的直⽅图');
效果图:
⽅法⼆(从⼤佬那⾥copy的)
Img= imread('a1.jpg');
if length(size(Img))>2
Img=rgb2gray(Img);
end
%绘制原始图像的直⽅图
[height,width]=size(Img);
[counts1, x] = imhist(Img,256);
counts2 = counts1/height/width;
figure(1),
subplot(1,2,1),
imshow(Img);title('原始图像');
subplot(1,2,2),
stem(x, counts2); title('原始图像直⽅图');
%统计每个灰度的像素值累计数⽬
NumPixel = zeros(1,256);%统计各灰度数⽬,共256个灰度级
for i = 1:height
for j = 1: width
%对应灰度值像素点数量+1
%NumPixel的下标是从1开始,⽽图像像素的取值范围是0~255,所以⽤NumPixel(Img(i,j) + 1)
NumPixel(Img(i,j) + 1) = NumPixel(Img(i,j) + 1) + 1;
end
end
%将频数值算为频率
ProbPixel = zeros(1,256);
for i = 1:256
ProbPixel(i) = NumPixel(i) / (height * width * 1.0);
end
%函数cumsum来计算cdf,并将频率(取值范围是0.0~1.0)映射到0~255的⽆符号整数
CumuPixel = cumsum(ProbPixel);
CumuPixel = uint8(255 .* CumuPixel + 0.5);
%直⽅图均衡。赋值语句右端,Img(i,j)被⽤来作为CumuPixel的索引
for i = 1:height
for j = 1: width
Img(i,j) = CumuPixel(Img(i,j)+1);
end
end
%显⽰更新后的直⽅图
figure(2),
subplot(1,2,1),
matlab直方图
imshow(Img); title('直⽅图均衡化图像');
[counts1, x] = imhist(Img,256);
counts2 = counts1/height/width;
subplot(1,2,2),
stem(x, counts2); title('直⽅图均衡化后图像的直⽅图');
上⾯都是对灰度图⽚进⾏均衡化,那么对彩⾊图⽚怎么均衡化呢?办法肯定是有的。我们知道,彩⾊图⽚⽆⾮就是RGB三通道组成的,只要我们分别对三个通道进⾏均衡化,再合成,得到的图⽚就是彩⾊的,均衡化后的。
上代码:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。