I have code which selects 50 random frames from a video and then finds the median of them, to make a background image.
This works with many of my videos, however it does not work for one of them and I am not sure why. All videos are in .avi format.
The problem video results in an error, "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()". The reason for this error (I think) is that when setting the frame ID to read the 50 random frames, I get a few which are NoneType objects, which does not happen for my other videos. This means I have problems later when finding the median.
Does anyone know the reason for this?
edit: further information, the nonetype frames are the ones with indexes quite high eg any with an index 800 and up. But according to cv2 there should be 1019 frames in total, so not sure why this is a problem
def get_background(file_path):
cap = cv2.VideoCapture(file_path)
# we will randomly select 50 frames for the calculating the median
frame_indices = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) * np.random.uniform(size=50)
# we will store the frames in array
frames = []
for idx in frame_indices:
# set the frame id to read that particular frame
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
frames.append(frame)
# calculate the median
median_frame = np.median(frames, axis=0).astype(np.uint8)
return median_frame