【opencv|opencv打开电脑摄像头,空格控制视频录制暂停,ESC退出并保存视频】基本思路:
(1)打开摄像头
(2)获得摄像头读入图像参数,设置视频录制器VideoWriter
(3)捕获键盘操作,空格key=32, ESC的key=27
(4)不断刷新当前帧,显示视频录制情况
(5)写入磁盘
代码:
/*********************************************************************
打开电脑摄像头,空格控制视频录制,ESC退出并保存视频RecordVideo.avi
*********************************************************************/
#include
#include
#include
#include
using namespace cv;
using namespace std;
void main()
{
//打开电脑摄像头
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "error" << endl;
waitKey(0);
return;
} //获得cap的分辨率
int w = static_cast(cap.get(CV_CAP_PROP_FRAME_WIDTH));
int h = static_cast(cap.get(CV_CAP_PROP_FRAME_HEIGHT));
Size videoSize(w, h);
VideoWriter writer("RecordVideo.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, videoSize);
Mat frame;
int key;
//记录键盘按键
char startOrStop = 1;
//0开始录制视频; 1 结束录制视频
char flag = 0;
//正在录制标志 0-不在录制; 1-正在录制 while (1)
{
cap >> frame;
key = waitKey(100);
if (key == 32)//按下空格开始录制、暂停录制可以来回切换
{
startOrStop = 1 - startOrStop;
if (startOrStop == 0)
{
flag = 1;
}
}
if (key == 27)//按下ESC退出整个程序,保存视频文件到磁盘
{
break;
}if (startOrStop == 0 && flag==1)
{
writer << frame;
cout << "recording" << endl;
}
else if (startOrStop == 1)
{
flag = 0;
cout << "end recording" << endl;
}
imshow("picture", frame);
}
cap.release();
writer.release();
destroyAllWindows();
}
推荐阅读
- 计算机视觉|OpenCV_05图像变换
- Python使用OpenCV检测图像的一角
- Python具有跟踪栏的OpenCV BGR调色板
- Python OpenCV cv2.arrowedLine()方法用法示例
- Python OpenCV cv2.copyMakeBorder()方法用法示例
- Python OpenCV cv2.cvtColor()方法用法示例
- Python OpenCV cv2.ellipse()方法用法介绍
- Python OpenCV cv2.erode()方法用法
- Python OpenCV | cv2.imshow()方法介绍