OpenCV拍摄图像(C++):定时拍摄和按键拍摄

使用摄像头进行图像拍摄是常见的需求,一般分为两种拍照方式:定时拍照和按键拍照

如果你还没有完成Linux环境下使用OpenCV调用摄像头,请参考本人另一篇博客OpenCV读取摄像头

定时拍摄

大致思路:


  • 读取摄像头中的图像数据,将其存放到Mat中
  • 定时使用imwrite函数将其写入.jpg文件
  • 文件以当前系统时间命名

具体代码如下

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <time.h>

using namespace std;
using namespace cv;

int main()
{
VideoCapture cap; //用于打开摄像头
cap.open(0);
char pic_Name[128] = {}; //照片名称

if(!cap.isOpened())
{
cout << "The camera open failed!" << endl;
}

Mat frame;

time_t nowTime;
tm* now;

while(1)
{
cap >> frame;
if(frame.empty())
break;
imshow("Camera",frame); //展示当前窗体

time(&nowTime); //获取系统当前时间戳
now = localtime(&nowTime); //将时间戳转化为时间结构体

sprintf(pic_Name,"photo/%d-%d-%d %d:%d:%d.jpg",now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
now->tm_hour+8, now->tm_min, now->tm_sec);

cout << "This timenow is:" << now->tm_year + 1900 << "-" << now->tm_mon + 1 << "-" << now->tm_mday
<< " " << now->tm_hour + 8 << ":" << now->tm_min << ":" << now->tm_sec << endl;
imwrite(pic_Name, frame); //将Mat数据写入文件

if(waitKey(30000) >= 0) //暂停30S,可随意更改
break;
}
}
按键拍摄

使用waitKey()函数可以延时程序,并获取用户按下的键的ASCII码值

例如:waitKey(30) == 27效果为延时30ms,且延时期间按下esc键(其ASCII码值为27)之后窗口程序结束延时

程序实例如下:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <time.h>

using namespace std;
using namespace cv;

int main()
{
VideoCapture cap;
cap.open(0);

char pic_Name[128] = {}; //照片名称

if(!cap.isOpened())
{
cout << "The camera open failed!" << endl;
}

Mat frame;

while(1)
{
cap >> frame;
if(frame.empty())
break;
imshow("camera", frame);

time_t nowTime;
tm* now;

if(waitKey(30) == 'q') //按下q键进行拍照
{
time(&nowTime); //获取系统当前时间戳
now = localtime(&nowTime); //将时间戳转化为时间结构体

sprintf(pic_Name,"photo/%d-%d-%d %d:%d:%d.jpg",now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
now->tm_hour+8, now->tm_min, now->tm_sec);
imwrite(pic_Name, frame); //将Mat数据写入文件
}
}
}

需要注意的是, opencv程序编译需要添加相应的编译选项以链接库文件,以上程序在编译时必须添加以下语句:

`pkg-config --cflags --libs opencv`