1

I am new at opengl and I try to convert OpenGL texture to OpenCV Mat. But the screen show nothing.

I init opengl texture with:

void InitGlParameter()
{
  GLuint texture;
  if (glIsTexture(texture)) {
    glDeleteTextures(1, &texture);
  }
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 1280, 720, 0, GL_RGBA, GL_FLOAT, 0);
  glBindTexture(GL_TEXTURE_2D, 0);
}

and then I created glWindow and draw something.

  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  glutInitWindowPosition(0, 0);
  glutInitWindowSize(width, height);
  glutCreateWindow("SHOW Pic");

finally, I used glGetTexImage to convert texture to mat.

  cv::Mat img(720, 1280, CV_8UC3);
  glPixelStorei(GL_PACK_ALIGNMENT, 1);
  glPixelStorei(GL_PACK_ROW_LENGTH, (GLint)(img.rows));
  glGetTexImage(GL_TEXTURE_2D, 0, GL_BGR, GL_UNSIGNED_BYTE, img.data);
  cv::flip(img, img, 0); 

However, it show nothing in the opencv windows. Does anyone know where the error is?

1 Answer 1

1

There's a bunch of problems with your code.

This reads an uninitialized local variable:

  GLuint texture;
  if (glIsTexture(texture)) {

This unbinds the texture you just created, therefore it's essentially 'leaked' and you cannot access it afterwards:

  glBindTexture(GL_TEXTURE_2D, 0);

Your code doesn't draw anything into the texture, therefore even if everything was right, you shouldn't expect any meaningful data to be returned.

Additionally, GL_PACK_ROW_LENGTH is the width of the image, so it corresponds to img.cols rather than img.rows.

To fix the above, you should

  • Return the created texture from InitGlParameter.
  • Draw something meaningful into the texture.
  • Bind the texture prior to the glGetTexImage call.
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for answer my question, I will try to fix these bug.
Additionally, what keywords do I need to search if I wanna screenshot that pictures drawn on the window? thanks.
imgur.com/zy23bZr For example, If I draw a checkerboard in the window, are there any methods that I can get this pic?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.