Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab indexing two dimensions with linear indicies while keeping a third dimension constant

Say I have 2D linear indicies:

linInd = sub2ind(imSize,rowPnts,colPnts);

And I have a 3D color image I:

I = rand(64,64,3)*255

Is there any way that I can index something like this in order to get all coordinates in the 2D plane but for each channel of the image? That is, can I get all of the color channel information for each pixel with one command using linear indicies that are specified for 2D?

I(linInd,:)

So I don't have to split up the image into 3 parts and then reassemble again?

Thanks.

like image 380
Termnus Avatar asked Feb 08 '23 05:02

Termnus


1 Answers

You can broadcast the 2D linear indices to a 3D case using bsxfun without messing with the input array, like so -

[m,n,r] = size(I);
out = I(bsxfun(@plus,linInd,(m*n*(0:r-1))'))

Sample setup

%// ---------------- 2D Case ---------------------
im = randi(9,10,10);
imSize = size(im);

rowPnts = [3,6,8,4];
colPnts = [6,3,8,5];
linInd = sub2ind(imSize,rowPnts,colPnts);

%// ---------------- 3D Case ---------------------
I = randi(9,10,10,4);

%// BSXFUN solution
[m,n,r] = size(I);
out = I(bsxfun(@plus,linInd,(m*n*(0:r-1))')); %//'

%// Tedious work of splitting
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
Ia = I(:,:,4);

Output

>> Ir(linInd)
ans =
     8     9     1     6
>> Ig(linInd)
ans =
     1     5     9     8
>> Ib(linInd)
ans =
     8     5     3     8
>> Ia(linInd)
ans =
     8     8     3     3
>> out
out =
     8     9     1     6
     1     5     9     8
     8     5     3     8
     8     8     3     3
like image 169
Divakar Avatar answered Feb 16 '23 01:02

Divakar