QT学习之usb摄像头采集(Opencv+QT)[cvCapture,IplImage,QImage]
参考自:http://blog.chinaunix.net/uid-23381466-id-3826748.html
将Opencv中的cvCaptureFromCAM不断获得摄像头采集到的图像数据,
QT中通过QImage,QPixMap,label控件显示图像到dlg的窗口中.
还用到了一个定时器间隔的从摄像头获得图像进行显示.
(这种实时图像处理的程序,要么定时器,要么多线程,最好不要用sleep这种~)
创建QT widgets工程,起名 mywindow
俩按钮,一个label控件,save暂时没用到
头文件:
mywindow.h
#ifndef MYWINDOW_H #define MYWINDOW_H #include <QMainWindow> #include <QtCore> #include <QLabel> #include <QTime> #include <opencv2/opencv.hpp> namespace Ui { class myWindow; } class myWindow : public QMainWindow { Q_OBJECT public: explicit myWindow(QWidget *parent = 0); ~myWindow(); private slots: void on_pushButton_clicked(); void getOneFrame(); private: Ui::myWindow *ui; IplImage* pFrame; CvCapture* pCap; int startedFlag; QTimer *timer; //QLabel *label; }; #endif // MYWINDOW_H
mywindow.cpp:
#include "mywindow.h" #include "ui_mywindow.h" #include <opencv2/opencv.hpp> myWindow::myWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::myWindow) { ui->setupUi(this); startedFlag = false; timer = new QTimer(this); pCap = NULL; pFrame = NULL; connect(timer, SIGNAL(timeout()), this, SLOT(getOneFrame())); } myWindow::~myWindow() { delete ui; } void myWindow::getOneFrame() { pFrame = cvQueryFrame(pCap); QImage img = QImage((uchar*)pFrame->imageData, pFrame->width,pFrame->height, pFrame->widthStep, QImage::Format_RGB888).rgbSwapped(); int height = img.height()/2; int width = img.width()/2; ui->label->resize(width, height); ui->label->setPixmap(QPixmap::fromImage(img.scaled(width,height)));//将图像长宽缩放一半显示 } void myWindow::on_pushButton_clicked() { if (startedFlag == false) { startedFlag = true; ui->pushButton->setText("stop"); pCap = cvCaptureFromCAM(0); timer->start(33); }else { startedFlag = false; ui->pushButton->setText("start"); timer->stop(); cvReleaseCapture(&pCap); ui->label->clear(); } }
main.cpp:
#include "mywindow.h" #include <QApplication> #include <opencv2/opencv.hpp> int main(int argc, char *argv[]) { QApplication a(argc, argv); myWindow w; w.show(); return a.exec(); }
Trouble is a Friend