skip to Main Content

I’m new to opencv and I try to generate a video file from a set a jpg pictures.

This works fine if I use ffmpeg : ffmpeg -y -r 60 -i capture.%d.jpg -c:v libx264 ffmpeg_test.mkv
With my 120 pictures, this generates a 2s video.
I’d like to do the same with opencv.

Here is the code I use:

import cv2

def record(writer):
  for i in range(121):
    img = cv2.imread(f"capture.{i}.jpg")
    writer.write(img)

fourcc = cv2.VideoWriter.fourcc(*'x264')
writer = cv2.VideoWriter("py_test.mkv", fourcc, 60.0, [120, 160])
record(writer)
writer.release()

I’ve got no error on execution, the file seems a regular video file, checked with mediainfo, but vlc raise an error (in verbose mode) "mkv error: cannot find any cluster or chapter". The file is 553 bytes.

Ubuntu 22.04
python3-opencv (package from apt)
python 3.10.12 (cv2.version = 4.5.4)

I tried changing format (MPEG, mpgv, XVID, mp4v, …) and container (avi, mp4), the result is always the same (file ~500 bytes).
I concluded that my images are never integrated to the video, but I don’t know why.

2

Answers


  1. Chosen as BEST ANSWER

    It was in "with shape (120, 160, 3)". while images are 120 height x 160 width, cv2.VideoWriter wants (width, height).

    Clue was in Can't play video created with OpenCV VideoWriter

    After correction, I tried with codec MPEG, mpgv, XVID, mp4v, H264, x264, DIVX, AVI1, RGBA, FLV1, with container mkv. Also with codec XVID, it works with containers mp4 and avi.

    I did not try all combinations, but if there is a problem, it is not related to mine.

    Thanks anyone for your time.


  2. Disclaimer: I don’t use OpenCV or Python so please fix any compiler errors.

    Try as:

    import cv2
    
    def record(writer):
      for i in range(121):
        img = cv2.VideoCapture("/myfolder/capture."+ str(i) + ".jpg")
        writer.write(img)
        
      # try releasing only after the For-loop is finished
      writer.release()
    
    fourcc = cv2.VideoWriter.fourcc(*'XVID') # consider also: *'MP4V'
    writer = cv2.VideoWriter("py_test2.mp4", fourcc, 60, (120, 160))
    record(writer)
    # writer.release() # might run too soon (eg: before For-loop ends)
    

    Code logic towards trying to solve the problem:

    • Expects files are named as capture.0.jpg , capture.1.jpg , capture.2.jpg .... capture.121.jpg.

    • Tries to wait until the For loop is finished before releasing the writer (finalize the video file).

    • Tries FOURCC of xvid (and possible mp4v) with MP4 output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search