-1

I'm trying to make a video from images with python and OpenCV but when I run the script the video is generated but when I try to open it I give this error:

enter image description here

This is the script:

import cv2
import numpy as np
import glob

frameSize = (1920, 1080)

out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)

for filename in glob.glob('/folder_path/*.jpg'):
   img = cv2.imread(filename)
   out.write(img)

out.release()

UPDATE:

If I use

out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'MJPG'), 60, frameSize)

Instead

out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)

The video start but I can see anything

enter image description here

Piero
  • 404
  • 3
  • 7
  • 22
  • Try this: https://stackoverflow.com/questions/30509573/writing-an-mp4-video-using-python-opencv and/or this: https://stackoverflow.com/questions/29317262/opencv-video-saving-in-python – Jeru Luke Jul 09 '22 at 18:24

1 Answers1

0

Ok, I have found a solution.

This is the final code:


import cv2,os 
from os.path import isfile, join 

def convert_pictures_to_video(pathIn, pathOut, fps, time):
    
    # this function converts images to video
    frame_array=[]
    files=[f for f in os.listdir(pathIn) if isfile(join(pathIn,f))]
    #files.remove(".DS_Store")

    for i in range (len(files)):

        filename=pathIn+files[i]
        # reading images
        img=cv2.imread(filename)
        # img=cv2.resize(img,(1400,1000))
        height, width, layers = img.shape
        size=(width,height)

        for k in range (time):
            frame_array.append(img)
    out=cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
    for i in range(len(frame_array)):
        out.write(frame_array[i])
    out.release()



pathIn= '/pathIn-folder/'
pathOut='/pathOut-folder/output.avi'
fps=1
time=20 # the duration of each picture in the video
convert_pictures_to_video(pathIn, pathOut, fps, time)

You can find more info and a tutorial here.

REMEMBER If you have a mac there are two important things to do.

  1. First you have to uncomment #files.remove(".DS_Store") because when you create a new folder on macOS there is an extra hidden file called .DS_Store
  2. You can't open the output video with Quick Time Player You have to use another software like VLC
Piero
  • 404
  • 3
  • 7
  • 22
  • and what exactly is different between those two blocks of code? -- the question basically lacks an `out.isOpened()` check, but the issue can have multiple other causes – Christoph Rackwitz Jul 09 '22 at 22:45
  • hi @ChristophRackwitz, I think the problems are many ... which have negatively affected. The codec, the DS.store file, quick time player the dimensions of the images that must exactly match those of the videos and the time that must be calculated based on the desired fps – Piero Jul 10 '22 at 11:32