QT下调用摄像头(opencv2.4.4)
项目pro文件:
#------------------------------------------------- # # Project created by QtCreator 2014-01-18T14:39:58 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = opencv_vedio TEMPLATE = app INCLUDEPATH +=D:\program\opencv\build\include\ INCLUDEPATH +D:\program\opencv\build\include\opencv\ INCLUDEPATH +=D:\program\opencv\build\include\opencv2\ CONFIG(debug,debug|release) { LIBS += -LD:\program\opencv\build\x86\vc10\lib \ -lopencv_core244d \ -lopencv_highgui244d \ -lopencv_imgproc244d \ -lopencv_features2d244d \ -lopencv_calib3d244d } else { LIBS += -LD:\program\opencv\build\x86\vc10\lib \ -lopencv_core244 \ -lopencv_highgui244 \ -lopencv_imgproc244 \ -lopencv_features2d244 \ -lopencv_calib3d244 } SOURCES += main.cpp\ dialog.cpp HEADERS += dialog.h FORMS += dialog.ui
dialog.h:
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <opencv/cv.h> #include <opencv/highgui.h> #include <QTimer> #include <QPixmap> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private: Ui::Dialog *ui; CvCapture *capture; //highgui 里提供的一个专门处理摄像头图像的结构体 IplImage *frame; //摄像头每次抓取的图像为一帧,使用该指针指向一帧图像的内存空间 QTimer *timer; //定时器用于定时取帧,上面说的隔一段时间就去取就是用这个实现。 private slots: void getFrame(); //实现定时从摄像头取图并显示在label上的功能。 }; #endif // DIALOG_H
dialog.cpp:
#include "dialog.h" #include "ui_dialog.h" #include <QDebug> Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); timer = new QTimer(this); capture = cvCaptureFromCAM(0); //cvCaptureFromCAM其实是一个宏,就是cvCreateCameraCapture的别名,0代表第一个摄像头。-1代表默认摄像头。 if(capture==NULL){ qDebug()<<"error!"; } timer->start(50); //1000为1秒,50毫秒去取一帧 connect(timer,SIGNAL(timeout()),this,SLOT(getFrame())); //超时就去取 } Dialog::~Dialog() { timer->stop(); //停止取帧 cvReleaseCapture(&capture); //释放资源是个好习惯 delete ui; } void Dialog::getFrame(){ frame = cvQueryFrame(capture); //从摄像头取帧 QImage image = QImage((const uchar*)frame->imageData, frame->width, frame->height, QImage::Format_RGB888).rgbSwapped(); //简单地转换一下为Image对象,rgbSwapped是为了显示效果色彩好一些。 ui->label->setPixmap(QPixmap::fromImage(image)); }
效果:
工程源码:
作者:小菜鸟_yang
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。