Why OpenCV VideoWriter is producing videos in which one image is flashing out of sequence repeatedly?

Viewed 25

I am creating a video from images using OpenCV VideoWriter but the output result has one image flashing repeatedly out of sequence.

I am not getting why is this happening.

Here is my code:

import cv2
import os
import numpy as np

image_folder = 'C:\\Users\\OneDrive\\Desktop\\new\\folder'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
video = cv2.VideoWriter(video_name, fourcc,30,(width,height))



for image in images:
    video.write(np.uint8(cv2.imread(os.path.join(image_folder, image))))


cv2.destroyAllWindows()
video.release()

I have also tried varying fps and codec, but the results do not vary.

Here is the original video: https://vimeo.com/743523133 and here is the video created by OpenCV: https://vimeo.com/743525698

Images in the folder are in the correct order and the folder does not contain that flashing image repeatedly.

Please help me. Thanks :)

1 Answers

You haven't sorted the images.

os.listdir makes no guarantees about order. You are getting them in some nonspecific order.

You should sort them. Make sure your images contain a counter with leading zeros (001, 002, 003, ...), so that lexical sorting gives the correct result. If you don't, you'll get an order like 1, 10, 11, ..., 19, 2, 20, 21, ....

If os.listdir did happen to sort the list before returning it, then the names you gave those images are unsuitable for a simple lexical sort. Either fix your file names or go to the trouble of parsing the numbers out of the file names and sorting numerically.

In any case, not an OpenCV problem. Please review minimal reproducible example to learn how you need to debug your code before asking.

Related