qt顯示通過opencv顯示攝像頭


qt顯示通過opencv顯示攝像頭

做畢業設計實現這個功能時遇到博客中遇到的不使用imshow就不顯示的問題,經過查找資料通過定時獲取圖像的方法解決了該問題。

以下是主要實現方法 下載地址(qt5.8 vs2013 addin2.0)

頭文件

#pragma once

#include <QtWidgets/QMainWindow>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QStatusBar>
#include <QLabel>
#include "ui_stereovisondemo.h"
#include <opencv2/opencv.hpp>

using namespace cv;

class stereovisondemo : public QMainWindow
{
Q_OBJECT

public:
stereovisondemo(QWidget *parent = Q_NULLPTR);

private:
Ui::stereovisondemoClass ui;

private slots:
void openCaptureClicked();
void showImage();
};

cpp

//#pragma execution_character_set("utf-8")
#include "stereovisondemo.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <Windows.h>
#include <QTimer>
using namespace std;
using namespace cv;

QTimer *timer;
QImage image;
VideoCapture cap;
Mat frame;


void stereovisondemo::display(cv::Mat mat)
{
cv::Mat rgb;
QImage img;
if (mat.channels() == 3)
{
cv::cvtColor(mat, rgb, CV_BGR2RGB);
img = QImage((const uchar*)(rgb.data), rgb.cols, rgb.rows, rgb.cols*rgb.channels(), QImage::Format_RGB888);
}
else
{
img = QImage((const uchar*)(mat.data), mat.cols, mat.rows, mat.cols*mat.channels(), QImage::Format_Indexed8);
}
ui.label1->clear();
ui.label1->setPixmap(QPixmap::fromImage(img));
ui.label1->resize(ui.label1->pixmap()->size());
ui.label1->show();
}

QImage Mat2QImage(cv::Mat cvImg)
{
QImage qImg;
if (cvImg.channels() == 3) //3 channels color image
{

cv::cvtColor(cvImg, cvImg, CV_BGR2RGB);
qImg = QImage((const unsigned char*)(cvImg.data),
cvImg.cols, cvImg.rows,
cvImg.cols*cvImg.channels(),
QImage::Format_RGB888);
}
else if (cvImg.channels() == 1) //grayscale image
{
qImg = QImage((const unsigned char*)(cvImg.data),
cvImg.cols, cvImg.rows,
cvImg.cols*cvImg.channels(),
QImage::Format_Indexed8);
}
else
{
qImg = QImage((const unsigned char*)(cvImg.data),
cvImg.cols, cvImg.rows,
cvImg.cols*cvImg.channels(),
QImage::Format_RGB888);
}

return qImg;

}
stereovisondemo::stereovisondemo(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
timer = new QTimer(this);
/*信號和槽*/
connect(timer, SIGNAL(timeout()), this, SLOT(showImage())); // 時間到,讀取當前攝像頭信息
}

void stereovisondemo::openCaptureClicked()//啟動定時器
{
timer->start(33);
cap.open(0);
}
void stereovisondemo::showImage()
{
cap >> frame;
image = Mat2QImage(frame);
ui.label1->setPixmap(QPixmap::fromImage(image)); // 將圖片顯示到label上
}

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: