nbsrujan
nbsrujan

Reputation: 1189

issue with sub2ind and matrix of matrix in matlab with images

I here by post the code why I came across while exploring one technique.

   Y = repmat((1:m)', [1 n]);
   X = repmat(1:n, [m 1]) - labels_left;
   X(X<1) = 1;
   indices = sub2ind([m,n],Y,X);

  final_labels = labels_left;
  final_labels(abs(labels_left - labels_right(indices))>=1) = -1;

In above code labels left is single channel image.[m n] is the size of that image. I want to know how this sub2ind works in above code.And Iam also facing problem in the last statement which contains

  labels_right(indices)

what the above expression evaluates to.Here labels right is also an image

Upvotes: 0

Views: 558

Answers (1)

Amro
Amro

Reputation: 124563

Maybe a smaller example could help understand:

%# image matrix
M = rand(4,3)
[m n] = size(M)

%# meshgrid, and convert to linear indices
[X,Y] = meshgrid(1:n,1:m)
indices = sub2ind([m,n],Y,X)

%# extract those elements
M(indices)

The matrix M:

>> M
M =
      0.95717      0.42176      0.65574
      0.48538      0.91574     0.035712
      0.80028      0.79221      0.84913
      0.14189      0.95949      0.93399

the grid of (x,y) coordinates of all points:

>> X,Y
X =
     1     2     3
     1     2     3
     1     2     3
     1     2     3
Y =
     1     1     1
     2     2     2
     3     3     3
     4     4     4

converted to linear indices:

>> indices
indices =
     1     5     9
     2     6    10
     3     7    11
     4     8    12

then we index into the matrix using those indices.

>> M(indices)
ans =
      0.95717      0.42176      0.65574
      0.48538      0.91574     0.035712
      0.80028      0.79221      0.84913
      0.14189      0.95949      0.93399

Note that: M(indices(i,j)) = M(Y(i,j)),X(i,j)).

Upvotes: 1

Related Questions