代码如下,在pro中加入opencv的include和lib
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimer>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
using namespace cv;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void readFarme();
private slots:
void on_openCamera_clicked();
void on_closeCamera_clicked();
private:
Ui::Widget *ui;
Mat image;
VideoCapture* m_videoCapture;
QTimer* m_timer;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QPixmap>
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//打开摄像头,从摄像头中获取视频
m_videoCapture = new VideoCapture(0);
m_timer = new QTimer();
connect(m_timer, SIGNAL(timeout()), this, SLOT(readFarme()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::readFarme()
{
m_videoCapture->read(image);
cv::cvtColor(image, image, CV_BGR2RGB);
QImage img = QImage((const unsigned char*)image.data, image.cols,
image.rows, QImage::Format_RGB888);
int w = ui->cameraShow->width(); //textLabel
int h = ui->cameraShow->height();
QImage im = img.scaled(w, h);
ui->cameraShow->setPixmap(QPixmap::fromImage(im));
ui->cameraShow->resize(ui->cameraShow->pixmap()->size());
}
void Widget::on_openCamera_clicked()
{
//开启定时器, 33ms刷新一次
m_timer->start(33);
}
void Widget::on_closeCamera_clicked()
{
m_timer->stop();
m_videoCapture->release();
QApplication* app;
app->exit(0);
}