ZBLOG

使用opencv读取图片,然后使用glfw加载到纹理渲染,并把这个纹理缩放1/2后显示的例子

以下是一个使用OpenCV读取图片,然后使用GLFW加载到纹理渲染并缩放1/2后显示的例子:

#include <iostream>
#include <opencv2/opencv.hpp>
#include <GLFW/glfw3.h>

// GLFW窗口大小
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;

void errorCallback(int error, const char* description) {
    std::cout << "GLFW Error: " << description << std::endl;
}

int main() {
    // 初始化GLFW
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit()) {
        std::cout << "Failed to initialize GLFW" << std::endl;
        return -1;
    }

    // 创建窗口
    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Image Texture", nullptr, nullptr);
    if (!window) {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    
    glfwMakeContextCurrent(window);

    // 初始化OpenGL
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    
     // 加载图片并创建纹理
     cv::Mat image = cv::imread("image.jpg");  // 替换成你要读取的图片路径和名称
    
     if (image.empty()) {
         std::cout << "Failed to load image" << std::endl;
         glfwTerminate();
         return -1;
     }
     
     cv::resize(image, image, cv::Size(image.cols / 2, image.rows / 2)); // 缩放图像
     
     GLuint textureID;
     glGenTextures(1, &textureID);
     
     glBindTexture(GL_TEXTURE_2D, textureID);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
     
     glTexImage2D(GL_TEXTURE_2D,
                  0,
                  GL_RGB,
                  image.cols,
                  image.rows,
                  0,
                  GL_BGR_EXT,
                  GL_UNSIGNED_BYTE,
                  image.ptr());
                  
    // 渲染循环
    while (!glfwWindowShouldClose(window)) {
        // 清空缓冲区
        glClear(GL_COLOR_BUFFER_BIT);

        // 绘制纹理
        glEnable(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D, textureID);
        
        glBegin(GL_QUADS);
        {
            glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 0.0f);
            glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 0.0f);
            glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f);
            glTexCoord2f(0.0f, 0.0); glVertex3d(-1.5,-1.,-10.);
          }
          glEnd();
      
        // 刷新窗口
        glfwSwapBuffers(window);

       // 检查并处理事件
       glfwPollEvents();
   }

   // 清理资源
   glDeleteTextures(1, &textureID);
   glfwTerminate();
  
   return 0;
}

请确保在编译时链接了OpenCV和GLFW库,并将代码中的图片路径替换为你要加载的图片路径。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9084

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?