Search code examples
matlabvideoimage-processingframemedian

How to calculate median of frames efficient in Matlab?


I'm using median function (http://www.mathworks.com/help/matlab/ref/median.html) in Matlab in order to calculate average value of each pixels from each frame in a video. Here is my code:

[a,b,c,d] = size(video);  //take video's dimensions
background=zeros(a,b,c);  //create a matrix for background image
tempR=zeros(1,d);         //create template matrices for each channel
tempG=zeros(1,d);
tempB=zeros(1,d);
for i=1:a    % for each pixel
    for j=1:b
        for(k=1:d)       //for each frame
            tempR(1,k) = video(i,j,1,k); // r channel
            tempG(1,k) = video(i,j,2,k); // g channel
            tempB(1,k) = video(i,j,3,k); // b channel
        end
        background(i,j,1) = median(tempR);  //calculate median value for each channel
        background(i,j,2) = median(tempG);
        background(i,j,3) = median(tempB);
    end
end

My question is: Is there a more efficient way to do this? As shown this way is not efficient and for bigger videos it is working so slow. Using for loops for each frame,channel and pixel makes cost. Can i calculate median value in a more efficient way?


Solution

  • How about:

    background = median( video, 4 ); % median along fourth dim
    

    PS,
    It is best not to use i and j as variable names in Matlab.