Friday, 31 October 2014

Capturing OpenGL Rendered window using OpenCV

When working with graphics I wanted to store whatever was on the output of my OpenGL render window as a set of images. Typically this is achieved by using glReadPixels to read the pixels in the rendered window and store them into a byte array. This array is then converted and saved using a helper library.

I thought of doing the same thing, however, since I am more familiar with OpenCV, I wanted to use cv::Mat to do this.

Turns out it is really straight foward, all you need to do is to initialize the Mat with the required size and store the data directly onto its data container. Here is the code:

//Get dimensions of the image
RECT dimensions = rGameWindow.GetDimensions();
int width = dimensions.right - dimensions.left;
int height = dimensions.bottom -; 

// Initialise a Mat to contain the image
cv::Mat temp = cv::Mat::zeros(height, width, CV_8UC3); cv::Mat tempImage;   

// Read Image from buffer
glReadPixels(0,0, width, height, GL_RGB, GL_UNSIGNED_BYTE,;

// Process buffer so it matches correct format and orientation
cv::cvtColor(temp, tempImage, CV_BGR2RGB); 
cv::flip(tempImage, temp, 0);

// Write to file
cv::imwrite("savedWindow.png", temp);

Thats all! You do need to do some data conversions to match the format of OpenCV images, but its pretty straightforward and self explanatory.

No comments:

Post a Comment