Indexing 3D arrays using vectors of indexes

4 次查看(过去 30 天)
I want to get RGB values of an image (utf-8 160x120x3 matrix). I know which pixels I want, I nx1 vectors, xi and yi, which are indexes for each of these pixels of interest. I would like the output in nx3 format. I've had this problem in the past where I'd like to get data from a 3D matrix using 2D indecies. This works in 2D where you can grab several rows at once using the colon (xi,:), but not in 3D. I would like to extract the "hyper-row" so to speak.
What is the fastest way to do this? I have a working solution using impixel that is way too slow for this application. I could create a 3D logical matrix, but I am only sampling a few pixels relative to the total number, and sparse matrices don't work for this applicaiton. I usually tend to vectorize rather than use for loops, but it doesn't seem like there is a great alternative.
lab_image = randi(255,160,120,3); % sample image
xi = [1 2 3];
yi = [1 2 3];
impixel(lab_image,xi,yi) % correct answer, but too slow.
lab_image(xi, yi, :) % wrong (but it works on 2D matrices?)
test2d = randi(255,10,10);
test2d(xi,:) % see how it grabs the rows associated with xi?

采纳的回答

Rik
Rik 2022-10-15
The problem with indexing in Matlab is that it will grab every pair of indices, which is not always what you want.
The easiest solution is to convert your indices to linear indices with sub2ind. I would suggest doing each color channel separately and concatenating the result with cat(3,R,G,B).

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by