使用opencv2在qt界面上进行摄像头采集以及简单的拍照功能

来源:互联网 发布:图像尺寸测量软件 编辑:程序博客网 时间:2024/05/17 20:15

首先在这边说明一下为什么要写这个,因为在网上都是使用opencv1的代码,个人感觉有点过时,现在大家基本上都是用opencv2或者opencv3,而库基本上都是用opencv2的库。


首先我们要先将环境安装好:

  1. 安装opencv,链接地址如下:https://opencv.org/downloads.html
  2. 安装qt,我个人是安装比较新的qt5.6.0,链接地址如下:http://download.qt.io/archive/
  3. 配置环境,这个这边不作说明,网上资料一大堆,方法也满天飞,大家自行百度
新建工程:


在ui界面上放两个labeltext,以及三个简单的pushbutton



编辑opencam.h文件:

#ifndef OPENCAM_H
#define OPENCAM_H
#include <QWidget>
#include <QImage>
#include <QTimer>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
namespace Ui {
class opencam;
}
class opencam : public QWidget
{
    Q_OBJECT
public:
    explicit opencam(QWidget *parent = 0);
    ~opencam();
private slots:
    void openCamera();      // 打开摄像头
    void readFarme();       // 读取当前帧信息
    void closeCamera();     // 关闭摄像头。
    void takingPictures();  // 拍照
private:
    Ui::opencam *ui;
    QImage Mat2QImage(Mat cvImg);
    QTimer    *timer;
    QImage    *imag;
    VideoCapture cap;// 视频获取结构, 用来作为视频获取函数的一个参数
    Mat frame;//Mat类型,每一帧存放地址
};
#endif // OPENCAM_H

编辑main.cpp文件

#include "opencam.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    opencam w;
    w.show();
    return a.exec();
}

编辑opencam.cpp文件

  • 初始化以及进行信号槽链接
        timer   = new QTimer(this);
        imag    = new QImage();         // 初始化
        /*信号和槽*/
        connect(timer, SIGNAL(timeout()), this, SLOT(readFarme()));  // 时间到,读取当前摄像头
        connect(ui->open, SIGNAL(clicked()), this, SLOT(openCamera()));
        connect(ui->pic, SIGNAL(clicked()), this, SLOT(takingPictures()));
        connect(ui->closeCam, SIGNAL(clicked()), this, SLOT(closeCamera()));
    }
  • 编辑openCamera()
        cap = NULL;
        VideoCapture cap(1);
        if(!cap.isOpened())
        {
             printf("frame is empty\n");
        }
        timer->start(40);              //开始计时,不可缺少,控制帧率,在这里为25帧
  • 编辑readFrame()函数读取摄像头
    cap>>frame;// 从摄像头中抓取并返回每一帧
        // 将抓取到的帧,转换为QImage格式。QImage::Format_RGB888不同的摄像头用不同的格式。
        QImage imag = Mat2QImage(frame);
        ui->label->setPixmap(QPixmap::fromImage(imag));  // 将图片显示到label上
  • 编辑takingPictures()函数进行拍照设置
    cap>>frame;// 从摄像头中抓取并返回每一帧
        imwrite("frame.jpg",frame);
        // 将抓取到的帧,转换为QImage格式。QImage::Format_RGB888不同的摄像头用不同的格式。
        QImage imag = Mat2QImage(frame);
        ui->label_2->setPixmap(QPixmap::fromImage(imag));  // 将图片显示到label上
  • 编辑closeCamera()函数
    timer->stop();         // 停止读取数据。
        cap.release();



到此,所有程序已经准备就绪



资源下载地址:http://download.csdn.net/detail/ryeda/9692129

1 0
原创粉丝点击