opengl截图时原点在图像的左下角, 因此数据的顺序是这样的:
但是opencv中图像的原点是在左上角的, 因此opengl输出的图给opencv的时候opencv还是以为图像的数据是从上到下排列的, 这样就会造成使用opencv输出后图像是倒着的,需要我们手动翻转数据
另一个问题, opencv中图像的像素排列为BGR, 因此在opengl截图的时候也要指定输出图像像素排列方式
GLubyte *pixels = (GLubyte *)malloc(3*settings->screen_width*settings->screen_height
* sizeof(GL_FLOAT));
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, settings->screen_width,
settings->screen_height, GL_BGR, GL_UNSIGNED_BYTE, pixels);
cv::Mat img(settings->screen_height, settings->screen_width, CV_8UC3, pixels);
cv::Mat img_to_write(settings->screen_height, settings->screen_width, CV_8UC3);
GLubyte* p_src, *p_dst;
for (int step = 0; step != settings->screen_height; ++step)
{
p_src = img.ptr<GLubyte>(step);
p_dst = img_to_write.ptr<GLubyte>(settings->screen_height-step-1);
for (int step1 = 0; step1 != settings->screen_width*3; ++step1)
{
p_dst[step1] = p_src[step1];
}
}
cv::imwrite(“aa.png”, img_to_write);