Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Output by OpenCV VideoWriter empty

I have recently started to program with opencv-python, but I got stuck when I tried to write a video using cv2. The output by the script is empty. Here's my code:

import cv2
import numpy as np
import matplotlib.pyplot as plt

cap = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc(*'h263')
out = cv2.VideoWriter('cv2_camera_output.mp4',fourcc, 20.0, (800,600))


while True:
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', frame)
    cv2.imshow('gray', gray)
    out.write(frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


cap.release()
out.release()
cv2.destroyAllWindows()

I guessed that the issue must have something to do with the fourcc codec. So I googled if there was a fourCC codec for mac (I am using OS X 10.12.3 (Sierra)), but all the suggestions didn't work for my computer, so the issue may not even be in the fourCC codec. These are the links I have visited:

OpenCV Documentation (I didn't follow this one, it was just to make sure, and it didn't work either)

GitHub Tests for FourCC codecs on OS X

Does anybody know the real issue? Any help would be great

like image 720
MisterMM23 Avatar asked Aug 17 '17 17:08

MisterMM23


2 Answers

Your frame width and height must be the same as the width and height of your VideoWriter. Just add this before out.write(frame) and you might be fine:

frame = cv2.resize(frame,(800,600))

Or change the size of your VideoWriter to the initial size of webcam frame. Mine is (640,480). I think if your OS doesn't support the format, it just won't write anything. Not even an empty file will be created. I'm on Linux and I think 'h263' doesn't work on it but 'h264' does. When I use 'h263' it just doesn't make any file.

like image 105
Arash Rohani Avatar answered Oct 15 '22 13:10

Arash Rohani


I solved the problem. The problem simply was that I could not use the VideoWriter for grayscale, so I had to use it for the coloured frame.

like image 22
MisterMM23 Avatar answered Oct 15 '22 11:10

MisterMM23