现代opengl 设计入门,opencv 纹理贴图

在 现代opengl 设计入门,纹理贴图 一文中介绍了用 stb_image.h 导入图片来实现openGL 的纹理贴图,而本文介绍另外一种方式opencv。 OpenCV是Intel®开源计算机视觉库,图像处理功能很强大。如果你熟悉opencv,或者正在使用,在做openGL 贴图的时候,肯定想如何组合。

如果你对opencv 不熟悉,那你还是用stb_image.h 导入图片比较简单。opencv的好处是,你可以利用opencv超强的处理图片,比如变换灰度图,或者自画图,这样灵活性比较好。我的测试环境是visual studio 2010 c++,  opencv 3.0 beta。更高级的oepncv 版本在2010 下需要自己编译。

opencv 导入图片,设置为opengl 贴图很简单,就是下面的代码:

cv::Mat image = cv::imread( "lena.jpg", 1 );
if(image.elemSize()>0)
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.cols,image.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, image.data);

对于opengl 工程而言,其他要做的是添加opencv 应用必要的包含文件,链接库,设置文件路径,运行时动态库。当然还有重要一点,你先要安装好opencv3.0beta 以上版本,否则本文方法要些修改。

#include "opencv2/opencv.hpp"

在工程属性里添加opencv 的路径,我的是

include: C:\opencv\build\include;  

lib: C:\opencv\build\x86\vc10\lib;

图示如下:

现代opengl 设计入门,opencv 纹理贴图_第1张图片

链接时输入函数库添加:opencv_ts300d.lib; opencv_world300d.lib

原来opengl 本来包含 glfw3d.lib opendl32.lib

图示如下:

现代opengl 设计入门,opencv 纹理贴图_第2张图片

复制 opencv_world300d.dll,opencv_world300.dll 到你运行目录。

其他的都与  现代opengl 设计入门,纹理贴图  一文相似。

运行效果图,这个和上篇一样,只是纹理导入方式 不一样。opencv的好处是,你可以处理图片,比如变换灰度图,或者自画图,这样灵活性比较好。

现代opengl 设计入门,opencv 纹理贴图_第3张图片

代码,调试说明

要完成本工程的代码调试和运行要注意如下几点:

代码有好几个文件,着色器类shader_s.h 在这里,4.1.texture.vs,4.1.texture.fs在后面贴出了,主程序也在后面。

所有程序文件都准备好了,应该可以 编译链接成功了,如果不成功, 请看 现代opengl 设计入门 准备第一个工程 可能你GLFW, GLAD,包含路径,库文件没有设置好,glad.c文件没有加入工程。

调试运行时,你要准备好你的顶点着色器文件4.1.texture.vs,片段着色器文件4.1.texture.fs,还有纹理贴图文件lena.jpg。纹理贴图文件你可以找一个bmp,png,jpg 等等图片文件,然后你要修改主程序中贴图文件的名字,如果不是lena.jpg。这三个文件在程序运行时要打开,你可以放在一个目录里,然后在那个目录(工作目录)里运行。debug 的话,需修改工程属性:Configuration Properties-> Debugging->Working Drirectory,指向这三个文件在的目录,如下图:

现代opengl 设计入门,opencv 纹理贴图_第4张图片

如果你不想这么设置,也可以用绝对路径。

如果你运行有驱动问题,请查看现代 opengl 的驱动安装。

附录3个文件
4.1.texture.vs 文件内容:

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
 out vec3 ourColor;
out vec2 TexCoord;
 void main()
{
    gl_Position = vec4(aPos, 1.0);
    ourColor = aColor;
    TexCoord = aTexCoord;
}


4.1.texture.fs 文件内容: 

#version 330 core
out vec4 FragColor; 
in vec3 ourColor;
in vec2 TexCoord;
uniform sampler2D ourTexture; 
void main()
{
    FragColor = texture(ourTexture, TexCoord);
}

程序源代码openglA.cpp:
 

#include 
#include 
//#define STB_IMAGE_IMPLEMENTATION
//#include 

#include 

#include 

#include "opencv2/opencv.hpp"

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // build and compile our shader zprogram
    // ------------------------------------
    Shader ourShader("4.1.texture.vs", "4.1.texture.fs"); 

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float vertices[] = {
        // positions          // colors           // texture coords
         0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 0.0f, // top right
         0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 1.0f, // bottom right
        -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 1.0f, // bottom left
        -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 0.0f  // top left 
    };
    unsigned int indices[] = {  
        0, 1, 3, // first triangle
        1, 2, 3  // second triangle
    };
    unsigned int VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    // color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    // texture coord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);


    // load and create a texture 
    // -------------------------
    unsigned int texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	// set texture wrapping to GL_REPEAT (default wrapping method)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    //int width, height, nrChannels;
    // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
    /*unsigned char *data = stbi_load(("lena.jpg"), &width, &height, &nrChannels, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);*/
	cv::Mat image = cv::imread( "lena.jpg", 1 );
	if(image.elemSize()>0)
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.cols,image.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, image.data);


    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // bind Texture
        glBindTexture(GL_TEXTURE_2D, texture);

        // render container
        ourShader.use();
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}

// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and 
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

 

你可能感兴趣的:(c++,opengl,opengl,opencv,glfw,glad,纹理贴图)