Created
June 20, 2020 05:00
-
-
Save marty958/943cf881fd36bd185877e14dde18ff32 to your computer and use it in GitHub Desktop.
Save a OpenGL widow image with OpenCV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <OpenGL/OpenGL.h> | |
#include <GLUT/GLUT.h> | |
#include "opencv2/opencv.hpp" | |
#include "opencv2/highgui.hpp" | |
#include "opencv2/imgcodecs.hpp" | |
const int WindowSize = 600; | |
void display(void){ | |
glViewport(0, 0, WindowSize*2, WindowSize*2); //twice the size for Mac Retina display | |
glClear(GL_COLOR_BUFFER_BIT); | |
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | |
glutWireTeapot(0.5); | |
glFlush(); | |
} | |
void SaveImage(){ | |
const int imageWidth = WindowSize*2; //twice the size for Mac Retina display | |
const int imageHeight = WindowSize*2; //twice the size for Mac Retina display | |
const unsigned int channelNum = 4; // RGBなら3, RGBAなら4 | |
void* dataBuffer = NULL; | |
dataBuffer = (GLubyte*)malloc(imageWidth * imageHeight * channelNum); | |
// 読み取るOpneGLのバッファを指定 GL_FRONT:フロントバッファ GL_BACK:バックバッファ | |
glReadBuffer(GL_BACK); | |
// OpenGLで画面に描画されている内容をバッファに格納 | |
glReadPixels( | |
0, //読み取る領域の左下隅のx座標 | |
0, //読み取る領域の左下隅のy座標 //0 or getCurrentWidth() - 1 | |
imageWidth, //読み取る領域の幅 | |
imageHeight, //読み取る領域の高さ | |
GL_BGRA, //取得したい色情報の形式 | |
GL_UNSIGNED_BYTE, //読み取ったデータを保存する配列の型 | |
dataBuffer //ビットマップのピクセルデータ(実際にはバイト配列)へのポインタ | |
); | |
GLubyte* p = static_cast<GLubyte*>(dataBuffer); | |
cv::Mat data(imageWidth, imageHeight, CV_8UC4, p); | |
cv::Mat gray; | |
cv::cvtColor(data, gray, cv::COLOR_BGR2GRAY); | |
cv::Mat disp; | |
cv::flip(gray, disp, 0); | |
cv::namedWindow("test", cv::WINDOW_AUTOSIZE); | |
cv::imshow("test", disp); | |
cv::waitKey(0); | |
std::string fname = "./outputImage.jpg"; | |
} | |
void keyPressed(unsigned char key, int x, int y){ | |
switch(key){ | |
case 's': | |
SaveImage(); | |
break; | |
} | |
} | |
int main(int argc, char * argv[]) { | |
glutInit(&argc, argv); | |
glutInitWindowSize(WindowSize, WindowSize); | |
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); | |
glutCreateWindow("Wire_teapot"); | |
glutDisplayFunc(display); | |
glutKeyboardFunc(keyPressed); | |
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | |
glutMainLoop(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment