通常的增強現(xiàn)實應(yīng)用需要支持OpenGL的OpenCV來對真實場景進行渲染。從2.4.2版本開始,OpenCV在可視化窗口中支持OpenGL。這意味著在OpenCV中可輕松渲染任何3D內(nèi)容。 若要在OpenCV中開始一個OpenGL窗口,需要做的第一件事是生成支持OpenGL的OpenCV。 在cmake的時候,應(yīng)該設(shè)置標(biāo)志: cmake -D ENABLE_OPENGL=YES 如果現(xiàn)在有一個支持OpenGL的OpenCV庫,可用其創(chuàng)建第一個OpenGL窗口。OpenGL窗口的初始化由創(chuàng)建一個命名的窗口開始,這需要設(shè)置一個OpenGL標(biāo)志: string openGLWindowName = "OpenGL Test"; cv::namedWindow(openGLWindowName, WINDOW_OPENGL);
resizeWindow(openGLWindowName, 640, 480); 接下來需對此窗口設(shè)置上下文: setOpenGlContext(openGLWindowName); 現(xiàn)在窗口就可以使用了。為了在窗口上畫一些東西,應(yīng)用以下方法注冊一個回調(diào)函數(shù): setOpenGlDrawCallback(openGLWindowName, on_opengl, NULL); 該回調(diào)函數(shù)將被稱為回調(diào)窗口。第一個參數(shù)為窗口名,第二個參數(shù)為回調(diào)函數(shù),第三個可選參數(shù)將被傳遞給回調(diào)函數(shù)。 on_opengl是一個繪圖函數(shù),例如: void on_opengl(void* param) { glLoadIdentity(); glTranslated(0.0, 0.0, -1.0); glRotatef( 55, 1, 0, 0 ); glRotatef( 45, 0, 1, 0 ); glRotatef( 0, 0, 0, 1 ); static const int coords[6][4][3] = { { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } }; for (int i = 0; i < 6; ++i) { glColor3ub( i*20, 100+i*10, i*42 ); glBegin(GL_QUADS); for (int j = 0; j < 4; ++j) { glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); } glEnd(); } } 這個函數(shù)可以繪制一個長方體,程序執(zhí)行效果如下所示: 同樣的,我們可以寫其他的繪制函數(shù) void onDraw(void* param) { // Draw something using OpenGL here glClearColor(0.0f, 0.0f, 1.0f, 1.0f); // background glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f); glRectf(-0.5f, -0.5f, 0.5f, 0.5f); // draw rect glFlush(); } 此函數(shù)的作用是在藍(lán)色背景下繪制一個紅色方塊,程序運行效果如下: 完整代碼下載地址:https://download.csdn.net/download/buaa_zn/10476956 |
|