Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created March 9, 2017 15:01
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save keithweaver/4b16d3f05456171c1af1f1300ebd0f12 to your computer and use it in GitHub Desktop.
Save keithweaver/4b16d3f05456171c1af1f1300ebd0f12 to your computer and use it in GitHub Desktop.
Stream and save video in Python with OpenCV
# For more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
import cv2
import numpy as np
import os
FILE_OUTPUT = 'output.avi'
# Checks and deletes the output file
# You cant have a existing file or it will through an error
if os.path.isfile(FILE_OUTPUT):
os.remove(FILE_OUTPUT)
# Playing video from file:
# cap = cv2.VideoCapture('vtest.avi')
# Capturing video from webcam:
cap = cv2.VideoCapture(0)
currentFrame = 0
# Get current width of frame
width = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) # float
# Get current height of frame
height = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) # float
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'X264')
out = cv2.VideoWriter(FILE_OUTPUT,fourcc, 20.0, (int(width),int(height)))
# while(True):
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
if ret == True:
# Handles the mirroring of the current frame
frame = cv2.flip(frame,1)
# Saves for video
out.write(frame)
# Display the resulting frame
cv2.imshow('frame',frame)
else:
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# To stop duplicate images
currentFrame += 1
# When everything done, release the capture
cap.release()
out.release()
cv2.destroyAllWindows()
# Potential Error:
# OpenCV: Cannot Use FaceTime HD Kamera
# OpenCV: camera failed to properly initialize!
# Segmentation fault: 11
#
# Solution:
# I solved this by restarting my computer.
# http://stackoverflow.com/questions/40719136/opencv-cannot-use-facetime/42678644#42678644
@Monkeydluffy3
Copy link

giving following error:
module 'cv2' has no attribute 'cv'

@eelectron
Copy link

Its not working on Ubuntu 16.04. Which OS you are using?

@bharshal
Copy link

@Monkeydluffy3 try using " fourcc=cv2.VideoWriter_fourcc('XVID') " or " fourcc=cv2.VideoWriter_fourcc('X264') " at line 27. In the newer versions of OpenCV, the correct way to use is cv2.xyz rather than cv2.cv.xyz.

@217aniruddhapal
Copy link

@bharshal Its not working. giving AttributeError as "cv2.cv2' has no attribute 'videoWriter'"

@vinothsethupathy007
Copy link

# For more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
import cv2 as cv2
import cv2 as cv
import numpy as np
import os

FILE_OUTPUT = 'output.avi'

# Checks and deletes the output file
# You cant have a existing file or it will through an error
if os.path.isfile(FILE_OUTPUT):
    os.remove(FILE_OUTPUT)

# Playing video from file:
# cap = cv2.VideoCapture('vtest.avi')
# Capturing video from webcam:
cap = cv2.VideoCapture(0)

currentFrame = 0


width = cap.set(cv2.CAP_PROP_FRAME_WIDTH, 160);
height  = cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 120);


# Get current width of frame
# width = cap.get(cv2.CV_CAP_PROP_FRAME_WIDTH)   # float
# Get current height of frame
# height = cap.get(cv2.CV_CAP_PROP_FRAME_HEIGHT) # float


# Define the codec and create VideoWriter object
# fourcc = cv2.CV_FOURCC(*'X264')

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(FILE_OUTPUT,fourcc, 20.0, (int(width),int(height)))

# while(True):
while(cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = cap.read()

    if ret == True:
        # Handles the mirroring of the current frame
        frame = cv2.flip(frame,1)

        # Saves for video
        out.write(frame)

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

    # To stop duplicate images
    currentFrame += 1

# When everything done, release the capture
cap.release()
out.release()
cv2.destroyAllWindows()

@officer47p
Copy link

Hey guys, why should I use out.write(cv2.flip(frame, 180)) in my codes to save the videos? I've seen some people that don't use it and they can save their videos but I can't without it.
Any suggestions?

@HappyBahman
Copy link

I managed to run the code on opencv 4 and ubuntu 18 by changing the line 27 to:
cv2.VideoWriter_fourcc(*'X264')
and the lines 20 to 23 as:
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float

@BenDurmishllari
Copy link

It gives me this error :

objc[44260]: Class RunLoopModeTracker is implemented in both /Users/ben/anaconda3/lib/python3.7/site-packages/cv2/.dylibs/QtCore (0x11686b7f0) and /Users/ben/anaconda3/lib/libQt5Core.5.9.7.dylib (0x12f501a80). One of the two will be used. Which one is undefined.
QObject::moveToThread: Current thread (0x7ffc85f31e40) is not the object's thread (0x7ffc85d98d30).
Cannot move to target thread (0x7ffc85f31e40)

You might be loading two sets of Qt binaries into the same process. Check that all plugins are compiled against the right Qt binaries. Export DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded.
qt.qpa.plugin: Could not load the Qt platform plugin "cocoa" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: cocoa, minimal, offscreen.

@sysad-aldama
Copy link

It gives me this error :

objc[44260]: Class RunLoopModeTracker is implemented in both /Users/ben/anaconda3/lib/python3.7/site-packages/cv2/.dylibs/QtCore (0x11686b7f0) and /Users/ben/anaconda3/lib/libQt5Core.5.9.7.dylib (0x12f501a80). One of the two will be used. Which one is undefined.
QObject::moveToThread: Current thread (0x7ffc85f31e40) is not the object's thread (0x7ffc85d98d30).
Cannot move to target thread (0x7ffc85f31e40)

You might be loading two sets of Qt binaries into the same process. Check that all plugins are compiled against the right Qt binaries. Export DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded.
qt.qpa.plugin: Could not load the Qt platform plugin "cocoa" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: cocoa, minimal, offscreen.

I am having the same exact issue and its driving me crazy. Three hours and the same thing. please help :( anyone out there.

@scandav
Copy link

scandav commented Jun 21, 2022

For those using cv2 v4+, I solved using

width = self.video.get(cv2.CAP_PROP_FRAME_WIDTH)  
height = self.video.get(cv2.CAP_PROP_FRAME_HEIGHT)

fourcc = cv2.VideoWriter.fourcc(*'X264')

as explained here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment