少時几何

星月神话

导航

查找二值图像连通区域的质心

研究摄像头的目的,在于对运动的物体进行定位,并提取特征值为下一步的运动控制做准备,当然,这之前需要基本的确定某一静态物体的位置,很容易让我们想到确定感兴趣区域的质心。下面代码是对一幅图像进行的处理:

image = imread('2.jpg');
image = rgb2gray(image);
thresh = graythresh(image);
image = ~im2bw(image,thresh);%背景色和前景色互换
imshow(image);
[L,num] = bwlabel(image,8);%标记二值化图像中的连通部分
plotx = zeros(1,1);%记录质心位置坐标的变量
ploty = zeros(1,1);
%%求质心
sumx = 0;
sumy = 0;
area = 0;
[height,width] = size(image);
for i = 1 : height
	for j = 1 : width
		if L(i,j) == 1
			sumx = sumx + i;
			sumy = sumy + j;
			area = area + 1;
		end
	end
end

%%质心坐标
plotx(1) = fix(sumx / area);
ploty(1) = fix(sumy / area);
dis = dataset(plotx(1),ploty(1));%变量dis为质心位置坐标数据(行列)
figure(2);
imshow(image);

hold on
plot(ploty(1),plotx(1),'*');

在寻找质心的过程中,刚开始是找寻的是背景色连通区域的质心,而不是感兴趣部分的质心,针对这个问题,就二值化图像而言,最好的办法就是在二值化前加反向符号,即背景色和前景色互换,就OK了。今天到这里,后天接着探究动态质心的可行性~

下面是效果图:


posted on 2014-01-04 16:32  Lewiski  阅读(1223)  评论(0编辑  收藏  举报