Creating an image of first non-zero values in a 3d matrix

2 views (last 30 days)
Hi everyone,
I have a 2300x2475x109 datacube/ 3d matrix (109 images with 2300x2475 pixels). All images are binary (0 and 1). Now I want to create an image where each pixel contains the index of the first non-zero value. So for example, if the pixel 500x1500 is always zero until to the 12th image, the value in the result image should be 12. I could write a code, where this works for a single pixel location:
pixval = im_datacube(500,1500,:);
pixval = squeeze(pixval);
firstNonZero = find(pixval~=0, 1, 'first');
But now I want to make that for each pixel location and merge it all together into a single image. I tried to do it with loops, but i failed so far. Hope you can help me, thanks in advance.

Accepted Answer

Bruno Luong
Bruno Luong on 20 Dec 2018
Edited: Bruno Luong on 20 Dec 2018
[maxval,firstNonZero] = max(im_datacube ~= 0, [], 3);
firstNonZero(~maxval) = NaN; % pixel where 1 is not found along the 3rd dim
firstNonZero
  4 Comments
Bruno Luong
Bruno Luong on 21 Dec 2018
Edited: Bruno Luong on 21 Dec 2018
Flip the 3rd dimension of the input array; find the first indexes on flipped arrays using MAX as above, then reverse the indexes found.
Simon Hagmayer
Simon Hagmayer on 21 Dec 2018
A very elegant and simple solution, thank you so much.

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 20 Dec 2018
One way:
inverted_image = ~im_datacube;
max(cumsum(inverted_image, 3) .* cumprod(inverted_image, 3), [], 3)

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!