Matlab - 查找直线和周长之间的坐标

时间:2016-06-16 16:44:59

标签: matlab image-processing matrix intersection

我使用bwlabel分割鼠标并获取其图像属性。从而我可以访问质心的位置和鼠标的方向。我还使用bwperim来获取鼠标的周长。

我想找到穿过质心的直线的两个点,并且方向与切割周边的鼠标的方向相同。

我使用该代码找到直线的等式:

% E is a 2*2 matrix containing the coordinates of the centroid and the
% coordinates of the point which belong to the straight line and making 
% the right angle given by the orientation
coeffs = polyfit(E(:,1),E(:,2),1);
% Create the equation of the straight line
x = 1:width;
yfit = coeffs(1)*x+coeffs(2);
% Make sure there are only int values.
yfit = uint16(yfit);

我将我的值转换为uint16,因为我想填充一个新矩阵,我将与包含周长的矩阵进行比较。这就是我的所作所为:

% Create a matrix of zeros and set to 1 all the pixels which belong to the
% straight line 
k = 1;
temp = false;
m = false(size(iPerim));
while temp~=true
    temp = false;
    if yfit(k) > 0
        m(yfit(k),k)=1;
        temp = true;
    end
    k = k+1;
end
[t,p] = ind2sub(size(m), find(m==1));
minM = [min(p),min(t)];
% complete the straight line to don't have little holes
x = linspace(minM(1),D(1),width);
y = coeffs(1)*x+coeffs(2);
idx = sub2ind(size(m),round(y),round(x));
m(idx) = 1;

然后我将m与iPerim进行比较,后者是包含我的周长的矩阵:

% Compare the matrix of the perimeter and the matrix of the straight line
% and find the two points in common. It is the points where the straight
% line cut the perimeter
p = m & iPerim;
% Extract thoses coordinates 
[coordsY,coordsX] = ind2sub(size(p), find(p==1));

我是Matlab的新用户,所以我认为这不是一个优雅的解决方案,但结果是:

Matrix m

matrix m

我绘制yfit的周界

Perimeter where I plot yfit

正如你所看到的算法只检测到一个点,而不是第二个点(黄点)...我想为什么,但我找不到解决方案。这是因为直线是通过对角线切割周边但没有共同的坐标...

有人解决了我的问题吗?当然,我正在采取任何建议来改变我的代码:)

非常感谢!

编辑:如果有一个更简单的解决方案,我明显地采取了

1 个答案:

答案 0 :(得分:1)

当鼠标周长与线交叉的点的坐标为E(2,:)时,该点中该点的位置是距离最小的位置。例如。像:

[xLine, yLine] = find(m);    % x,y positions of the line
dX = abs(xline-E(2,1))       % x-distance to x-coordinate of direction-point
dY = abs(yLine-E(2,2))       % y-distance to y-coordinate of direction-point
distP =  sqrt(dX.^2+dY.^2)   % distance of line-points to directon-point
[~,indMin] = min(distP);     % index of line-point which has the minimum distance
xPoint = xLine(indMin(1)); 
yPoint = yLine(indMin(1));

此处不需要abssqrt函数来查找正确的点,仅用于正确的中间值......

关于ind2sub的Matlab文档:

  

对于矩阵,[I,J] = ind2sub(size(A),find(A> 5))返回与[I,J] = find(A> 5)相同的值。