赞
踩
关键代码语句:
① VideoCapture cam(0);
② cam.read(img);
③ imshow("cam", img);
- # include<opencv2/opencv.hpp>
- # include<cstdio>
- using namespace cv;
- using namespace std;
-
- int main(int argc, char *argv[]){
- // 打开摄像头
- VideoCapture cam(0);
- if (!cam.isOpened()){
- cout << "cam open failed!" << endl;
- getchar();
- return -1;
- }
-
- cout << "cam open success!" << endl;
- namedWindow("cam");
- Mat img;
-
- for(;;){
- cam.read(img); // 读帧
- if (img.empty()) break;
- imshow("cam", img); // 显示每一帧
-
- if (waitKey(5) == 'q') break; // 键入q停止
- }
-
- return 0;
- }
关键代码:
①VideoWriter vw
②vw.open():fourcc指定编码格式(常见编码方式)、fps指定帧率、Size指定大小
③vw.write()
- # include<opencv2/opencv.hpp>
- # include<cstdio>
- using namespace cv;
- using namespace std;
-
- int main(int argc, char *argv[]){
- // 打开摄像头
- VideoCapture cam(0);
- if (!cam.isOpened()){
- cout << "cam open failed!" << endl;
- getchar();
- return -1;
- }
- cout << "cam open success!" << endl;
-
- namedWindow("cam");
- Mat img;
- VideoWriter vw;
- int fps = cam.get(CAP_PROP_FPS); // 获取原视频的帧率
- if (fps <= 0) fps = 25;
-
- vw.open("./out1120.avi",
- VideoWriter::fourcc('X', '2', '6', '4'),
- fps,
- Size(cam.get(CAP_PROP_FRAME_WIDTH),
- cam.get(CAP_PROP_FRAME_HEIGHT))
- );
-
- if (!vw.isOpened()){ // 判断VideoWriter是否正常打开
- cout << "videoWriter open failed!" << endl;
- getchar();
- return -1;
- }
- cout << "videoWriter open sucess!" << endl;
- for(;;){
- cam.read(img); // 读帧
- if (img.empty()) break;
- imshow("cam", img); // 展示当前帧
- /*
- 这里可以添加对当前帧的处理操作
- */
- vw.write(img); // 保存当前帧
- if (waitKey(5) == 'q') break; // 键入q停止
- }
-
- return 0;
- }
注:在Windows上执行上述代码可能会报以下错误:
解决方法:在输出的网址下载对应版本的库文件,放在执行文件.exe的同级目录即可,或者将该dll文件的路径添加到系统变量path中。
结果:生成的out1120.avi可以正常播放;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。