使用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);
