Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and OpenCV - Cannot write readable avi video files

I have a code like this:

import numpy as np
import cv2


cap = cv2.VideoCapture('C:/Users/Hilman/haatsu/drive_recorder/sample/3.mov')

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

But the output.avi cannot be played.

Tried also change the out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480)) to something like this (as suggested by some people) out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480)). But when I did this, I got this message

OpenCV: FFMPEG: tag 0xffffffff/'    ' is not found (format 'avi / AVI (Audio Video Interleaved)')'.

What could be the problem? I am using Windows 10 by the way.

like image 842
Hafiz Hilman Mohammad Sofian Avatar asked Nov 09 '22 16:11

Hafiz Hilman Mohammad Sofian


1 Answers

I couldn't get that code to run on my Windows 10 machine either.

So here's what I did:

  1. I followed these instructions and installed the latest ffmpeg build on machine:
    1. Download the latest static build for Windows and then extract the files. You may need 7zip to extract.
    2. Create a folder in C:\ called ffmpeg
    3. Copy the contents of the extracted files into C:\ffmpeg
    4. Edit your PATH environment variable to append at the end the following entry: C:\ffmpeg\bin;
    5. Confirm that everything is working correct by opening a cmd prompt and enter the following (Note you might need to run cmd as administrator): ffmpeg -version
  2. Modified your code as follows:

_

import numpy as np
import cv2
import os

base_path = 'C:\\Users\\Hilman\\haatsu\\drive_recorder\\sample\\'
cap = cv2.VideoCapture('%s3.mov' % base_path)

i = 0
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)
        cv2.imwrite(os.path.join(base_path, str(i) + '.png'), frame)
        i = i + 1
    else:
        break

# Release everything if job is finished
cap.release()  
  1. Opened a command prompt at C:\Users\Hilman\haatsu\drive_recorder\sample and ran the following command: ffmpeg -framerate 29 -i %d.png -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
  2. Your video should be saved as out.mp4.
like image 119
Jim G. Avatar answered Nov 14 '22 22:11

Jim G.