MATLAB: Vectorizing nested for loops

for loopframesnested loopvectorizingvideo

Hi,
I am having a few issuing trying to vectorise multiple nested for loops. This application is video and i am looping through each pixel in each line of each frame of all the frames.
for l=1:nFrames
currentVFrame = read(liveVid, l); % Read in next frame
alphaVFrame = zeros(vidHeight, vidWidth, 3, 'uint8'); % create and then reset to 0
for k = 1:3
for i=1:vidHeight
for j=1:vidWidth
if(currentVFrame(i,j,k) == 254) % 254 = green screen
alphaVFrame(i,j,k) = 000; % Set to transparent instead
else
alphaVFrame(i,j,k) = currentVFrame(i,j, k); % Keep original file info
end
end
end
end
%imshow(alphaVFrame); % Show a preview of trhe current frame
mov(l).cdata = im2uint8(alphaVFrame); % Write the frame to our mov structure (int)
writeVideo(OutputVideo, alphaVFrame); % write the frame to the video file (ext)
end
I have tried to vectorise it following the example written on this post:
[i,j] = ndgrid(1:vidHeight*vidWidth);
r = reshape(a(i)+a(j), [nFrames, 3, VidHeight, VidWidth]);
But I get an error:
Maximum variable size allowed by the program is exceeded.
Error in ndgrid (line 63)
varargout{1} = x(:,ones(size(y)));
Can anyone point me in the right direction? I'm using Matlab R2013a.

Best Answer

  • The post you linked does not apply to what you're doing. The simplest thing is to use matrix operations on your frames instead of your three inner loops:
    for frame = 1:nframes %why use a meaningless letter instead of a meaningful name?
    currentVFrame = read(liveVid, frame);
    alphaVFrame = currentVFrame; %copy frame to output
    alphaVFrame(alphaVFrame == 254) = 0; %and replace green screen with transparent?
    %imshow(alphaVFrame); % Show a preview of trhe current frame
    mov(frame).cdata = im2uint8(alphaVFrame); % Write the frame to our mov structure (int)
    writeVideo(OutputVideo, alphaVFrame); % write the frame to the video file (ext)
    end
    I'm puzzled by your comment though %254 = green screen, this is only true on the green channel, ( k==2) but you're doing your test on all three colour channels.