OpenСV offers great opportunities when working with video and images. For example, saving streaming video from a video camera in real time.
All examples were written for OpenCV version 3.4.2
Example on python3.6.5:
import cv2
# function video capture
cameraCapture = cv2.VideoCapture(0)
# rame rate or frames per second
fps = 30
# Width and height of the frames in the video stream
size = (int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
"""
Create a VideoWriter object. We should specify the output file name (eg: MyOutput.avi). Then we should specify the FourCC. Then number of frames per second (fps) and frame size should be passed. May specify isColor flag. If it is True, encoder expect color frame, otherwise it works with grayscale frame.
FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org. It is platform dependent.
"""
videoWriter = cv2.VideoWriter('MyOutput.avi',
cv2.VideoWriter_fourcc('I','4','2','0'), fps, size)
success, frame = cameraCapture.read()
# some variable
numFramesRemaining = 10*fps - 1
# loop until there are no more frames and variable > 0
while success and numFramesRemaining > 0:
videoWriter.write(frame)
success, frame = cameraCapture.read()
cv2.imshow('frame',frame)
cv2.waitKey(1)
numFramesRemaining -= 1
#Closes video file or capturing device
cameraCapture.release()
Examples of different meanings FourCC:
The same code written in C ++ and gcc 7.3.0:
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(){
// Create a VideoCapture object and use camera to capture the video
VideoCapture cap(0);
int fps = 30;
// Check if camera opened successfully
if(!cap.isOpened()){
cout << "Error opening video stream" << endl;
return -1;
}
// Default resolutions of the frame are obtained.The default resolutions are system dependent.
int frame_width = cap.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
// Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file.
VideoWriter video("outcpp.avi",CV_FOURCC('I','4','2','0'), fps, Size(frame_width,frame_height));
int numFramesRemaining = (10*fps - 1);
while (1 and numFramesRemaining > 0) {
Mat frame;
// Capture frame-by-frame
cap >> frame;
// If the frame is empty, break immediately
if (frame.empty())
break;
// Write the frame into the file 'outcpp.avi'
video.write(frame);
// Display the resulting frame
imshow( "Frame", frame );
char c = (char)waitKey(1);
// possible use ESC for break
//if( c == 27 )
// break;
numFramesRemaining -= 1;
}
// When everything done, release the video capture and write object
cap.release();
video.release();
// Closes all the frames
destroyAllWindows();
return 0;
}
Oct. 24, 2023, 12:01 p.m. - fun88 ¶
Jan. 5, 2022, 10:49 a.m. - Klee ¶
Jan. 6, 2022, 9:23 p.m. - Ihar moderator ¶
Sept. 23, 2021, 9:38 p.m. - Klaus ¶