绘制线以连接质心

时间:2015-05-27 04:49:30

标签: matlab image-processing line centroid

我有一张图片

enter image description here

在我处理找到质心后,它有四个质心。 我的目标是我想用线连接它们并测量这个区域之间的角度。要明确质心和目标,您可以打开enter image description here

这是我的代码来实现质心

I = imread('22c.jpg');
Ibw = im2bw(I);
Ibw = imfill(Ibw,'holes');

Ilabel = bwlabel(Ibw);
stat = regionprops(Ilabel,'centroid');
imshow(I); hold on;
for x = 1: numel(stat)
    plot(stat(x).Centroid(1),stat(x).Centroid(2),'ro');
end

问题是我仍然感到困惑,要做下一个(连接每个质心并测量角度)。我需要你的帮助,谢谢

1 个答案:

答案 0 :(得分:1)

以下是file exchange linkbresenham.m

更改了您的代码以获取所有4个质心

%// read your input image
im = imread('http://i.stack.imgur.com/xeqe8.jpg');

BW = im>220;

CC = bwconncomp(BW);
stat = regionprops(CC,'Centroid');

figure; imshow(BW); hold on
for x = 1: numel(stat)
    plot(stat(x).Centroid(1),stat(x).Centroid(2),'ro');
end

以下是输出:

enter image description here

进一步实施:

%// putting all the Centroid coordinates into corresponding x,y variable
x = [stat(1).Centroid(1),stat(2).Centroid(1),stat(3).Centroid(1),stat(4).Centroid(1)];
y = [stat(1).Centroid(2),stat(2).Centroid(2),stat(3).Centroid(2),stat(4).Centroid(2)];

%// obtain row and col dim
[r,c] = size(BW);

%// get all x,y values connecting the centroid points
[xAll{1},yAll{1}] = bresenham(x(1),y(1),x(4),y(4));
[xAll{2},yAll{2}] = bresenham(x(2),y(2),x(3),y(3));
[xAll{3},yAll{3}] = bresenham(x(3),y(3),x(4),y(4));

%// change row and col subs to linear index
for ii = 1:3
    idx{ii} = sub2ind(size(BW),yAll{ii},xAll{ii});
end

%// change grayscale image to 3D (as you want red line)
out = repmat(im,[1,1,3]);

%// obtaining corresponding index of all 3 slices
for ii = 1:3
    idxall{ii} = bsxfun(@plus, idx{ii},[0:2].*(r*c));
end

%// keep only the index of 1st slice to 255 and changing rest to 0 to obtain a red line.
%// Similar process for blue line except keep the index in the 3rd slice to 255
out(cat(1,idxall{:})) = 0;
out(idx{1}) = 255;
out(idx{2}) = 255;
out(idx{3}+2*(r*c)) = 255;

%// see what you have obtained
figure; imshow(out);hold on
for x = 1: numel(stat)
    plot(stat(x).Centroid(1),stat(x).Centroid(2),'bo');
end

<强>结果:

注意:由于图片尺寸较大,该线条看起来可能会点缀,但其连续性

enter image description here

最后一个数字放大以查看连续线:

enter image description here

更进一步:

您可能需要接受@Spektre的建议才能使用atan2找到倾斜角度。另请参阅his answer以获取更多解释。