简体   繁体   中英

Sample 1D vectors from 3D array using a vector of points

I have an channel image and I have a 100x2 matrix of points (in my case n is 20 but perhaps it is more clear to think of this as a 3 channel image). I need to sample the image at each point and get an nx100 array of these image points. I know how to do this with a for loop:

for j = 1:100
        samples(j,:) = image(points(j,1),points(j,2),:);
end

How would I vectorize this? I have tried

samples = image(points);

but this gives 200 samples of 20 channels. And if I try

samples = image(points,:);

this gives me 200 samples of 4800 channels. Even

samples = image(points(:,1),points(:,2));

gives me 100 x 100 samples of 20 (one for each possible combination of x in X and y in Y)

A concise way to do this would be to reshape your image so that you force your image that was [nRows, nCols, nChannels] to be [nRows*nCols, nChannels] . Then you can convert your points array into a linear index (using sub2ind ) which will correspond to the new "combined" row index. Then to grab all channels, you can simply use the colon operator ( : ) for the second dimension which now represents the channels.

% Determine the new row index that will correspond to each point after we reshape it
sz = size(image);
inds = sub2ind(sz([1, 2]), points(:,2), points(:,1));

% Do the reshaping (i.e. flatten the first two dimensions)
reshaped_image = reshape(image, [], size(image, 3));

% Grab the pixels (rows) that we care about for all channels
newimage = reshaped_image(inds, :);

size(newimage)

    100    20

Now you have the image sampled at the points you wanted for all channels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM