Reputation: 1485
I have a 3D matrix with size is 120x256x256
where 120 is number of slices and 256x256 is size of each image slice. I want to extract the 3D matrix into 2D image (256x256). How to get the data of 3D matrix. I try to with matlab code:
Img_3D=zeros(120,256,256);
for numSlice=1:120
Img2D=Img_3D(numSlice,:,:);
end
But it does not work. It return a matrix that size is 1x256x256
, instead of 256x256
matrix. How to fix my problem. Thank you so much
Upvotes: 1
Views: 103
Reputation: 4311
You can certainly solve this problem using squeeze(), it is the most easy way of removing singleton dimensions. squeeze() detects the singleton dimension(s) and removes it (them) by calling reshape() accordingly. If speed is an issue, you could speed it up by using reshape() yourself, saving some computations:
Img_3D=reshape(1:120*256*256, [120,256,256]);
t0 = tic;
for j = 1:100
for numSlice = 120:-1:1 %// backwards for preallocation
slices_squeeze{numSlice } = squeeze( Img_3D(numSlice,:,:) );
end
end
t_squeeze = toc(t0);
t0 = tic;
for j = 1:100
for numSlice = 120:-1:1 %// backwards for preallocation
slices_reshape{numSlice } = reshape(Img_3D(numSlice,:,:),[256, 256]);
end
end
t_reshape = toc(t0);
fprintf('squeeze-solution: %5.3f seconds\n', t_squeeze);
fprintf('reshape-solution: %5.3f seconds\n', t_reshape);
The speedup is not too much though...
squeeze-solution: 5.654 seconds
reshape-solution: 4.790 seconds
Best, Nras.
Upvotes: 1
Reputation: 25232
Just squeeze
your resulting Matrix to get what you want.
Img_3D=zeros(120,256,256);
for numSlice = 120:-1:1 %// backwards for preallocation
slices{numSlice } = squeeze( Img_3D(numSlice,:,:) );
end
basically the same can be achieved using permute
as you suggested
for numSlice = 120:-1:1 %// backwards for preallocation
slices{numSlice } = permute( Img_3D(numSlice,:,:),[2 3 1] );
end
performance-wise equal.
And after some timings it doesn't seem to matter if you permute
in advance or not:
Img_3D = permute(Img_3D,[2 3 1]);
for numSlice = 120:-1:1 %// backwards for preallocation
slices{numSlice } = Img_3D(numSlice,:,:);
end
Upvotes: 2