3

I'm trying to create a 3d matrix of 1's and 0's. I want to connect 2 points together (shortest distance) by forming a line of 1's in between them.

It would look something like this, but in 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];

I'm able to do it in 2d using this code

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)

How can I expand this method to 3d?

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Taimoor Khan
  • 585
  • 2
  • 6
  • 15

1 Answers1

1

It depends what you mean by "connect", exactly. But, if the goal is a one-cell wide region between starting and end points, then that looks a lot like a "one-pixel wide" line, which could be defined as follows.

% 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

Please forgive ugly code, I did this in a rush ;).