RGB 顏色空間轉 HSI 顏色空間的matlab程序實現
2014.10.20之前的內容有誤,這里依據wikipedia更新了算法內容. 算法以wiki為准
https://en.wikipedia.org/wiki/HSL_and_HSV
這里demo出 HSI中 S 空間的圖像和暗通道圖的對照.
會發現,確實右邊到非常暗,這是由於HSV轉換的時候對RGB值做了歸一化處理,假設打印出歸一化處理后的R+G+B值會發現輸出圖像非常亮(白茫茫一片~)
下圖是取自圖像第321列的數據分布,能夠看見圖像的灰度分布是非常明晰的
以下給出了我寫的轉換函數,直接調用就可以.
%%************************************************************************** % Function writer : EOF % code file : RGB2SHI_Color.m % code date : 2014.10.16 % Translate RGB into HSI-space % % Code Description: % % If you want to translate a colourful Image which is coded as % RGB colour space into HSI space, what you need to do is just input your % colour image. % % This function would return HSI as a matrix [H,S,I]. % %% ************************************************************************* function [H,S,I] = RGB2SHI_Color(Image) if size(Image,3) ~= 3 fprintf('ERROR Imput-Image must be three channel image\n'); return; end Height_Image = size(Image,1); Width_Image = size(Image,2); Channel_Image = size(Image,3); H = zeros(1,Height_Image * Width_Image); H_temp = zeros(1,Height_Image * Width_Image); S = zeros(1,Height_Image * Width_Image); I = zeros(1,Height_Image * Width_Image); %% Normalization into (0,1) R_temp = double(Image(:,:,1)); G_temp = double(Image(:,:,2)); B_temp = double(Image(:,:,3)); R = R_temp./(R_temp + G_temp + B_temp); G = G_temp./(R_temp + G_temp + B_temp); B = B_temp./(R_temp + G_temp + B_temp); Max_channel = max(max(R,G),B); Min_channel = min(min(R,G),B); Difference = Max_channel - Min_channel; I = (R + G + B)./3; for row = 1:Height_Image for col = 1: Width_Image % In fact , if Difference(row,col) is zero, the H_temp is % undefine , it means that H_temp(row,col) close to % infinite. if Difference(row,col) == 0 H_temp(row,col) = 0; end if Max_channel(row,col) == R(row,col) H_temp(row,col) = mod((G(row,col) - B(row,col)) ... ./Difference(row,col), 6 ); end if Max_channel(row,col) == G(row,col) H_temp(row,col) = (B(row,col) - R(row,col)) ... ./Difference(row,col) + 2; end if Max_channel(row,col) == B(row,col) H_temp(row,col) = (B(row,col) - R(row,col)) ... ./Difference(row,col) + 4; end H(row,col) = H_temp(row,col)*60; if I(row,col) == 0 S(row,col) = 0; else S(row,col) = 1 - (Min_channel(row,col)./I(row,col)); end end end end