1. 程式人生 > >Qt下使用OpenCV捕獲攝像頭

Qt下使用OpenCV捕獲攝像頭

        在Qt下沒有專門的視訊採集與播放工具。這裡使用了OpenCV所帶的庫函式捕獲攝像頭的視訊影象。這裡要注意的是Qt的影象格式是RGB格式,而OpenCV的格式是BGR,所以要進行顏色通道的轉換,用到了OpenCV的庫函式:cvtColor函式。

       Qt的影象儲存格式是QImage類,而OpenCV的影象格式是Mat,所以要進行轉換:

Mat image = imread("1.jpg");

//改變顏色通道的順序
cv::cvtColor(image, image, CV_BGR2RGB);

//Qt影象
QImage img = QImage((const unsigned char*)(image.data), image.cols, image.rows, QImage::Format_RGB888);

//顯示在label中
ui->label->setPixmap(QPixmap::fromImage(img));  //將QImage 格式轉換成 QPixmap格式用於繪製圖像

           新建一個Qt GUI應用,建立一個新類CameraGet,繼承QWidget類。建立的GUI介面如下:

CameraGet類的標頭檔案如下:


#ifndef CAMERAGET_H
#define CAMERAGET_H

#include <QWidget>
#include <QImage>
#include <QPixmap>
#include <QTimer>

#include <opencv2/opencv.hpp>

namespace Ui {
    class CameraGet;
}

class CameraGet : public QWidget
{
    Q_OBJECT

public:
    explicit CameraGet(QWidget *parent = 0);
    ~CameraGet();

public slots:
    void openCamera();   //開啟攝像頭
    void readFrame();    //讀取當前幀資訊
    void closeCamera();  //關閉攝像頭
    void takingPictures();  //拍照

private:
    Ui::CameraGet *ui;

    QTimer *timer;

    QImage qimage;  //q開頭表示Qt的影象格式

    cv::VideoCapture capture;
    cv::Mat cvframe;  //cv開頭表示是OpenCv的影象格式
};

#endif // CAMERAGET_H


 CameraGet類的實現檔案:

#include "cameraget.h"
#include "ui_cameraget.h"

CameraGet::CameraGet(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CameraGet)
{
    ui->setupUi(this);

    timer = new QTimer(this);

    connect(timer, SIGNAL(timeout()), this, SLOT(readFrame()));
    connect(ui->openCam, SIGNAL(clicked()),this, SLOT(openCamera()));
    connect(ui->tackingPic, SIGNAL(clicked()), this, SLOT(takingPictures()));
    connect(ui->closeCam, SIGNAL(clicked()), this, SLOT(closeCamera()));


}

CameraGet::~CameraGet()
{
    delete ui;
}


//開啟攝像頭
void CameraGet::openCamera()
{
    capture = cv::VideoCapture(0);

    timer->start(33);
}


//讀取攝像頭資訊
void CameraGet::readFrame()
{
    //捕獲攝像頭一幀影象
    capture >> cvframe;

    //顏色通道轉換
    cv::cvtColor(cvframe, cvframe, CV_BGR2RGB);

    //獲取QImage格式的影象
    qimage = QImage((const uchar*)(cvframe.data), cvframe.cols, cvframe.rows, QImage::Format_RGB888);

    //將影象顯示在label中, 之前要把QImage格式的影象轉換成QPixmap格式
    ui->label->setPixmap(QPixmap::fromImage(qimage));
}

//拍照
void CameraGet::takingPictures()
{
    ui->label_2->setPixmap(QPixmap::fromImage(qimage));
}

//關閉攝像頭

void CameraGet::closeCamera()
{
    timer->stop();

    capture.release();
}



演示結果: