MATLAB: Order of data extracted with logical indexing

image processinglogical indexing

Hi all,
I've been trying to extract an image from a stack of source images, where I want to use a logical index mask in 4D. The four dimensions of my source image stack are width, height, rgb, and number of source images. For each point in the width*height plane there is one source image of which all three rgb values are taken, so they have a value of 1 in the mask while everything else at this width*height position gets a 0 in the mask.
The problem is that if I extract the pixel values that I want from my stack of source images like this
resultImage = imageStack(logicalMask);
I end up with a long vector of values, not an array with 3 dimensions width, height and rgb (the fourth is flattened by the extraction). This makes sense because MATLAB can't know that I want to end up with an image. I know I have to reshape the resultImage vector into the correct dimensions but the order of values is messed up. How can I control the logical indexing process so I know which value ends up where?
Right now I assume the extraction goes through the width dimension first with height, rgb and n set to 1, which would mean I'd first get a line of red values from pixels in the first image in the stack. In the end, I can't reshape a result vector like this because the original pixel locations are not recoverable from the result vector. I'd need the indexing process to go through rgb of each source image at all locations, so I get a vector of rgbrgbrgbrgb where each rgb triple is still at the right position.
How can I achieve that?

Best Answer

Ok while writing this I answered my own question, as it happens sometimes.. The solution is to reorder the dimensions of image stack and logical mask before the logical indexing, then do the indexing operation, then reshaping into the correct measurements and permuting back. Looks like this:
permute(imageStack, [3,4,1,2]);
permute(logicalMask,[3,4,1,2]);
% now both arrays' dimensions are ordered rgb, n, width, height
result = imageStack(logicalMask);
% this has the form of a vector with 3*width*height elements
resultReshaped = reshape(result,[3,width,height]);
% this has the correct measurements, but not in the right image format x*y*3
resultPermuted = permute(resultReshaped,[2,3,1]);
% this is the final image with correctly ordered dimensions