如何在ImGUI中将cv::Mat转换为ImTextureID及适配正确库版本
问题:OpenCV渲染图像无法在ImGUI中正常显示
我开发了一个渲染应用,基础帧缓冲定义如下:
std::vector<Eigen::Vector3f> frame_buffer;
通过OpenCV完成渲染显示的代码运行完全正常:
pipeline.refresh(); pipeline.draw(); cv::Mat image(700, 700, CV_32FC3, pipeline.raster.frameBuffer().data()); image.convertTo(image, CV_8UC3, 1.0f); cv::cvtColor(image, image, cv::COLOR_RGB2BGRA); cv::imshow("image", image);
但尝试将渲染结果在ImGUI中显示时,编写的转换及显示代码无法正常运行,相关代码如下:
UI.h中的显示循环代码
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <opencv2/opencv.hpp> // 显示循环 while (!glfwWindowShouldClose(windows)){ glfwPollEvents(); // 启动ImGui帧 ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); // 创建ImGui窗口 ImGui::Begin("LRenderer"); pipeline.refresh(); pipeline.draw(); cv::Mat image(700, 700, CV_32FC3, pipeline.raster.frameBuffer().data()); image.convertTo(image, CV_8UC3, 1.0f); cv::cvtColor(image, image, cv::COLOR_RGB2BGRA); Mat2Texture(image, image_texture); ImGui::Image((void*)(intptr_t)image_texture, ImVec2(image.cols, image.rows)); ImGui::End(); // 渲染ImGui内容 ImGui::Render(); int display_w, display_h; glfwGetFramebufferSize(windows, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); const ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { GLFWwindow* backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); glfwMakeContextCurrent(backup_current_context); } glfwSwapBuffers(windows); }
cv::Mat转OpenGL纹理的函数代码
void LRenderer::UI::Mat2Texture(const cv::Mat& image, GLuint& imageTexture) { if (image.empty()) { std::cout << "image is empty! " << std::endl; return; } else { // 生成OpenGL纹理 glGenTextures(1, &image_texture); glBindTexture(GL_TEXTURE_2D, imageTexture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA, image.cols, image.rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.data); } }
我当前使用GLFW 3.3、GLEW 4.6(均为最新版本),也曾尝试使用对应版本的GLAD,但都无法正常运行。
请问:
- 如何解决图像无法在ImGUI中显示的问题?
- 适配的库版本应该选择哪一组?
- 正确的cv::Mat转ImTextureID的实现方法是什么?
内容的提问来源于stack exchange,提问作者Interesting
相关产品推荐
相关产品推荐

