Remove moving objects with OpenCV calculating the mode using Python

448 Views Asked by At

this code works great in order to substract moving objects. The input is an mp4 video and the output is the background without any moving object. The problem is, this code is calculating the MEDIAN of every pixel. Is there any way to calculate the mode?

import numpy as np
import cv2 as cv
file_path = 'videoprueba2.mp4' ## THIS IS THE INPUT VIDEO
video = cv.VideoCapture(file_path) 
FOI = video.get(cv.CAP_PROP_FRAME_COUNT) * np.random.uniform(size=30)
frames = []
for frameOI in FOI:
    video.set(cv.CAP_PROP_POS_FRAMES, frameOI)
    ret, frame = video.read()
    frames.append(frame)
result2 = np.median(frames, axis=0).astype(dtype=np.uint8) #HERE IT CALCULATES THE MEDIAN OF EVERY PIXEL IN THE FRAME
cv.imwrite('prueba3Metodo2.png',result2) #THIS IS THE FINAL PICTURE
1

There are 1 best solutions below

1
u1234x1234 On

If your data contains only non-negative int numbers use np.bincount like this:

result2 = np.apply_along_axis(lambda x: np.bincount(x).argmax(), axis=0, arr=frames)

Also you can use scipy.stats.mode as it allows negative and float values but it is much slower. For example for a video with resolution 1280x720 and 30 frames:

scipy.stats.mode took 30.892 seconds
np.bincount took 5.950 seconds