Video written through OpenCV on Raspberry Pi not running

Question:

I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code

import cv2
cap = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'')
out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480))
while True:
    ret, frame = cap.read()
    cv2.imshow('frame', frame) 
    out.write(frame) 
    if cv2.waitKey(1) & 0xFF== ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

The video file is created but I am not able to run that file. I also tried with different formats like ‘XVID’,’MJPG’,’H264′ but faced the same issue.
My opencv version is 4.3.038

Asked By: Ekta arora

||

Answers:

There are two issues, I would like to address:

  • Issue #1: DIVX should be declared as:

  • fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
    
  • Issue #2:


  • You have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480)

  • frame = cv2.resize(frame, (640, 480))
    

But if you use it with DIVX you will have a warning:

OpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'

Instead of DIVX use mp4v for creating .mp4 videos.

Code:


import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('output.mp4', fourcc, 25, (640, 480), isColor=True)
while True:
    ret, frame = cap.read()
    frame = cv2.resize(frame, (640, 480))
    cv2.imshow('frame', frame)
    out.write(frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()
Answered By: Ahx

You can try this code. Works for me

import cv2

cap = cv2.VideoCapture(0)

video_speed = 15 #This frame rate works well on my case
video_name = 'output.avi'
writer = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc('M','J','P','G'),video_speed, (640,480))

while True:
    ret , frame = cap.read()
    if ret == True:
        writer.writer(frame)
        cv2.imshow('Frame', frame)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
writer.release()
cv2.destroyAllWindows()
Answered By: Melon Streams