MATLAB: How to detect empty rows and columns from 3-D matrix and crop them

3-d matrixlogical indexingMATLABvideo processing

I have a 3-D matrix as a video. It contains empty (0) zero values along the tree dimentions.
The matrix is represented as a video. So I need to:
  • if the row along the frames is empty (==0), I want to crop it.
  • if the column along the frames is empty (==0), I want to crop it
I have an example 3-D dimention but I need a general method.
I have tried to write something but there is something wrong.
Please Help.
%% define the video (3-D matrix)
Frames = [0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0;0 0 0 0 0];
Frames(:,:,2 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,3 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,4 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,5 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,6 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,7 ) = [0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0;0 0 0 0 0];
Frames(:,:,8 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,9 ) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
Frames(:,:,10) = [0 0 0 0 0;0 0 90 0 0; 0 0 90 0 0; 90 90 90 0 0;0 0 0 0 0];
%% define some varibles
%% n & m are zeros counters
%% x,y,z are lengths along the three dimentions
n=0;
m=0;
x=length(Frames(:,1,1));
y=length(Frames(1,:,1));
z=length(Frames(1,1,:));
%% if the row along the frames is empty (==0),crop it.
%% r for row
% %% c for columns

% %% f for frames

for c=1:y
for r=1:x
for f=1:z
if Frames(r,c,f)==0 %detect

m=m+1;
end
end
if m==25
Frames(:,c,:) = []; %crop

end
end
end
%% %% if the column along the frames is empty (==0),crop it.
%% r for row
% %% c for columns
% %% f for frames
for r=1:x
for c=1:y
for f=1:z
if Frames(r,c,f)==0 %detect
n=n+1;
end
end
if m==25
Frames(r,:,:) = []; %crop
end
end
end

Best Answer

tmp=any(Frames,3);
I = any(tmp,2);
J= any(tmp,1);
Frames=Frames(I,J,:);