1

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?

Shai
  • 111,146
  • 38
  • 238
  • 371
Ozg
  • 391
  • 2
  • 7
  • 20

1 Answers1

4

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.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • It gives me this error: "Error using median (line 28) First input must be single or double." – Ozg May 22 '13 at 13:36
  • 1
    @ozg, then cast to `single`: `background = uint8( median( single( video ), 4 ) );` – Shai May 22 '13 at 13:40
  • Okay.I really couldn't guess it can be calculated in a one line,thanks for help. – Ozg May 22 '13 at 13:43
  • 1
    @ozg - triple nested loop in Matlab is a bad thing... you MUST have extremely good reason to do so. – Shai May 22 '13 at 13:45
  • @ozg what version of Matlab are you using? From [doc of `median`](http://www.mathworks.com/help/matlab/ref/median.html) it seems like it should support `int`s as well... – Shai May 22 '13 at 13:51
  • @Shai - I use the same line of code in one of my applications and I'm curious: is there any way this process could be speeded up even more? – Alex B. May 27 '14 at 20:22
  • @AlexB. computing `median` is quite heavey: you need to sort (at least partially) so I don't suppose you can compute `median` much faster... You may consider using `mean` instead, should be a lot faster... – Shai May 28 '14 at 06:05
  • @Shai - Thanks, I thought so! However I did find one possibility: using a faster implementation of it, written in c++, through mex (http://www.mathworks.com/matlabcentral/fileexchange/29453-nth-element). But I haven't tried it yet. – Alex B. May 28 '14 at 11:16