版权声明:原创文章,转载请标明来源 https://blog.csdn.net/ngy321/article/details/79883468
opencv-python
代码如下:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
#Define the codec and create VideoWrite object, 10 is fps, (640,480) is screen size
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('./video/cameravideo/cameraoutput.avi', fourcc, 10, (640,480))
while(1):
#get a frame
ret, frame = cap.read()
#save a frame
out.write(frame)
#show a frame
cv2.imshow("capture", frame)
#press 'q' to quit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
opencv c++ 代码:
#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/video/video.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
using namespace std;
using namespace cv;
int main()
{
cout << "+++++++++++++++++++++++++++++++++++++++++" << endl << "| This is a demo. |" << endl
<< "| Press 'R' to start recording. |" << endl << "| Press 'S' to stop recording. |" << endl
<< "| Press 'Q' to quit. |" << endl << "+++++++++++++++++++++++++++++++++++++++++" << endl;
string output_path = "../out.avi";
VideoCapture cap;
cap.open(0);
if(!cap.isOpened())
cout << "camera not opened!" << endl;
VideoWriter writer;
Mat cameraImg;
int width = cap.get(CAP_PROP_FRAME_WIDTH);
int height = cap.get(CAP_PROP_FRAME_HEIGHT);
while(1)
{
cap.read(cameraImg);
if(writer.isOpened())
{
if (cameraImg.empty()) break;
writer.write(cameraImg);
}
imshow("image",cameraImg);
char key = char(waitKey(1));
if (key == 'q') // ESC
{
cout << "-- camera closed" << endl;
cap.release();
destroyAllWindows();
break;
}
if (key == 't') // T
{
drawOverlay = !drawOverlay;
}
if (key == 'r') // R
{
cout << "-- start recording" << endl;
writer.open(output_path, writer.fourcc('P', 'I', 'M', '1'), 25.0, Size(width, height));
if(writer.isOpened())
{
cout << " writer opened successfully" << endl;
}
else
{
cout << " writer opening failed" << endl;
}
}
if (key == 's')
{
cout << "-- stop recording" << endl << " video is saved to " << output_path << endl;
if(writer.isOpened())
{
writer.release();
}
}
}
return 0;
}