To Save OpenGL ViewPort to Image File (glReadPixels, OpenGL->OpenCV)


You can save the Viewport of OpenGL to Image file using glReadPixels function.
And this code is example for saving image file using openCV.
Thank you.

void CaptureViewPort()
{
 
 GLubyte * bits; //RGB bits
 GLint viewport[4]; //current viewport
  
 //get current viewport
 glGetIntegerv(GL_VIEWPORT, viewport);

 int w = viewport[2];
 int h = viewport[3];
 
 bits = new GLubyte[w*3*h];

 //read pixel from frame buffer
 glFinish(); //finish all commands of OpenGL
 glPixelStorei(GL_PACK_ALIGNMENT,1); //or glPixelStorei(GL_PACK_ALIGNMENT,4);
 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
 glPixelStorei(GL_PACK_SKIP_ROWS, 0);
 glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
 glReadPixels(0, 0, w, h, GL_BGR_EXT, GL_UNSIGNED_BYTE, bits);

 IplImage * capImg = cvCreateImage( cvSize(w,h), IPL_DEPTH_8U, 3);
 for(int i=0; i < h; ++i)
 {
  for(int j=0; j < w; ++j)
  {
   capImg->imageData[i*capImg->widthStep + j*3+0] = (unsigned char)(bits[(h-i-1)*3*w + j*3+0]);
   capImg->imageData[i*capImg->widthStep + j*3+1] = (unsigned char)(bits[(h-i-1)*3*w + j*3+1]);
   capImg->imageData[i*capImg->widthStep + j*3+2] = (unsigned char)(bits[(h-i-1)*3*w + j*3+2]);
  }
 }

 cvSaveImage("result.jpg",capImg); 
 cvReleaseImage(&capImg); 
 delete[] bits; 
 
}

Comments

Post a Comment

Popular posts from this blog

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

OpenCV Stitching example (Stitcher class, Panorama)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Real-time N camera stitching Class.

Optical Flow sample source code using OpenCV

OpenCV Drawing Example, (line, circle, rectangle, ellipse, polyline, fillConvexPoly, putText, drawContours)

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)

SICK LMS511 sensor data acquisition interface (source code, C++/MFC)

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

Image warping (using opencv findHomography, warpPerspective)