QT中利用opencv 代码进行摄像头编程

来源:互联网 发布:linux下载jdk1.8.0 编辑:程序博客网 时间:2024/04/29 03:54

http://mobile.51cto.com/symbian-271265.htm

http://blog.csdn.net/yang_xian521/article/details/7042687

[cpp] view plaincopy
  1. // myWidget.h    
  2. #ifndef MYWIDGET_H    
  3. #define MYWIDGET_H    
  4. #include <QtGui\QWidget>   
  5. #include <QtGui\QPaintEvent>   
  6. #include <QtGui\QImage>   
  7. #include <QtCore\QTimer>   
  8. #include <cv.h>   
  9. #include <highgui.h>   
  10. class myWidget : public QWidget    
  11. {  
  12.    Q_OBJECT    
  13.    public:     
  14.    myWidget(const char *filename,QWidget *parent = 0);  
  15.    ~myWidget();  
  16.    protected:  
  17.    void paintEvent(QPaintEvent *e);  
  18.    private slots:  
  19.    void nextFrame();  
  20.    private:  
  21.    CvCapture *capture;  
  22.    IplImage *iplImg;  
  23.    IplImage *frame;  
  24.    QImage *qImg;  
  25.    QTimer *timer;  
  26. };  
  27. #endif  


 

[cpp] view plaincopy
  1. // myWidget.cpp    
  2. #include "myWidget.h"    
  3. #include <QtGui\QPainter>   
  4. #include <QtCore\QPoint>   
  5. myWidget::myWidget(const char *filename,QWidget *parent /* = 0 */) : QWidget(parent)    
  6. {  
  7.    capture = cvCaptureFromFile(filename);  
  8.    if (capture)  
  9.    {  
  10.         frame = cvQueryFrame(capture);  
  11.         if (frame)  
  12.             this->resize(frame->width,frame->height);  
  13.         qImg = new QImage(QSize(frame->width,frame->height), QImage::Format_RGB888);  
  14.         iplImg = cvCreateImageHeader(cvSize(frame->width,frame->height), 8,3);  
  15.         iplImg->imageData = (char*)qImg->bits();  
  16.         timer = new QTimer(this);  
  17.         timer->setInterval(30);  
  18.         connect(timer,SIGNAL(timeout()),this,SLOT(nextFrame()));  
  19.         timer->start();  
  20.     }  
  21. }  
  22. myWidget::~myWidget()    
  23. {  
  24.    cvReleaseImage(&iplImg);  
  25.    cvReleaseCapture(&capture);  
  26.    delete qImg;   delete timer;  
  27. }    
  28. void myWidget::paintEvent(QPaintEvent *e)    
  29. {  
  30.    QPainter painter(this);  
  31.    painter.drawImage(QPoint(0,0),*qImg);    
  32. }    
  33. void myWidget::nextFrame()    
  34. {  
  35.    frame = cvQueryFrame(capture);  
  36.    if (frame)  
  37.    {  
  38.     if (frame->origin == IPL_ORIGIN_TL)  
  39.     {  
  40.         cvCopy(frame,iplImg,0);  
  41.     }  
  42.     else  
  43.     {  
  44.         cvFlip(frame,iplImg,0);  
  45.     }  
  46.     cvCvtColor(iplImg,iplImg,CV_BGR2RGB);  
  47.     this->update();  
  48.     }    
  49. }   

主函数里面调用

[cpp] view plaincopy
  1. int main(int argc,char* argv[])    
  2. {  
  3.    QApplication app(argc,argv);  
  4.    char *filename = "test.avi";     
  5.     myWidget *mw = new myWidget(filename);     
  6.     mw->show();  
  7.     int re = app.exec();  
  8.     return re;    
  9. }   
0 0