1. 程式人生 > >ubuntu下基於qt+opencv控制攝像頭

ubuntu下基於qt+opencv控制攝像頭

環境:ubuntu10.04 + opencv2.2.0 + qt4.7.0

opencv下控制攝像頭是容易的,提供的highgui庫呼叫linux本身的v4l2機制就能控制攝像頭.在這裡我與qt混合程式設計,在qt中開一個30ms的定時器,不斷通過攝像頭捕捉影象,這30ms就是幀速。

捕捉的影象在opencv中是IplImage型別,在qt中呼叫影象一般是QImage型別,所以需要進行一個格式轉換,而且捕捉到的影象顏色是BGR,需要轉換城RGB。攝像頭捕捉的影象顯示視窗為QWidget部件。

原始碼:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include "iostream"
#include "stdio.h"

#include "highgui.h"
#include "cv.h"
#include <QTimer>
#include <QImage>
#include <QPainter>

using namespace std;

#define TIME_OUT    30                  //視訊播放間隔時間
#define FPS         30                  //播放幀率

namespace Ui {
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

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

private:
    Ui::Widget *ui;

    CvCapture *capture;             //視訊資料結構
    IplImage *frame;
    QTimer *timer;
    QImage *img;

private slots:
    void slot_timer();

protected:
    void paintEvent (QPaintEvent *);
};

#endif // WIDGET_H

widget.c
#include "widget.h"
#include "ui_widget.h"

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

    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(slot_timer()));
    timer->start(FPS);

    capture = cvCreateCameraCapture(0);
    //cvNamedWindow("jdh",CV_WINDOW_AUTOSIZE);
}

void Widget::slot_timer()
{
    frame = cvQueryFrame(capture);
    if (!frame)
    {
        return;
    }

    //img->load("test.jpg");
    cvCvtColor(frame,frame,CV_BGR2RGB);
    img = new QImage((unsigned char*)frame->imageData,frame->width,frame->height,frame->widthStep,QImage::Format_RGB888);
    //img = new QImage((unsigned char*)frame->imageData,frame->width,frame->height,QImage::Format_RGB888);
    update();
    //cvShowImage("jdh",frame);
}

void Widget::paintEvent(QPaintEvent * event)
{
    //painter->drawImage(0,0,mm);
    QPainter *pp = new QPainter(this);
    pp->drawImage(0,0,*img);
}

Widget::~Widget()
{
    delete ui;

    cvReleaseImage(&frame);
    //cvDestroyWindow("jdh");
}

效果圖: