|
今天寫的QT+openCV實現(xiàn)攝像頭拍照功能。
在網(wǎng)上收羅了很多資料,QT沒有專門操作攝像頭的類,這個得自己寫。網(wǎng)上也有很多關(guān)務(wù)openCV和V4l的一些介紹,由于我項目要在window下開發(fā),所以就選擇了openCV。由于以前沒有用過openCV,所以就只看了關(guān)于openCVS攝像頭操作的這部分,其他的還沒時間去看。
openCV : http:///projects/opencvlibrary/files/opencv-win/2.1/
剛開始下載的是2.3.1的,安裝后發(fā)現(xiàn)沒有l(wèi)ib庫所以后面選擇了2.1的
openCV中文學(xué)習(xí) pdf :
現(xiàn)在,開始詳細(xì)的介紹如何在QT中實時的采集攝像頭數(shù)據(jù)。
打開QTcreator (我用的是QT 2.3的 中文版)
新建一個widget工程

在界面上放兩個label 分別用來顯示攝像頭采集到的數(shù)據(jù)和照的照片。

編輯camaraget.h 文件
- #ifndef CAMARAGET_H
- #define CAMARAGET_H
-
- #include <QWidget>
- #include <QImage>
- #include <QTimer> // 設(shè)置采集數(shù)據(jù)的間隔時間
-
- #include <highgui.h> //包含opencv庫頭文件
- #include <cv.h>
-
- namespace Ui {
- class camaraGet;
- }
-
- class camaraGet : public QWidget
- {
- Q_OBJECT
-
- public:
- explicit camaraGet(QWidget *parent = 0);
- ~camaraGet();
-
- private slots:
- void openCamara();
- void readFarme();
- void closeCamara();
- void takingPictures();
-
- private:
- Ui::camaraGet *ui;
- QTimer *timer;
- QImage *imag;
- CvCapture *cam;
- IplImage *frame;
- };
-
- #endif // CAMARAGET_H
編輯camaraget.cpp
- #include "camaraget.h"
- #include "ui_camaraget.h"
-
- camaraGet::camaraGet(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::camaraGet)
- {
- ui->setupUi(this);
-
- cam = NULL;
- timer = new QTimer(this);
- imag = new QImage();
-
-
- connect(timer, SIGNAL(timeout()), this, SLOT(readFarme()));
- connect(ui->open, SIGNAL(clicked()), this, SLOT(openCamara()));
- connect(ui->pic, SIGNAL(clicked()), this, SLOT(takingPictures()));
- connect(ui->closeCam, SIGNAL(clicked()), this, SLOT(closeCamara()));
- }
-
-
-
-
- void camaraGet::openCamara()
- {
- cam = cvCreateCameraCapture(0);
-
- timer->start(33);
- }
-
-
-
-
- void camaraGet::readFarme()
- {
- frame = cvQueryFrame(cam);
-
- QImage image((const uchar*)frame->imageData, frame->width, frame->height, QImage::Format_RGB888);
- ui->label->setPixmap(QPixmap::fromImage(image));
- }
-
-
-
-
- void camaraGet::takingPictures()
- {
- frame = cvQueryFrame(cam);
-
-
- QImage image((const uchar*)frame->imageData, frame->width, frame->height, QImage::Format_RGB888);
-
- ui->label_2->setPixmap(QPixmap::fromImage(image));
- }
-
-
-
-
- void camaraGet::closeCamara()
- {
- timer->stop();
-
- cvReleaseCapture(&cam);
- }
-
- camaraGet::~camaraGet()
- {
- delete ui;
- }
好了,全部代碼都OK了(當(dāng)然,創(chuàng)建工程時,會生成main.cpp,不必去改動它),但現(xiàn)在你點(diǎn)運(yùn)行,依然會產(chǎn)生錯誤,為什么呢?因為還沒有把openCV的庫包含進(jìn)去。
在*.pro 文件中 加入:
INCLUDEPATH+=C:\OpenCV2.1\include\opencv LIBS += C:\OpenCV2.1\lib\highgui210.lib \ C:\OpenCV2.1\lib\cxcore210.lib \ C:\OpenCV2.1\lib\cv210.lib OK,大功告成,運(yùn)行后,在widget中點(diǎn)擊打開攝像頭,就可以看到自己了。運(yùn)行后的效果:

后來我發(fā)現(xiàn)這個效果不怎么好,就改了一下:改了以后的運(yùn)行效果也貼出來:
就改了一句:
- QImage image((const uchar*)frame->imageData, frame->width, frame->height, QImage::Format_RGB888);
- 改為了 QImage image = QImage((const uchar*)frame->imageData, frame->width, frame->height, QImage::Format_RGB888).rgbSwapped();

|