下面是一个使用OpenCV读取图片,然后使用GLFW加载到纹理,并将纹理缩放为原来的一半后显示的示例代码:
#include <iostream>
#include <GLFW/glfw3.h>
#include <opencv2/opencv.hpp>
// 定义窗口大小
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main()
{
// 初始化 GLFW
if (!glfwInit())
{
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
// 创建窗口并设置相关属性
GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Image Texture", nullptr, nullptr);
if (!window)
{
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// 设置视口大小回调函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// 加载图像
cv::Mat image = cv::imread("your_image_path.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)); // 缩小为原来的一半
int textureWidth = image.cols;
int textureHeight = image.rows;
GLuint textureID; // 纹理ID
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, image.data);
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);
// 渲染循环
while (!glfwWindowShouldClose(window))
{
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// 绑定纹理并绘制一个矩形
glBindTexture(GL_TEXTURE_2D, textureID);
float vertices[] = {
// positions // texture coords
0.5f,-0.5f,-1.0f , 1.0f , 1.0f,
-0.5f,-0.5f,-1.0f , 0.0f , 1.0f,
0.5f,-1.f ,-1.f , 1.f , 0.f ,
-0.f ,-1.f ,-1.f , .00001,.00001,
};
unsigned int indices[] = {
3, 1,//上
// 下面两个是右上的两个点
2,//左下角对应纹理坐标(最左边)
// 右上角对应纹理坐标(最右边)
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(float) * 5, vertices);
glTexCoordPointer(2, GL_FLOAT, sizeof(float) * 5, &vertices[3]);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawElements(GL_TRIANGLE_STRIP,sizeof(indices)/sizeof(unsigned int),GL_UNSIGNED_INT,&indices[0]);
glfwSwapBuffers(window);
glfwPollEvents();
}
// 清理
glDeleteTextures(1, &textureID);
glfwTerminate();
return 0;
}
确保你已经正确安装了OpenGL、GLFW和OpenCV库,并将”your_image_path.jpg”替换为你要加载的图像路径。运行代码后,应该会弹出一个窗口显示缩放后的图像纹理。
内容由零声教学AI助手提供,问题来源于学员提问