Bootstrap

Matlab底层算法实现直方图均衡

理论原理

     直方图均衡常用于图像预处理过程中,对灰度的矫正十分有效。

公式

     灰度的线性变换就是将图像中所有点的灰度按照线性灰度变换函数进行变换。灰度变换方程为:
                                                                P r ( r i ) = N u m ( r i ) C o u n t N u m P_{r}(r_{i})=\frac{Num(r_{i})}{CountNum} Pr(ri)=CountNumNum(ri),
                                                                     ∑ i = 0 k − 1 P r ( r i ) = 1 \sum_{i=0}^{k-1}P_{r}(r_{i})=1 i=0k1Pr(ri)=1
式中 k k k为一帧图像对应的灰度级数。
     直方图均衡化就是利用累积分布函数作为灰度变换函数。 T ( r ) T(r) T(r)与原图像概率密度分布函数 P r ( r ) Pr(r) Pr(r)之间的关系为:
                                                                s = T ( r ) = ( k − 1 ) ∫ 0 r 1 P r ( r ) d r s=T(r)=(k-1)\int_{0}^{r_{1}}P_{r}(r)dr s=T(r)=(k1)0r1Pr(r)dr

源代码

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%图像灰度直方图均衡化
%Author:Zhu
%时间:2022.3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc;
image = imread("F:\\fabrik.png");

image_matrix=image(:,:,1);
image_matrix=double(image_matrix);
[height,width,channels]=size(image);
image_out=zeros(height,width);

%灰度映射表,灰度从0255之间
gray_map = zeros(1,256);

%灰度直方图丧失了灰度的像素值位置信息,只有灰度分布信息
 for i=1:height
      for j=1:width
           T = image_matrix(i,j)+1;
           %灰度统计计数
           gray_map(T)=gray_map(T)+1;
      end
 end

%计算灰度分布密度,即归一化,灰度分布概率
gray_layout = zeros(1,256);
for i=1:256
    gray_layout(i)=gray_map(i)/(height*width);
end

%进行均衡化处理
tmp = zeros(1,256);
balance_gray = zeros(1,256);
for i=1:256
    if(i==1)
       tmp(1) = gray_layout(1);
    else
       %先累加
       tmp(i) = tmp(i-1)+gray_layout(i);
    end
    balance_gray(i)=ceil(255*tmp(i)+0.1);
end

 for i=1:height
      for j=1:width
           T = image_matrix(i,j)+1;
           image_out(i,j)=balance_gray(T);
      end
 end
 
image_out = uint8(image_out);
%显示 
subplot(1,2,1);
imshow(image);
title("原图");
subplot(1,2,2);
imshow(image_out);
title("直方图均衡");

效果图

在这里插入图片描述

;