赞
踩
重点语句:VideoCapture、imshow
原理:使用VideoCapture语句读取摄像头,再利用while一次次将VideoCapture所读取的数据利用imshow语句一帧帧地读取出来
- #include <opencv2/opencv.hpp>
- #include <iostream>
- #include "CameraVideo.h"
-
- using namespace cv;
- using namespace std;
-
- int main(int argc,char** argv)
- {
- VideoCapture video; //用VideoCapture来读取摄像头
- Mat picture; //声明一个保存图像的类
- video.open(0); //括号的0表示使用电脑自带的摄像头
- if (!video.isOpened()) //判断摄像头是否读取成功
- {
- return -1; //返回一个代数值,表示函数失败(若为return 1,则表示ture)
- }
- while(1) //(读取成功,使用循环语句将视频一帧一帧地展示出来)
- {
- video >> picture; //词条将video中的数据流向picture
- imshow("input", picture); //使用imshow语句将图片显示出来
- waitKey(30); //停顿30ms
- }
- return 0;
- }

重点语句:VideoWriter
原理:在摄像头读取完图之后,利用VideoWriter语句将图像保存为固定格式
- #include <opencv2/opencv.hpp>
- #include <iostream>
- using namespace cv;
- using namespace std;
- int main(int argc, char** argv)
- {
- Mat picture;
- VideoCapture video(0);
- if (!video.isOpened())
- {
- return-1;
- }
-
-
- video >> picture;
- VideoWriter outputVideo; //用VideoWriter语句保存视频
- int codec = VideoWriter::fourcc('P', 'I','M','1'); //OpenCV4版本的编码设置格式
- //('P', 'I','M','1')—MPEG-1编码类型,文件扩展名.avi
- int fps = 25; //设置帧率
- string outputVideoPath = "CameraVideo.mp4"; //保存视频的文件名
- outputVideo.open(outputVideoPath, codec, fps, picture.size());//创建保存视频文件的视频流
- if (!outputVideo.isOpened()) //判断视频流是否创建成功
- {
- return -1;
- }
- while (1)
- {
- if (!video.read(picture)) //检测是否能够读取一帧图像
- {
- break;
- }
- outputVideo.write(picture); //将video的图像数据一帧图像写入
- imshow("CameraVideo.mp4", picture); //显示图像
- char c = waitKey(50);
- if (c == 27) //按Esc保存视频
- {
- break;
- }
- }
-
- return 0;
- }

通过加入一个循环语句,按空格将图片按照1.2.3.4.5.6.的顺序保存下来
- #include <opencv2/opencv.hpp>
- #include <iostream>
- using namespace cv;
- using namespace std;
- int main(int argc, char** argv)
- {
- Mat picture;
- VideoCapture video(0);
- if (!video.isOpened())
- {
- return-1;
- }
-
-
- int i = 0;
- while (1)
- {
- video >> picture;
- imshow("input", picture);
-
- if (waitKey(20) == 32) //设置为按空格保存
- {
- string name = to_string(i) + ".jpg"; //将照片以jpg的格式进行命名
- imwrite(name, picture); //将按空格时的图像帧保存下来
- i++;
- }
- if (waitKey(10) == 27) //按Esc键退出
- {
- break;
- }
- }
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。