MATLAB圖像處理-圖像增強之彩色圖像直方圖均衡化（RGB通道和HSV通道兩種）

對RGB通道

OutImg(:,:,1)=R;
OutImg(:,:,2)=G;
OutImg(:,:,3)=B;

``````%%
clc
clear all
%%
%%變化前灰度值
OutImg=I;
R=I(:,:,1);
subplot(2,3,1)
imhist(R);
title('R')
G=I(:,:,2);
subplot(2,3,2)
imhist(G);
title('G')
B=I(:,:,3);
subplot(2,3,3)
imhist(B);
title('B')
%%
%%變化後灰度值
R=hist_1(R);
subplot(2,3,4)
imhist(R);
title('after R')
G=hist_1(G);
subplot(2,3,5)
imhist(G);
title('after G')
B=hist_1(B);
subplot(2,3,6)
imhist(B);
title('after B')
%%
%變化後圖像
OutImg(:,:,1)=R;
OutImg(:,:,2)=G;
OutImg(:,:,3)=B;
figure,
imshow(I);
title('原圖像')
figure,
imshow(OutImg);
title('直方圖均衡化後的圖像')
%%
%直方圖均衡化函數
function hist_img = hist_1(I)
[M, N] = size(I);
size_img = M*N;
c = zeros(1,256);%統計每個每個像素值的個數
b= c;%轉化前後的對照表

temp = I(:);
temp = sort(temp);

for i = 1:size_img
c(temp(i)+1) = c(temp(i)+1)+1;
end
a = c;%求和
for i = 2:256
a(i) = c(i) + a(i-1);
end

min_cdf = 10000;
for i = 1:256
if a(i)>0
if a(i) < min_cdf
min_cdf = a(i);
end
end
end

for j = 1:256
if a(j) > 0
b(j) = round(255*(a(j)-min_cdf)/(size_img-min_cdf));
end
end

for i = 1:M
for j = 1:N
I(i,j) = b(I(i,j)+1);
end
end
hist_img = I;
end
``````

ps：圖片拍攝於湖南師範大學體育館二樓，2019.10.1

對HSV通道

HSV(Hue, Saturation, Value)是根據顏色的直觀特性由A. R. Smith在1978年創建的一種顏色空間, 也稱六角錐體模型(Hexcone Model)。

V通道通常小於1，但是直方圖均衡化爲0-255，故：
floor(v * 255)

v/255

``````%%
clc
clear all
%%
%%HSV
OutImg=rgb2hsv(I);
V=OutImg(:,:,3);
V = floor(V * 255);
%%
%%變化後V
V=hist_1(V);
V = V / 255;
%%
%變化後圖像
OutImg(:,:,3) = V;
OutImg = hsv2rgb(OutImg);

imshow(I);
title('原圖像')
figure,
imshow(OutImg);
title('直方圖均衡化後的圖像')
%%
%直方圖均衡化函數
function hist_img = hist_1(I)
[M, N] = size(I);
size_img = M*N;
c = zeros(1,256);%統計每個每個像素值的個數
b= c;%轉化前後的對照表

temp = I(:);
temp = sort(temp);

for i = 1:size_img
c(temp(i)+1) = c(temp(i)+1)+1;
end
a = c;%求和
for i = 2:256
a(i) = c(i) + a(i-1);
end

min_cdf = 10000;
for i = 1:256
if a(i)>0
if a(i) < min_cdf
min_cdf = a(i);
end
end
end

for j = 1:256
if a(j) > 0
b(j) = round(255*(a(j)-min_cdf)/(size_img-min_cdf));
end
end

for i = 1:M
for j = 1:N
I(i,j) = b(I(i,j)+1);
end
end
hist_img = I;
end
``````