Getting started with video:
http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html#display-video
The following example will load up a video from disk . It uses the VideoCapture object.
- Its argument can be either the device index or the name of a video file. Device usually is the index is just the number to specify which camera to use. This line below sets the video source to use an existing file.
#------------------------------------------------------------
import numpy as np
import cv2 as cv
cap = cv.VideoCapture('output.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow('frame',gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
#------------------------------------------------------------
[link] - tweak for VideoCapture
VideoWriter([filename, fourcc, fps, frameSize, isColor)
- filename – Name of the output video file.
- fourcc – 4-character code of codec used to compress the frames.
- fps – Framerate of the created video stream.
- frameSize – Size of the video frames.
- isColor – If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).
The read() function
- reads one frame from the video source, which in this example is the webcam.
This returns two things:
- The actual video frame read (one frame on each loop)
- A return code (True/False). If frame is read correctly. It tells us if we have run out of frames, which will happen if we are reading from a file. This doesn’t matter when reading from the webcam, since we can record forever, so we will ignore it.
#------------------------------------------------------------
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame',gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
#------------------------------------------------------------
Saving images from video camera input to a file:
import cv2
import numpy as np
#This line sets the video source to the default webcam, which OpenCV
cap = cv2.VideoCapture(0)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH);
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT);
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4',fourcc, 15.0, (int(w),int(h)))
while True:
ret,frame = cap.read()
#---------for gray video--------
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(frame)
cv2.imshow('myvideo',gray)
cv2.waitKey(0)
k = cv2.waitKey(0) & 0xFF
if k == ord('q'): # wait for 'q' key to exit break
break
cap.release()
out.release()
cv2.destroyAllWindows()