qt_opencv物体追踪

项目描述:
使用opencv和qt来测试qt的视频流物体追踪的代码

创作不易,如果帮到了你,请点赞关注^^

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
// opencv
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/tracking.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/videoio.hpp>
// file
#include <QFileDialog>
// qt
#include <QDebug>
#include <QTimer>


QT_BEGIN_NAMESPACE
namespace Ui {
    
    
    class MainWindow;
}
QT_END_NAMESPACE

using namespace cv;
class MainWindow : public QMainWindow {
    
    
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_openButton_clicked();

    void importFrame();
private:
    Ui::MainWindow *ui;
    VideoCapture capture;
    QTimer *timer;
};
#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"
cv::Ptr<cv::Tracker> tracker;
// 定义要跟踪的物体矩形框
cv::Rect trackWindow(0, 0, 0, 0);
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    
    
    ui->setupUi(this);

    capture.open(0);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(importFrame()));//import frame when timeout
}

MainWindow::~MainWindow() {
    
    
    delete ui;
}

void MainWindow::on_openButton_clicked() {
    
    
    // 按下按键显示图像,让用户去选择需要追踪的内容
    Mat frame;
    capture >> frame;
    // 进行图像镜像操作
    flip(frame, frame, 1);
    cv::Rect2d roi = cv::selectROI(frame, false);

    // 这个不知道为啥,应该没有用到
//    cv::Mat mask(frame.size(), CV_8UC1, cv::Scalar::all(0));
//    mask(roi).setTo(cv::Scalar::all(255));

    // 关闭 OpenCV 窗口
    cv::destroyAllWindows();

    // 初始化 OpenCV 的物体跟踪器
    tracker = cv::TrackerKCF::create();
    tracker->init(frame, roi);

    timer->start(10);
}

void MainWindow::importFrame() {
    
    
    // 读取下一帧图像
    cv::Mat frame;
    capture >> frame;
    // 进行图像镜像操作
    flip(frame, frame, 1);
    // 跟踪物体位置
    bool ok = tracker->update(frame, trackWindow);

    // 显示物体位置
    if(ok) {
    
    
        cv::rectangle(frame, trackWindow, cv::Scalar(0, 255, 0), 2);
    }

    // 在 QT 窗口上显示物体位置
    cvtColor(frame, frame, COLOR_BGR2RGB);//only RGB of Qt
    QImage srcQImage = QImage((uchar *)(frame.data), frame.cols, frame.rows, QImage::Format_RGB888);
    ui->label->setPixmap(QPixmap::fromImage(srcQImage));
    ui->label->resize(srcQImage.size());
    ui->label->show();
}

猜你喜欢

转载自blog.csdn.net/weixin_44248637/article/details/130576174
今日推荐