OpenCV拍摄图像(C++)

18 篇文章 10 订阅

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`
  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值