Matlab indexes two dimensions with linear measures, keeping the third dimension constant

Let's say I have two-dimensional linear indicators:

linInd = sub2ind(imSize,rowPnts,colPnts);

And I have a three-dimensional color image I:

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

Is there a way so that I can index something like this to get all coordinates in a 2D plane, but for each image channel? That is, can I get all the information about the color channels for each pixel with one command using the linear pointers that are indicated for 2D?

I(linInd,:)

So, I do not need to divide the image into 3 parts, and then reassemble?

Thanks.

+4
source share
3 answers

broadcast 2D 3D, bsxfun, , :

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

%// ---------------- 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);

>> 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
+4

, .

I2=reshape(I,[],3)
I2(ind,:)
+2

Do you need this dimension to be considered third? If not, you can permutemove the dimension to the 1st position in the array, and then use it arr(i3d, linInd).

+2
source

Source: https://habr.com/ru/post/1621540/


All Articles