Matlab图像处理学习笔记(二):基于颜色的图像分割

在实际处理图像时,经常需要对图像进行分割,然后提取ROI,本学习笔记记录怎么用Matlab实现基于颜色的图像分割。

基于颜色的图像分割实现简单,算法简洁,具有很好的实时性。

实现代码的过程中,我参考了Kyle Hounslow的objectTrackingTutorial.cpp,链接:https://www.youtube.com/watch?v=bSeFrPrqZ2A点击打开链接。颜色分割的数据范围及寻找最大连通区域的思想由师兄提供。

转载请注明出处:http://blog.csdn.net/u010278305。

本文涉及到的知识点如下:

1、RGB到YCBCR的色彩空间转换。

2、用各个通道的阈值对图像进行二值化。

3、形态学处理:腐蚀、膨胀、孔洞填充。

4、连通区域提取。

主要涉及到的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

 

运行之后的效果如下图:



原始图片已上传。


 

posted on 2015-01-08 13:32  chenyn2014  阅读(23808)  评论(2编辑  收藏  举报

导航