Archivos para 17 noviembre 2011

Playing with Qt and OpenCv

In this project I’m going to capture the image from a USB camera, using openCV, and showing all in a QT window.

Let’s started:

The first thing that we have to do, once we have created the project, is to edit the *.pro file, and add our OpenCv paths.

QT       += core gui
 TARGET = untitled
 INCLUDEPATH += /home/opencv_source/trunk/opencv/include/opencv
 LIBS += -L/home/opencv_source/trunk/opencv/release/lib -lml -lcvaux -lhighgui -lcv -lcxcore
 SOURCES += capture.cpp\

HEADERS  +=  capture.h\

FORMS    += mainwindow.ui

I had a problem,  “undefined recerence to vtable” ,that I could fix placing on top capture.h and capture.cpp files.

Once we have ready our environment I’ll explain the content of the files:

– capture: Is the most important file, this class runs in other thread that the GUI, and all that it does is emitting a signal when has a new IplImage from the cam.

Create a new Thread in QT is so easy, all that we have to do is derivate from QThread and implement the virtual method void run()

class Captura : public QThread
 Q_OBJECT              //We need this macro for use Signals mechanism
 void run();
 void newImgAvailable(QImage*);

void Capture::run()

 CvCapture * cap = cvCaptureFromCAM(0);
 if(cap == NULL)
 cout << "There were troubles .. " << endl;
 cout << "Ok" << endl;
 IplImage* imgDisplay;
 imgDisplay = cvQueryFrame(cap);
 QImage* image = IplImage2QImage(imgDisplay);
 emit newImgAvailable(image);

– In mainwindow we are going to create the instance of capture, start it, and connect with our own slots wich will set the image in a QLabel using setPixMap property.

The header:

class MainWindow : public QMainWindow

 explicit MainWindow(QWidget *parent = 0);

public slots:
 void getImg(QImage*);
 Ui::MainWindow *ui;

and the cpp:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),  ui(new Ui::MainWindow)
 Capture* cap = new Capture();               //Create the Thread wich deals with opencv
 connect(cap, SIGNAL(newImgAvailable(QImage*)),this, SLOT(getImg(QImage*)));
 cap->start();  //starting the thread...

void MainWindow::getImg(QImage* img)   //This code will update the image
 delete img;

To avoid memory leaks we have to bear in mind that getImg has to delete the QImage.

Important: We mustn’t release the IplImage* in the loop, because this  is made internally and it would be a mistake


1 comentario