簡體   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