Cut region of interest images from 3D stack with known indices and without for loop

1 回表示 (過去 30 日間)
Hi! I am having trouble cutting region of interest from a 3D stack.
A small example, I have a 3x3x2 array of:
array = [1,2,3;4,5,6;7,8,9];
array(:,:,2) = [1,2,3;4,5,6;7,8,9];
mini image indices:
left = [1,2]
right = [2,3]
top = [1,2]
bottom = [2,3]
create mini images:
miniImages = array(top:bottom,left:right,:)
result:
miniImages(:,:,1) = [1,2;4,5]
miniImages(:,:,2) = [1,2;4,5]
However, I want the result to be:
miniImages(:,:,1) = [1,2;4,5]
miniImages(:,:,2) = [5,6;8,9]
It seems that it only uses the first indices in variables left, right, top, bottom to create all mini images.
Anyone know how to solve this? Currently I use a for loop over the indices, but I want to make it faster.
Thanks!
  2 件のコメント
Matt J
Matt J 2023 年 3 月 2 日
miniImages(:,:,2) = [5,6;7,8]
Don't you mean [5 6;8;9] ?
Kevin Jansen
Kevin Jansen 2023 年 3 月 2 日
Yes! That was a mistake, I will try to edit it.

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

採用された回答

Matt J
Matt J 2023 年 3 月 2 日
編集済み: Matt J 2023 年 3 月 2 日
I doubt anything will be faster than a loop, but you can try this:
array = [1,2,3;4,5,6;7,8,9];
array(:,:,2) = [1,2,3;4,5,6;7,8,9]
array =
array(:,:,1) = 1 2 3 4 5 6 7 8 9 array(:,:,2) = 1 2 3 4 5 6 7 8 9
left = [1,2];
top = [1,2];
bottom = [2,3];
right = [2,3];
args=cellfun(@(z)reshape(z,1,1,[]) , {left,top,bottom,right} ,'un' ,0);
[L,T,B,R]=deal(args{:});
[m,n,p]=size(array);
[I,J]=ndgrid(1:m,1:n);
lidx=T<=I & I<=B & L<=J & J<=R;
miniImages=reshape( array(lidx) ,B(1)-T(1)+1,R(1)-L(1)+1,[])
miniImages =
miniImages(:,:,1) = 1 2 4 5 miniImages(:,:,2) = 5 6 8 9
  1 件のコメント
Kevin Jansen
Kevin Jansen 2023 年 3 月 2 日
Hey, awesome it worked! Much more difficult than I thought it would be. My code with larger arrays ran 380x faster without the for loop. Thank you so much!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeImages についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by