Jav_Rock Jav_Rock - 11 months ago 60
C++ Question

Loading texture for OpenGL with OpenCV

I have seen many code samples for loading textures for OpenGL, many of them a bit complicated to understand or requiring new functions with a lot of code.

I was thinking that as OpenCV allows us to load any image format it can be a simple an efficient way to load textures to OpenGL, but I am missing something. I have this piece of code in c++:

cv::Mat texture_cv;
GLuint texture[1];
int Status=FALSE;

if( texture_cv = imread("stones.jpg")) {

Status=TRUE; // Set The Status To TRUE
glGenTextures(1, &texture[0]); // Create The Texture

glBindTexture(GL_TEXTURE_2D, texture[0]);

glTexImage2D(GL_TEXTURE_2D, 0, 3, texture_cv.cols, texture_cv.rows, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_cv.data);

And it is not compiling because of this error:

error C2451: conditional expression of type 'cv::Mat' is illegal

Any suggestions? How should I do the conversion from cv::Mat to openGL texture?

Answer Source

Your error appears there, right?

if( texture_cv = imread("stones.jpg"))  {

because in if(expr) expr must be bool or can be casted to bool. But there is no way to convert cv::Mat into boolean implicitly. But you can check the result of imread like that:

texture_cv = imread("stones.jpg");
if (texture_cv.empty()) {
  // handle was an error
} else {
  // do right job

See: cv::Mat::empty(), cv::imread

Hope that helped you.