连接多维矩阵中的两个点



我正在尝试创建一个1和0的3D矩阵。我想通过在它们之间形成一条线的一条线来将2点(最短距离)连接在一起。

看起来像这样,但是在3D

path_pixels = [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0;
               0,0,0,1,0,0,0,0,0,0,0,0,0,0,0;
               0,0,0,0,1,0,0,0,0,0,0,0,0,0,0];

我可以使用此代码在2D中进行

clc;
clear;
%matrix size
A = zeros(70);
A(20,20) = 1;   %arbitrary point
B = zeros(70);
B(40,40) = 1; %arbitrary point
D1 = bwdist(A);
D2 = bwdist(B);
D_sum = D1 + D2 ;
path_pixels = imregionalmin(D_sum);
spy(path_pixels)

如何将此方法扩展到3D?

它完全取决于您的含义"连接"。但是,如果目标是在起点和终点之间的一个单元宽区域,那么看起来很像"单像素宽"线,可以定义如下。

% start and end point of line
a = [1 10 2];
b = [4 1 9];
% get diffs
ab = b - a;
% find number of steps required to be "one pixel wide" in the shorter
% two dimensions
n = max(abs(ab)) + 1;
% compute line
s = repmat(linspace(0, 1, n)', 1, 3);
for d = 1:3
    s(:, d) = s(:, d) * ab(d) + a(d);
end
% round to nearest pixel
s = round(s);
% if desired, apply to a matrix
N = 10;
X = zeros(N, N, N);
X(sub2ind(size(X), s(:, 1), s(:, 2), s(:, 3))) = 1;
% or, plot
clf
plot3(s(:, 1), s(:, 2), s(:, 3), 'r.-')
axis(N * [0 1 0 1 0 1])
grid on

请原谅丑陋的代码,我匆忙做到了;)。

最新更新