ZBLOG

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

下面是一个使用OpenCV读取图片,然后使用GLFW加载到纹理,并将纹理缩放1/2后显示的示例代码:

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

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

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

    // 创建窗口和OpenGL上下文
    GLFWwindow* window = glfwCreateWindow(800, 600, "Image Texture", nullptr, nullptr);
    if (!window) {
        std::cerr << "Failed to create GLFW window." << std::endl;
        glfwTerminate();
        return -1;
    }
    
    glfwMakeContextCurrent(window);

    // 加载图片并创建纹理
    cv::Mat image = cv::imread("path_to_your_image.jpg");
    if (image.empty()) {
        std::cerr << "Failed to load image." << std::endl;
        glfwTerminate();
        return -1;
    }

    cv::resize(image, image, cv::Size(image.cols / 2, image.rows / 2));  // 缩放图片

    GLuint textureID;  // 纹理ID
	glGenTextures(1, &textureID);  // 创建纹理对象
	glBindTexture(GL_TEXTURE_2D, textureID);  // 绑定纹理

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);  
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	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.data);

	// 设置纹理坐标
	GLfloat texCoords[] = {
	    0.0f, 1.0f,
	    1.0f, 1.0f,
	    1.0f, 0.0f,
	    0.0f, 0.0f
	};

    // 设置顶点数据
    GLfloat vertices[] = {
        -1.0f, -1.0f,
         1.0f,-1.0f,
         1.0f, 1.0f,
        -1.0f ,1.0f
    };

    // 设置索引数据
    GLuint indices[] = {
        3 ,2 ,1 ,
        3 ,1 ,4 
    };
    
    glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glVertexPointer(2,GL_FLOAT , sizeof(vertices[8]) * sizeof(float), vertices);
	glTexCoordPointer(2,GL_FLOAT,sizeof(texCoords[8]) * sizeof(float),texCoords);
	glBindTexture(GL_TEXTURE_2D , textureID);

	while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT);

		glColor3ub(255 ,255 ,255);
		glDrawElements(GL_TRIANGLES ,6 ,GL_UNSIGNED_INT ,(GLvoid*)indices);

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

    // 清除资源并退出
    glDeleteTextures(1, &textureID);
    glfwTerminate();

    return 0;
}

请确保你已经安装了OpenCV和GLFW,并将图片路径替换为实际的图片路径。此示例使用的是OpenGL固定管线,如果需要更复杂的渲染,请参考相关OpenGL教程和文档。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?