Mp4 created with *'XVID' but does not play

I’m using Ubuntu 18.04, Python 3.6.9 and OpenCV 3.2.0.

II use the following snippet to create an mp4 file. A file is created but does not play. I’ve tried various media player, including VLC, with no luck. I’ve also tried various codex with no success.

Any assistance assistance would be greatly appreciated.


import cv2

cap = cv2.VideoCapture(2)

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

writer = cv2.VideoWriter('myVideo.mpg',cv2.VideoWriter_fourcc(*'XVID'),20,(width,height))

while True:
    
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame', gray)
    
    if cv2.waitKey(1) &  0xFF == ord('q'):
        
        break
        
cap.release()
cv2.destroyAllWindows()

no, that’s not a .mp4

  • try with an .avi container, not .mpg
  • you never write any frames into your writer, add a line like:
    writer.write(frame)
  • if you wanted to write grayscale images, add a isColor=False flag to the VideoWriter constructor

rather use pip install opencv-python to get a more recent version instead of the (very !!) outdated 3.2 your ppm schlepped in

I followed all of your suggestions and it works perfect now. Thank-you very much.

1 Like