由于涉及到相机的采集和opengl的绘制,需要使用第三方库,此处使用了OpenCV和OpenGL库。以下是示例代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <opencv2/opencv.hpp>
#include <GL/glut.h>

using namespace std;
using namespace cv;

const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;

mutex mtx;
bool is_running = true;
vector<Point2f> prev_pts;

void camera_thread(VideoCapture& cap)
{
    Mat frame;
    while (is_running) {
        cap >> frame;
        if (frame.empty()) {
            cerr << "Failed to read frame" << endl;
            break;
        }
        mtx.lock();
        cvtColor(frame, frame, COLOR_BGR2GRAY);
        if (prev_pts.empty()) {
            goodFeaturesToTrack(frame, prev_pts, 500, 0.01, 10);
        } else {
            vector<Point2f> next_pts;
            vector<uchar> status;
            vector<float> error;
            calcOpticalFlowPyrLK(prev_frame, frame, prev_pts, next_pts, status, error);
            prev_pts = next_pts;
        }
        mtx.unlock();
    }
}

void display_thread()
{
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    glutCreateWindow("Speed Display");
    glutDisplayFunc([]() {
        glClear(GL_COLOR_BUFFER_BIT);
        // 绘制速度曲线
        // ...
        glutSwapBuffers();
    });
    while (is_running) {
        mtx.lock();
        // 绘制图像
        // ...
        mtx.unlock();
        glutPostRedisplay();
        glutMainLoopEvent();
    }
}

void match_thread()
{
    while (is_running) {
        mtx.lock();
        // 计算速度
        // ...
        mtx.unlock();
        this_thread::sleep_for(chrono::milliseconds(100));
    }
}

int main()
{
    VideoCapture cap(0);
    if (!cap.isOpened()) {
        cerr << "Failed to open camera" << endl;
        return -1;
    }

    thread camera(camera_thread, ref(cap));
    thread display(display_thread);
    thread match(match_thread);

    while (is_running) {
        if (waitKey(10) == 27) {
            is_running = false;
        }
    }

    camera.join();
    display.join();
    match.join();

    return 0;
}
c++多线程 三个子线程一个子线程调用相机采图一个子线程实时显示图像一个子线程利用opencv特征点匹配计算速度主线程运用opengl实时显示速度并实时绘制速度曲线键盘按下esc程序结束运行c++代码

原文地址: https://www.cveoy.top/t/topic/btff 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录