Search code examples
pythonimagevideofiltermedian

Faster way to create a temporal median filter for a video


I am trying to create a median filter for a video. The goal is to create an image for every 5 frames whose pixel values correspond to the median value of the pixel for the 5 frames.

I can do so using several for cycles but I wanted a faster/simpler way to accomplish the same result. Any help?

UPDATE:

I tried to use the np.median function by defining the axis I want the median to be applied. When I tested it out with smaller arrays it worked just fine but when I transitioned to the images it did not work.

w = 5  # window
n = int(len(data)/w)  # new number of frames
fdata = np.zeros([n, len(data[0]), len(data[0][0])])

for i in range(0, n):
   it_data = data[ i*5 : 5*i+5 ]
   fdata[i] = np.median(it_data, axis=0)

The error I receive is on the last line:

>>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Solution

  • Here you have :), a, b and c are frames (let's say grayscale), you must stack them as if they were the RGB components (try the same with 5, it will work) and then apply the median to the outer axis (see question and this other).

    import numpy as np
    import random
    
    a = np.array(
        [[ random.randint(0,10) for i in range(3) ],
         [ random.randint(0,10) for i in range(3) ]])
    
    b = np.array(
        [[ random.randint(0,10) for i in range(3) ],
         [ random.randint(0,10) for i in range(3) ]])
    
    c = np.array(
        [[ random.randint(0,10) for i in range(3) ],
         [ random.randint(0,10) for i in range(3) ]])
    
    print(a)
    print(b)
    print(c)
    print('\n')
    
    # batch = a[..., np.newaxis]
    batch = np.stack((a,b,c))
    
    print(batch.shape)
    print(batch)
    
    print('\n')
    
    batch = np.median(batch, axis=0)
    
    print(batch.shape)
    print(batch)
    
    print('\n...Test...')
    
    print(
        np.median(
            (a[0,0],b[0,0],c[0,0])
        )
    )
    

    Check also