How do I track when multiple objects touch in MATLAB? - matlab

I have x,y pixel coordinates of multiple objects that have been tracked from an image (3744x5616). The coordinates are stored in a structure called objects, e.g.
objects(1).centre = [1868 1236]
The objects are each uniquely identified by a numerical code, e.g.
objects(i).code = 33
I want to be able to record each time any two objects come within a radius of 300 pixels each other. What would be the best way to check through if any objects are touching and then record the identity of both objects involved in the interaction, like object 33 interacts with object 34.
Thanks!

Best thing I can think of right now is a brute force approach. Simply check the distances from one object's centre with the rest of the other objects and manually check if the distances are < 300 pixels.
If you want this fast, we should probably do this without any toolboxes. You can intelligently do this with vanilla MATLAB using bsxfun. First, create separate arrays for the X and Y coordinates of each object:
points = reshape([objects.centre], 2, []);
X = points(1,:);
Y = points(2,:);
[objects.centre] accesses the individual coordinates of each centre field in your structure and unpacks them into a comma-separated list. I reshape this array so that it is 2 rows where the first row is the X coordinate and the second row is the Y coordinate. I extract out the rows and place them into separate arrays.
Next, create two difference matrices for each X and Y where the rows denote one unique coordinate and the columns denote another unique coordinate. The values inside this matrix are the differences between the point i at row i and point j at column j:
Xdiff = bsxfun(#minus, X.', X);
Ydiff = bsxfun(#minus, Y.', Y);
bsxfun stands for Binary Singleton EXpansion FUNction. If you're familiar with the repmat function, it essentially replicates matrices and vectors under the hood so that both inputs you're operating on have the same size. In this case, what I'm doing is specifying X or Y as both of the inputs. One is the transposed version of the other. By doing this bsxfun automatically broadcasts each input so that the inputs match in dimension. Specifically, the first input is a column vector of X and so this gets repeated and stacked horizontally for as many times as there are values in X.
Similarly this is done for the Y value. After you do this, you perform an element-wise subtraction for both outputs and you get the component wise subtraction between one point and another point for X and Y where the row gives you the first point, and the column gives you the second point. As a toy example, imagine we had X = [1 2 3]. Doing a bsxfun call using the above code gives:
>> Xdiff = bsxfun(#minus, [1 2 3].', [1 2 3])
Xdiff =
## | 1 2 3
----------------------
1 | 0 -1 -2
2 | 1 0 -1
3 | 2 1 0
There are some additional characters I placed in the output, but these are used solely for illustration and to give you a point of reference. By taking a row value from the ## column and subtracting from a column value from the ## row gives you the desired subtract. For example, the first row second column illustrates 1 - 2 = -1. The second row, third column illustrates 2 - 3 = -1. If you do this for both the X and Y points, you get the component-wise distances for one point against all of the other points in a symmetric matrix.
You'll notice that this is an anti-symmetric matrix where the diagonal is all 0 ... makes sense since the distance of one dimension of one point with respect to itself should be 0. The bottom left triangular portion of the matrix is the opposite sign of the right... because of the order of subtraction. If you subtracted point 1 with point 2, doing the opposite subtraction gives you the opposite sign. However, let's assume that the rows denote the first object and the columns denote the second object, so you'd want to concentrate on the lower half.
Now, compute the distance, and make sure you set either the upper or lower triangular half to NaN because when computing the distance, the sign gets ignored. If you don't ignore this, we'd find duplicate objects that interact, so object 3 and object 1 would be a different interaction than object 1 and object 3. You obviously don't care about the order, so set either the upper or lower triangular half to NaN for the next step. Assuming Euclidean distance:
dists = sqrt(Xdiff.^2 + Ydiff.^2);
dists(tril(ones(numel(objects))==1)) = NaN;
The first line computes the Euclidean distance of all pairs of points and we use tril to extract the lower triangular portion of a matrix that consists of all logical 1. Extracting this matrix, we use this to set the lower half of the matrix to NaN. This allows us to skip entries we're not interested in. Note that I also set the diagonal to 0, because we're not interested in distances of one object to itself.
Now that you're finally here, search for those objects that are < 300 pixels:
[I,J] = find(dists < 300);
I and J are row/column pairs that determine which rows and columns in the matrix have values < 300, so in our case, each pair of I and J in the array gives you the object locations that are close to each other.
To finally figure out the right object codes, you can do:
codes = [[objects(I).code].' [objects(J).code].'];
This uses I and J to access the corresponding codes of those objects that were similar in a comma-separated list and places them side by side into a N x 2 matrix. As such, each row of codes gives you unique pairs of objects that satisfied the distance requirements.
For copying and pasting:
points = reshape([objects.centre], 2, []);
X = points(1,:);
Y = points(2,:);
Xdiff = bsxfun(#minus, X.', X);
Ydiff = bsxfun(#minus, Y.', Y);
dists = sqrt(Xdiff.^2 + Ydiff.^2);
dists(tril(ones(numel(objects))==1)) = NaN;
[I,J] = find(dists < 300);
codes = [[objects(I).code].' [objects(J).code].'];
Toy Example
Here's an example that we can use to verify if what we have is correct:
objects(1).centre = [1868 1236];
objects(2).centre = [2000 1000];
objects(3).centre = [1900 1300];
objects(4).centre = [3000 2000];
objects(1).code = 33;
objects(2).code = 34;
objects(3).code = 35;
objects(4).code = 99;
I initialized 4 objects with different centroids and different codes. Let's see what the dists array gives us after we compute it:
>> format long g
>> dists
dists =
NaN 270.407100498489 71.5541752799933 1365.69396278961
NaN NaN 316.227766016838 1414.2135623731
NaN NaN NaN 1303.84048104053
NaN NaN NaN NaN
I intentionally made the last point farther than any of the other three points to ensure that we can show cases where there are points not near other ones.
As you can see, points (1,2) and (1,3) are all near each other, which is what we get when we complete the rest of the code. This corresponds to objects 33, 34 and 35 with pairings of (33,34) and (33,35). Points with codes 34 and 35 I made slightly smaller, but they are still greater than the 300 pixel threshold, so they don't count either:
>> codes
codes =
33 34
33 35
Now, if you want to display this in a prettified format, perhaps use a for loop:
for vec = codes.'
fprintf('Object with code %d interacted with object with code %d\n', vec(1), vec(2));
end
This for loop is a bit tricky. It's a little known fact that for loops can also accept matrices and the index variable gives you one column of each matrix at a time from left to right. Therefore, I transposed the codes array so that each pair of unique codes becomes a column. I just access the first and second element of each column and print it out.
We get:
Object with code 33 interacted with object with code 34
Object with code 33 interacted with object with code 35

Related

Faster way of putting Matrix elements into vectors other than a for loop

Hopefully this will come across correctly. I have 4 clouds/groups of points in a grid array (imagine a 2D space with 4 separate clusters of for example 3x3 grid of points) with each point having an X and Y coordinate. I'd like to write a vector of four points in the form of (X1, Y1, X2, Y2, X3, Y3, X4, Y4) where the number represents each cloud/group. Now I would actually like to write a matrix of all the combinations of the above vector covering all the points, so upper left points in all four groups in the first line, same for the second line, but the top middle point for group 4, etc.
One way to do it is to for-loop over all the variable, which would mean 8 nested for loops (4 for each X coordinate of 4 groups, 4 for each Y coordinate of 4 groups).
Is there a faster way maybe? 4 3x3 groups means 6561 combinations. Going to a larger array in each group, 11x11 for example, would mean 214 million combinations.
I'm trying to parallelize some calculations using these point coordinates, but writing the results in a parfor loop presents it's own set of issues if I was to do it on the points themselves. With a matrix of combinations I could just write the results in another matrix with the same number of rows and write the result of the nth row of point coordinates to the nth row of results.
As I understand, you have 4 groups of 3x3=9 coordinate pairs. You need to draw one pair from each group as one result, and produce all possible such results.
Thus, reducing each of the groups of 9 coordinate pairs to a lookup-table that is indexed with a number from 1 to 9, your problem can be reduced to drawing, with replacement, 4 values from the set 1:9.
It is fairly easy to produce all such combinations. permn is one function that does this (from the File Exchange). But you can actually get these even easier using ndgrid:
ind = 1:9;
[a1,a2,a3,a4] = ndgrid(ind,ind,ind,ind);
ind = [a1(:),a2(:),a3(:),a4(:)];
Each row in ind is the indices into one of your 3x3 grids.
For example, if grid 1 is:
x1 = [0.5,0.7,0.8];
y1 = [4.2,5.7,7.1];
then you can generate the coordinate pairs as follows:
[x1,y1] = meshgrid(x1,y1); % meshgrid is nearly the same as ndgrid...
xy1 = [x1(:),y1(:)];
Now your combination k is:
k = 563;
[xy1(ind(k,1),:), xy2(ind(k,2),:), xy3(ind(k,3),:), xy4(ind(k,4),:)]
You probably want to implement the above using multidimensional arrays rather than x1, x2, x3, etc. Adding indices to variables makes for confusing code that is difficult to extend. For example, for n groups you could write:
n = 4;
ind = 1:9;
ind = repmat({ind},n,1);
[ind{:}] = ndgrid(ind{:});
ind = cellfun(#(m)reshape(m,[],1), ind, 'UniformOutput',false);
ind = [ind{:}]; % ind is now the same as in the block of code above
etc.

How to use logical conditions only for some dimensions in multidimensional arrays in MATLAB

Let us have a 4D matrix (tensor), output:
[X,Y,Z] = ndgrid(-50:55,-55:60,-50:60);
a = 1:4;
output = zeros([size(X),length(a)]);
Next, we determine the area inside the ellipsoid:
position = [0,0,0];
radius = [10,20,10];
test_func = #(X,Y,Z) ((X-position(1))/radius(1)).^2 ...
+ ((Y-position(2))/radius(2)).^2 ...
+ ((Z-position(3))/radius(3)).^2 <= 1;
condition = test_func(X,Y,Z);
I need to fill the matrix output inside the ellipsoid for the first 3 dimensions. But for the fourth dimension I need to fill a. I need to do something like this:
output(condition,:) = a;
But it does not work. How to do it? Any ideas please!
If I understand your question correctly, you have a 4D matrix where each temporal blob of pixels in 3D for each 4D slice is filled with a number... from 1 up to 4 where each number tells you which slice you're in.
You can cleverly use bsxfun and permute to help you accomplish this task:
output = bsxfun(#times, double(condition), permute(a, [1 4 3 2]));
This takes a bit of imagination to imagine how this works but it's quite simple. condition is a 3D array of logical values where each location in this 3D space is either 0 if it doesn't or 1 if it does belong to a point inside an ellipsoid. a is a row vector from 1 through 4 or however many elements you want this to end with. Let's call this N to be more general.
permute(a, [1 4 3 2]) shuffles the dimensions such that we create a 4D vector where we have 1 row, 1 column and 1 slice but we have 4 elements going into the fourth dimension.
By using bsxfun in this regard, it performs automatic broadcasting on two inputs where each dimension in the output array will match whichever of the two inputs had the largest value. The condition is that for each dimension independently, they should both match or one of them is a singleton dimension (i.e. 1).
Therefore for your particular example, condition will be 106 x 116 x 111 while the output of the permute operation will be 1 x 1 x 1 x N. condition is also technically 106 x 116 x 111 x 1 and using bsxfun, we would thus get an output array of size 106 x 116 x 111 x N. Performing the element-wise #times operation, the permuted vector a will thus broadcast itself over all dimensions where each 3D slice i will contain the value of i. The condition matrix will then duplicate itself over the fourth dimension so we have N copies of the condition matrix, and performing the element-wise multiply thus completes what you need. This is doable as the logical mask you created contains only 0s and 1s. By multiplying element-wise with this mask, only the values that are 1 will register a change. Specifically, if you multiply the values at these locations by any non-zero value, they will change to these non-zero values. Using this logic, you'd want to make these values a. It is important to note that I had to cast condition to double as bsxfun only allows two inputs of the same class / data type to be used.
To visually see that this is correct, I'll show scatter plots of each blob where the colour of each blob would denote what label in a it belongs to:
close all;
N = 4;
clrs = 'rgbm';
figure;
for ii = 1 : N
blob = output(:,:,:,ii);
subplot(2,2,ii);
plot3(X(blob == ii), Y(blob == ii), Z(blob == ii), [clrs(ii) '.']);
end
We get:
Notice that the spatial extent of each ellipsoid is the same but what is different are the colours assigned to each blob. I've made it such that the values for the first blob, or those assigned to a = 1 are red, those that are assigned to a = 2 are assigned to green, a = 3 to blue and finally a = 4 to magenta.
If you absolutely want to be sure that the coordinates of each blob are equal across all blobs, you can use find in each 3D blob individually and ensure that the non-zero indices are all equal:
inds = arrayfun(#(x) find(output(:,:,:,x)), a, 'un', 0);
all_equal = isequal(inds{:});
The code finds in each blob the column major indices of all non-zero locations in 3D. To know whether or not we got it right, each 3D blob should all contain the same non-zero column major indices. The arrayfun call goes through each 3D blob and returns a cell array where each cell element is the column major indices for a particular blob. We then pipe this into isequal to ensure that all of these column major indices arrays are equal. We get:
>> all_equal
all_equal =
1

Matlab - Euclidian distance between two matrix

I have declared 2 matrixes like this:
a = [ 1 2;
11 12];
[m, n] = size(a);
b = a(2,:);
dist( b , a ); % the first column is not interesting
This works, I get a vector
[ 10.0499 9.0000 ]
However if I want to add a column or a line to my matrix a:
a = [ 1 2 3 ;
11 12 13];
then apply the same algorithm, than above, ignoring or not the first column, I get this error:
Error using -
Matrix dimensions must agree
I have no idea why it does not work, can someone explain to me please?
Actually I don't even know how to retrieve the way this euclidian distance is computed, I failed at trying to retrieve those values [ 10.0499 9.0000 ] by hand.
The Matlab mathworks manual says he algorithm used is the following:
d = sum((x-y).^2).^0.5
Any help
It does not work because the dist function when called with two arguments works like this:
Z = dist(W,P) takes an SxR weight matrix and RxQ input matrix and
returns the SxQ matrix of distances between W's rows and P's columns.
dist(P',P) returns the same result as dist(P).
That is, if you do this:
a = [ 1 2 3 ;
11 12 13]
b = a(2,:) % Then b = [11 12 13]
...and call:
dist(b, a)
It will try to compute the distance between b's rows (in this case, only a row with three numbers, that is, a 3D point) and a's columns (each column has two numbers, that is, a 2D point). Measuring a distance between them makes no sense.
The reason it worked on your first example was because the matrix was square (2x2). Therefore, you're computing distances between a row (2D) to the other columns (also 2D).
A distance by definition is a single number, not a vector. The fact that you've getting a vector for matrices of the same size already indicates that something is wrong. In particular, it gives you distance between each of the corresponding column vectors to each other. So it doesn't work when your matrices are of different sizes. A distance between matrices is not defined in any one particular way. I don't know of a notion of Euclidean distance between two matrices.

Finding the common segments of two noncontinuous vectors

I'm looking for a quick and elegant manner to solve this problem:
I have two noncontinuous line, like the black ones in this image:
For each, I have two vectors - one defining the starting points of each segment and the other defining the ending points.
I am looking for a MATLAB script that will give me the start and end points for the blue line, which is the intersection of the two lines.
I could, of course, create two vectors, each containing all the elements in the black lines, and then use "intersect". However, since the numbers here are in billions, the size of these vectors will be huge and the intersection will take long.
Any ideas?
Nice question!
This is a solution without loops for combining n discontinuous lines (n is 2 in the original post).
Consider n discontinuous lines, each defined by its start and stop points. Consider also an arbitrary test point P. Let S denote the solution, that is, a discontinuous line defined as the intersection of all the input lines. The key idea is: P is in S if and only if the number of start points to the left of P minus the number of stop points to the left of P equals n (considering all points from all lines).
This idea can be applied compactly with vectorized operations:
start = {[1 11 21], [2 10 15 24]}; %// start points
stop = {[3 14 25], [3 12 18 27]}; %// stop points
%// start and stop are cell arrays containing n vectors, with n arbitrary
n = numel(start);
start_cat = horzcat(start{:}); %// concat all start points
stop_cat = horzcat(stop{:}); %// concat all stop points
m = [ start_cat stop_cat; ones(1,numel(start_cat)) -ones(1,numel(stop_cat)) ].';
%'// column 1 contains all start and stop points.
%// column 2 indicates if each point is a start or a stop point
m = sortrows(m,1); %// sort all start and stop points (column 1),
%// keeping track of whether each point is a start or a stop point (column 2)
ind = find(cumsum(m(:,2))==n); %// test the indicated condition
result_start = m(ind,1).'; %'// start points of the solution
result_stop = m(ind+1,1).'; %'// stop points of the solution
With the above data, the result is
result_start =
2 11 24
result_stop =
3 12 25
Your idea of discretizising is fine, but instead of using fixed step sizes I reduced it to the relevant points. The start or endpoint of the union are start or end point from one of the inputs.
%first input
v{1}=[1,3,5,7;2,4,6,8];
%second input
v{2}=[2.5,6.5;4,8];
%solution can only contain these values:
relevantPoints=union(v{1}(:),v{2}(:));
%logical matrix: row i column j is true if input i contains segment j
%numel(relevantPoints) Points = numel(relevantPoints)-1 Segments
bn=false(size(v,2),numel(relevantPoints)-1);
for vector=1:numel(v)
c=v{vector};
for segment=1:size(c,2)
thissegment=c(:,segment);
%set all segments of bn to true, which are covered by the input segment
bn(vector,find(relevantPoints==thissegment(1)):find(relevantPoints==thissegment(2))-1)=true;
end
end
%finally the logic we want to apply
resultingSegments=and(bn(1,:),bn(2,:));
seg=[relevantPoints(find(resultingSegments))';relevantPoints(find(resultingSegments)+1)'];

Matlab - relational matricies?

I have a vector of coordinates called x. I want to get the element(s) with the min y coordinate:
a = find(x(:,2)==min(x(:,2))); % Contains indices
This returns the indexes of the elements with the smallest y coordinates. I say element*s* because sometimes this would return more than 1 value (e.g. (10,2) and (24,2) both have 2 as y coordinate and if 2 is the min y coordinate...).
Anyway, my next step is to sort (ascending) the elements with the min y coordinates according to their x coordinates. First I do:
b = sort(x(a,1));
The above operation might rearrange the elements with min y coordinates so I want to apply this rearrangement to a as well. So I do:
[v i] = ismember(b, x(:, 1));
Unfortunately, if there are elements with the same x value but different y values and one of these elements turns out to be a member of a (i.e. b) then the above matrix chooses it. For example if (10,2) and (24,2) are the elements with smallest y coordinates and there is a 3rd element (24, 13) then it will mess up the above operation. Is there a better way? I wrote my script using loops and everything was fine but in line with Matlab's methodology I rewrote it and I fear my unfamiliarity with matlab is causing this error.
Sorry, I might have misunderstood your question but lemme rephrase what I think you want here:
You have a set of 2D coordinates:
x = [24,2; 10,2; 24,13];
You want the pairs of coordinates to stay together (24,2) (10,2) and (24,13). And you want to find the pairs of coordinates that has the min y-coordinate and if there are multiples, then you want to sort them by x-coordinate. And you want the row indices of what those coordinate pairs were in the original matrix x. So in other words, you want a final answer of:
v = [10,2; 24,2];
i = [2,1];
If I understood correctly, then this is how you can do it:
(Note: I changed x to have one more pair (40,13) to illustrate the difference between idx(i) and i)
>> x = [40,13; 24,2; 10,2; 24,13];
>> idx = find(x(:,2)==min(x(:,2))) %Same as what you've done before.
idx =
2
3
>> [v,i] = sortrows(x(idx,:)) %Use sortrows to sort by x-coord while preserving pairings
v =
10 2
24 2
i = % The indices in x(idx,:)
2
1
>> idx(i) %The row indices in the original matrix x
ans =
3
2
And finally, if this is not what you wanted, can you indicate what you think your answer [v,i] should be in the example you gave?