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

1 回表示 (過去 30 日間)
Simon Hagmayer
Simon Hagmayer 2018 年 12 月 20 日
コメント済み: Simon Hagmayer 2018 年 12 月 21 日
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.

採用された回答

Bruno Luong
Bruno Luong 2018 年 12 月 20 日
編集済み: Bruno Luong 2018 年 12 月 20 日
[maxval,firstNonZero] = max(im_datacube ~= 0, [], 3);
firstNonZero(~maxval) = NaN; % pixel where 1 is not found along the 3rd dim
firstNonZero
  4 件のコメント
Bruno Luong
Bruno Luong 2018 年 12 月 21 日
編集済み: Bruno Luong 2018 年 12 月 21 日
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 2018 年 12 月 21 日
A very elegant and simple solution, thank you so much.

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2018 年 12 月 20 日
One way:
inverted_image = ~im_datacube;
max(cumsum(inverted_image, 3) .* cumprod(inverted_image, 3), [], 3)

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by