OpenGL——OpenCV与SOIL读取图片进行纹理贴图

使用OpenCV读取图片代码如下

  /*传入的参数
  std::string m_fileName;
  GLenum m_textureTarget = GL_TEXTURE_2D;
  GLuint m_textureObj;
  */
  Mat img = imread(m_fileName);

    if (img.empty())
    {
        fprintf(stderr, "Can not load image %s\n", m_fileName);
        return -1;
    }
    //设置长宽
    int width = img.cols;
    int height = img.rows;
    int channel = img.channels();
    printf(" depth  %d\n", channel);

    //获取图像指针
    int pixellength = width * height * channel;
    GLubyte* pixels = new GLubyte[pixellength];
    memcpy(pixels, img.data, pixellength * sizeof(char));
    //imshow("OpenCV", img);
    

    glGenTextures(1, &m_textureObj);
    glBindTexture(m_textureTarget, m_textureObj);
    //必须一个RGB  一个BGR(opencv的mat类的颜色通道是BGR) 否则会出现颜色偏差
    glTexImage2D(m_textureTarget, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, pixels);
    //纹理放大缩小使用线性插值
    glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);    
    glBindTexture(m_textureTarget, 0);
    free(pixels);

 

运行程序时,出现了两个问题:

  • 纹理贴图是黑白的——解决方案:读取的图片的高和宽的大小改为2的倍数即可
  • 贴图颜色出现偏差——解决方案:(原因见上)
    glTexImage2D(m_textureTarget, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, pixels);

 使用SOIL读取图片代码如下

    int picWidth, picHeight;
    int channel = 0;

    unsigned char* imageData = SOIL_load_image(m_fileName.c_str(), &picWidth, &picHeight, &channel, SOIL_LOAD_RGB);

    if (imageData == NULL)
    {
        fprintf(stderr, "Can not load image ");
        std::cout << m_fileName << "\n";
        return false;
    }
    
    //产生指定数量的纹理对象,并将他们的引用句柄放到GLuint数组指针中
    glGenTextures(1, &m_textureObj);
   //告诉OpenGL后面所有和纹理相关调用中所引用的是该次绑定的纹理对象,直到新的对象被绑定
    glBindTexture(m_textureTarget, m_textureObj);
    glTexImage2D(m_textureTarget, 0, GL_RGB, picWidth, picHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
    //纹理放大缩小使用线性插值
    glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);    
    glBindTexture(m_textureTarget, 0);
    SOIL_free_image_data(imageData);

 

posted @ 2018-09-03 22:47  Not-Bad  阅读(1937)  评论(0编辑  收藏  举报