繁体   English   中英

如何在 MATLAB 中获得直线和边界之间的交点?

[英]How do I obtain intersection points between a line and a boundary in MATLAB?

我有一个人类的二进制图像。 在MATLAB中也定义了边界点和图像的中心,它们是两个列矩阵。 现在我想从中心到边界点画线,这样我就可以获得这些线和图像边界之间的所有交点。 我怎样才能做到这一点? 这是我到目前为止的代码:如果有人可以提供帮助,那么编写的代码只是为了获得一个交点

clear all  
close all  
clc
BW = im2bw(imread('C:\fyc-90_1-100.png'));
BW = imfill(BW,'holes');  
[Bw m n]=preprocess(BW);  
[bord sk pr_sk]=border_skeleton(BW);  
boundry=bord;        
L = bwlabel(BW);  
s = regionprops(L, 'centroid');  
centroids = cat(1, s.Centroid);

第 1 步 - 生成您的线路

您需要做的第一件事是弄清楚如何绘制线条。 为了简单起见,我们假设人体的中心存储为cen = [x1 y1]的数组,如您所说。 现在,假设您单击图像中的任意位置,您会得到另一个点linePt = [x2 y2] 让我们假设xy坐标分别是水平和垂直分量。 我们可以找到这条线的斜率和截距,然后在这两个由斜率和截距参数化的点之间创建点以生成您的线点。 我要指出的一件事是,如果我们用垂直线绘制斜率,根据定义,斜率将是无穷大。 因此,我们需要进行检查,看看我们是否有这种情况。 如果我们这样做,我们假设所有的x点都相同,而y不同。 有了斜率和截距后,只需在直线之间创建点即可。 您必须自己选择沿着这条线需要多少点,因为我不知道您图像的分辨率,也不知道您希望这条线有多大。 然后我们将其存储到一个名为linePoints的变量中,其中第一列由x值组成,第二列由y值组成。 换句话说:

换句话说,这样做:

%// Define number of points
numPoints = 1000;
%// Recall the equation of the line: y = mx + b, m = (y2-y1)/(x2-x1) 
if abs(cen(1) - linePt(1)) < 0.00001 %// If x points are close
    yPts = linspace(cen(2), linePt(2), numPoints); %// y points are the ones that vary
    xPts = cen(1)*ones(numPoints, 1); %//Make x points the same to make vertical line
else %// Normal case
    slp = (cen(2) - linePt(2)) / cen(1) - linePt(1)); %// Solve for slope (m)
    icept = cen(2) - slp*cen(1); %// Solve for intercept (b)
    xPts = linspace(cen(1), linePt(1), numPoints); %// Vary the x points
    yPts = slp*xPts + icept; %// Solve for the y points
end
linePoints = [xPts(:) yPts(:)]; %// Create point matrix

第 2 步 - 寻找交点

假设您有一个点[xy]的二维数组,其中x表示水平坐标, y表示线的垂直坐标。 我们可以简单地找到边界中所有这些点与线上所有点之间的距离。 如果任何点低于某个阈值(例如0.0001 ),则这表示交叉点。 请注意,由于浮点数据的关键,由于数据中每个离散点之间的步长,我们无法检查距离是否为0

我还将假设border_skeleton返回相同格式的点。 此方法无需指定质心即可工作。 因此,我不需要在我提议的方法中使用质心。 此外,我将假设您的线点存储在一个名为linePoints的矩阵中,该矩阵与我刚刚谈到的类型相同。

换句话说,这样做:

numBoundaryPoints = size(boundry, 1); %// boundary is misspelled in your code BTW
ptsIntersect = []; %// Store points of intersection here
for idx = 1 : numBoundaryPoints %// For each boundary point...
    %//Obtain the i'th boundary point
    pt = boundry(:,idx);

    %//Get distances - This computes the Euclidean distance
    %//between the i'th boundary point and all points along your line
    dists = sqrt(sum(bsxfun(@minus, linePoints, pt).^2, 2));

    %//Figure out which points intersect and store
    ptsIntersect = [ptsIntersect; linePoints(dists < 0.0001, :)];
end

最后, ptsIntersect将存储沿边界与这条线相交的所有点。 请注意,我在这里做了很多假设,因为您没有(或似乎不愿意)提供比您在评论中指定的更多细节。


祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM