寫在前面
本案例用QWidget容器重寫paintEvent函數(shù)來顯示OpenCv采集的攝像頭畫面,圖像還可以自適應(yīng)QWidget的大小,還可以檢測相機(jī)斷開失聯(lián)的情況(可能是掉電、線被拔了等待)。在改變窗口大小時(shí)暫停顯示圖像,防止莫名其妙的卡頓奔潰錯(cuò)誤?。@示圖像的方式有很多種,可以用QLabel顯示圖像,雖然簡單但是對于這種視頻畫面不建議用QLabel;還可以用QGraphicsView顯示,下一篇文章更新)
一、新建工程
1、新建一個(gè)Qt工程,在UI中添加一個(gè)Widget容器和兩個(gè)按鈕,并添加合適的布局。把Widget的ObjectName設(shè)置為CameraWidget
,兩個(gè)按鈕分別是“打開相機(jī)openCamera
”、“關(guān)閉相機(jī)closeCamera
”
2、新建一個(gè)任務(wù)類,用于Opencv采集攝像頭圖像并發(fā)送信號(hào)。用moveToThread將該任務(wù)類添加到子線程中。
3、在Qt中新建一個(gè)類CameraWidget繼承QWidget,并將UI中的Widget控件提升為該類。
二、采集圖像
1、在Qt項(xiàng)目中配置OpenCv環(huán)境(本文默認(rèn)您已經(jīng)配置完成,否則看我另一篇文章:QT配置opencv346環(huán)境(MinGw編譯器)。
2、新建一個(gè)任務(wù)類,該類主要的任務(wù)是:采集圖像、發(fā)送信號(hào),關(guān)閉相機(jī)退出線程。
3、代碼如下
Camera.h
#ifndef CAMERA_H
#define CAMERA_H
#include <QObject>
#include <QTimer>
#include <QPixmap>
#include <opencv2/opencv.hpp>
using namespace cv;
class Camera : public QObject
{
Q_OBJECT
public:
explicit Camera(QObject *parent = nullptr);
void openCamera(); // 打開相機(jī)
void closeCamera(); // 關(guān)閉相機(jī)
private:
VideoCapture *cap; // 相機(jī)
QTimer *capTimer; // 采集圖像定時(shí)器
bool cameraIsOpened = false; // 相機(jī)打開標(biāo)志位
signals:
void cameraShowImage(QPixmap); // 發(fā)送圖像信號(hào)
void cameraIsOpen(bool); // 相機(jī)打開信號(hào)
};
#endif // CAMERA_H
Camera.cpp
#pragma execution_character_set("utf-8")
#include "camera.h"
#include <QDebug>
#include <QThread>
Camera::Camera(QObject *parent) : QObject(parent)
{
}
void Camera::openCamera()
{
qDebug() << "子線程:" << QThread::currentThreadId();
// 打開相機(jī)
int cameraDevId = 0;
this->cap = new VideoCapture;
this->cap->open(cameraDevId, cv::CAP_DSHOW); // 必須帶上 CAP_DSHOW ,否則會(huì)報(bào)錯(cuò) [ WARN:1] terminating async callback,然后再次打開就打不開了
if(!this->cap->isOpened()){
this->cap->release(); // 釋放相機(jī)
qDebug() << "相機(jī)打開失??!";
return;
}
this->cameraIsOpened = true;
emit this->cameraIsOpen(true); // 相機(jī)打開
qDebug() << QString("相機(jī)參數(shù): (%1, %2), %3 FPS").arg(cap->get(3)).arg(cap->get(4)).arg(cap->get(5));
this->capTimer = new QTimer;
connect(this->capTimer, &QTimer::timeout, [=]() {
// qDebug() << "子線程:" << QThread::currentThreadId();
Mat frame;
// 采集圖像
this->cap->read(frame);
if(frame.empty()){
qDebug() << "相機(jī)可能斷開";
this->closeCamera(); // 關(guān)閉相機(jī)
return ;
}
// 將OpenCv的BGR圖像轉(zhuǎn)換成正常的RGB圖像
cvtColor(frame, frame, cv::COLOR_BGR2RGB);
// 將OpenCv的圖像轉(zhuǎn)換成Qt的QImage
QPixmap showImage = QPixmap::fromImage(QImage((const uchar*)(frame.data),
frame.cols,
frame.rows,
frame.step,
QImage::Format_RGB888));
// 將QPixmap圖像通過信號(hào)發(fā)送出去
emit this->cameraShowImage(showImage);
});
// 采樣時(shí)間可以根據(jù)相機(jī)的FPS修改
this->capTimer->start(40);
}
void Camera::closeCamera()
{
qDebug() << "子線程:" << QThread::currentThreadId();
if(!this->cameraIsOpened) return;
if(this->capTimer->isActive()){
this->capTimer->stop();
this->capTimer->deleteLater();
this->cameraIsOpened = false;
emit this->cameraIsOpen(false); // 相機(jī)關(guān)閉
this->cap->release(); // 釋放相機(jī)
cv::destroyAllWindows(); // 銷毀OpenCv的窗口
}
}
三、顯示圖像
1、新建一個(gè)類繼承QWidget,并將UI中的Widget控件提升為該類。
2、重寫paintEvent函數(shù),根據(jù)widget的大小對圖像進(jìn)行縮放并繪制;設(shè)計(jì)一個(gè)變量showCameraImage
,如果為true
時(shí)才顯示繪制圖像。
3、新建一個(gè)定時(shí)器,重寫resizeEvent函數(shù);在窗口大小變化將showCameraImage
設(shè)置為false
,然后不斷刷定時(shí)器。當(dāng)窗口大小不再變化,定時(shí)器不刷新,時(shí)間到了之后將showCameraImage
設(shè)置為true
重新繪制圖像。
4、創(chuàng)建幾個(gè)成員函數(shù)用來更新圖像。
5、代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-538244.html
CameraWidget.h
#ifndef CAMERAWIDGET_H
#define CAMERAWIDGET_H
#include <QWidget>
#include <QTimer>
#include <QPixmap>
class CameraWidget : public QWidget
{
Q_OBJECT
public:
explicit CameraWidget(QWidget *parent = nullptr);
void showImage(bool b); // 顯示圖像
void setImage(QPixmap img); // 更新圖像
protected:
void resizeEvent(QResizeEvent *event) override;
void paintEvent(QPaintEvent *event) override;
private:
QPixmap cvImage; // 相機(jī)圖像
QTimer *noShowCameraImage; // 不顯示圖像定時(shí)器
bool showCameraImage = true; // 顯示圖像
bool camerIsOpened = false; // 相機(jī)打開
signals:
};
#endif // CAMERAWIDGET_H
CameraWidget.cpp
#pragma execution_character_set("utf-8")
#include "camerawidget.h"
#include <QDebug>
#include <QPainter>
#define CAMERA_IMAGE_WIDTH 640
#define CAMERA_IMAGE_HEIGHT 480
CameraWidget::CameraWidget(QWidget *parent) : QWidget(parent)
{
this->noShowCameraImage = new QTimer;
connect(this->noShowCameraImage, &QTimer::timeout, this, [=](){
this->showCameraImage = true;
this->noShowCameraImage->stop();
this->update();
});
this->update();
}
void CameraWidget::showImage(bool b)
{
this->camerIsOpened = b;
update();
}
void CameraWidget::setImage(QPixmap img)
{
this->cvImage = img;
update();
}
/**********************************************************
* @brief label大小變化事件
**********************************************************/
void CameraWidget::resizeEvent(QResizeEvent *event)
{
this->showCameraImage = false;
// 定時(shí)器刷新時(shí)間,當(dāng)窗口大小不變后多長時(shí)間恢復(fù)圖像
// 這涉及到用戶體驗(yàn),設(shè)置適當(dāng)?shù)闹导纯?/span>
this->noShowCameraImage->setInterval(200);
this->noShowCameraImage->start();
QWidget::resizeEvent(event);
}
void CameraWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
// 背景顏色
painter.setPen(QColor(192, 192, 192));
painter.setBrush(QColor(192, 192, 192));
painter.drawRect(0, 0, this->width(), this->height());
// 等比縮放,繪制圖像
if(this->showCameraImage && this->camerIsOpened){
// 尋找圖像大小和widget大小的縮放關(guān)系
QRectF imgRect = this->cvImage.rect();
QRectF widgetRect = this->rect();
double factor = qMin(widgetRect.width() / imgRect.width(), widgetRect.height() / imgRect.height());
// 計(jì)算新的Rect
int imgWidth = imgRect.width() * factor;
int imgHeight = imgRect.height() * factor;
int startX = (this->width() - imgWidth) / 2;
int startY = (this->height() - imgHeight) / 2;
// 顯示圖像
painter.drawPixmap(startX, startY, imgWidth, imgHeight, this->cvImage);
}
QWidget::paintEvent(event);
}
四、主窗口
在主線程里面主要是創(chuàng)建子線程已經(jīng)信號(hào)槽綁定。文章來源地址http://www.zghlxwxcb.cn/news/detail-538244.html
#pragma execution_character_set("utf-8")
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug() << "主線程:" << QThread::currentThreadId();
// 相機(jī)子線程
this->camera = new Camera;
this->cameraThread = new QThread;
this->camera->moveToThread(this->cameraThread);
connect(this->cameraThread, &QThread::finished, this->cameraThread, &QThread::deleteLater);
connect(this->cameraThread, &QThread::finished, this->camera, &Camera::deleteLater);
connect(this->camera, &Camera::cameraShowImage, ui->cameraWidget, &CameraWidget::setImage); // 更新圖像
this->cameraThread->start();
connect(ui->openCamera, &QPushButton::clicked, this->camera, &Camera::openCamera); // 打開相機(jī)
connect(ui->closeCamera, &QPushButton::clicked, this->camera, &Camera::closeCamera); // 關(guān)閉相機(jī)
connect(this->camera, &Camera::cameraIsOpen, ui->cameraWidget, &CameraWidget::showImage);
}
MainWindow::~MainWindow()
{
if(this->cameraThread->isRunning()){
this->cameraThread->quit();
this->cameraThread->wait();
}
delete ui;
}
到了這里,關(guān)于【Qt】用QWidget顯示opencv采集的攝像頭圖像的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!