Matlab圖像處理學習筆記(二):基於顏色的圖像分割

在實際處理圖像時,常常須要對圖像進行分割,而後提取ROI,本學習筆記記錄怎麼用Matlab實現基於顏色的圖像分割。算法

基於顏色的圖像分割實現簡單,算法簡潔,具備很好的實時性。函數

實現代碼的過程當中,我參考了Kyle Hounslow的objectTrackingTutorial.cpp,連接:https://www.youtube.com/watch?v=bSeFrPrqZ2A點擊打開連接。顏色分割的數據範圍及尋找最大連通區域的思想由師兄提供。學習

轉載請註明出處:http://blog.csdn.net/u010278305。spa

本文涉及到的知識點以下:.net

一、RGB到YCBCR的色彩空間轉換。code

二、用各個通道的閾值對圖像進行二值化。orm

三、形態學處理:腐蝕、膨脹、孔洞填充。blog

四、連通區域提取。圖片

主要涉及到的Matla圖形處理函數以下:rgb2ycbcr(色彩空間轉換),roicolor(ROI二值化),imerode(腐蝕),imdilate(膨脹),imfill(孔洞填充),regionprops(區域屬性)。這些函數的具體實現仍是參考岡薩雷斯的《數字圖像處理》,及matlab幫助文檔,及論文引用。文檔

很少說了,具體看代碼,每一步都有註釋.

%function:
%       基於顏色的圖像分割
%       定位圖片中的臉部區域
%referrence:
%       思路借鑑Kyle Hounslow寫的objectTrackingTutorial.cpp。
%       Kyle Hounslow的原版代碼連接:https://www.youtube.com/watch?v=bSeFrPrqZ2A
%       Y_MIN ,Y_MAX ,Cb_MIN , Cb_MAX ,Cr_MIN , Cr_MAX 的取值及尋找最大區域的想法由課題組師兄提供
%date:2015-1-8
%author:chenyanan
%轉載請註明出處:http://blog.csdn.net/u010278305

%清空變量,讀取圖像
clear;close all
RGB = imread('images/girl.jpg');

figure('name','process'),
subplot(2,2,1),imshow(RGB),title('原始RGB'),

%convert frame from RGB to YCBCR colorspace(轉換到YCBCR空間)
YCBCR = rgb2ycbcr(RGB);
whos,
subplot(2,2,2),imshow(YCBCR),title('YCBCR'),
%filter YCBCR image between values and store filtered image to threshold
%matrix(用各個通道的閾值對其進行二值化處理)
Y_MIN = 0;  Y_MAX = 256;
Cb_MIN = 100;   Cb_MAX = 127;
Cr_MIN = 138;   Cr_MAX = 170;
threshold=roicolor(YCBCR(:,:,1),Y_MIN,Y_MAX)&roicolor(YCBCR(:,:,2),Cb_MIN,Cb_MAX)&roicolor(YCBCR(:,:,3),Cr_MIN,Cr_MAX);
subplot(2,2,3),imshow(threshold),title('YCBCR二值化'),

%perform morphological operations on thresholded image to eliminate noise
%and emphasize the filtered object(s)(進行形態學處理:腐蝕、膨脹、孔洞填充)
erodeElement = strel('square', 3) ;
dilateElement=strel('square', 8) ;
threshold = imerode(threshold,erodeElement);
threshold = imerode(threshold,erodeElement);
threshold=imdilate(threshold, dilateElement);
threshold=imdilate(threshold, dilateElement);
threshold=imfill(threshold,'holes');
subplot(2,2,4),imshow(threshold),title('形態學處理'),

%獲取區域的'basic'屬性, 'Area', 'Centroid', and 'BoundingBox' 
figure('name','處理結果'),
stats = regionprops(threshold, 'basic');
[C,area_index]=max([stats.Area]);
%定位臉部區域
face_locate=[stats(area_index).Centroid(1),stats(area_index).Centroid(2)];
imshow(RGB);title('after'),hold on
text(face_locate(1),face_locate(2)-40,  'face','color','red');
plot(face_locate(1),face_locate(2), 'b*');
rectangle('Position',[stats(area_index).BoundingBox],'LineWidth',2,'LineStyle','--','EdgeColor','r'),
hold off

 

運行以後的效果以下圖:



原始圖片已上傳。

相關文章
相關標籤/搜索