通常的增強(qiáng)現(xiàn)實(shí)應(yīng)用需要支持OpenGL的OpenCV來對(duì)真實(shí)場(chǎng)景進(jìn)行渲染。從2.4.2版本開始,OpenCV在可視化窗口中支持OpenGL。這意味著在OpenCV中可輕松渲染任何3D內(nèi)容。 若要在OpenCV中開始一個(gè)OpenGL窗口,需要做的第一件事是生成支持OpenGL的OpenCV。 在cmake的時(shí)候,應(yīng)該設(shè)置標(biāo)志: cmake -D ENABLE_OPENGL=YES 如果現(xiàn)在有一個(gè)支持OpenGL的OpenCV庫,可用其創(chuàng)建第一個(gè)OpenGL窗口。OpenGL窗口的初始化由創(chuàng)建一個(gè)命名的窗口開始,這需要設(shè)置一個(gè)OpenGL標(biāo)志: string openGLWindowName = "OpenGL Test"; cv::namedWindow(openGLWindowName, WINDOW_OPENGL);
resizeWindow(openGLWindowName, 640, 480); 接下來需對(duì)此窗口設(shè)置上下文: setOpenGlContext(openGLWindowName); 現(xiàn)在窗口就可以使用了。為了在窗口上畫一些東西,應(yīng)用以下方法注冊(cè)一個(gè)回調(diào)函數(shù): setOpenGlDrawCallback(openGLWindowName, on_opengl, NULL); 該回調(diào)函數(shù)將被稱為回調(diào)窗口。第一個(gè)參數(shù)為窗口名,第二個(gè)參數(shù)為回調(diào)函數(shù),第三個(gè)可選參數(shù)將被傳遞給回調(diào)函數(shù)。 on_opengl是一個(gè)繪圖函數(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(); } } 這個(gè)函數(shù)可以繪制一個(gè)長(zhǎng)方體,程序執(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)色背景下繪制一個(gè)紅色方塊,程序運(yùn)行效果如下: 完整代碼下載地址:https://download.csdn.net/download/buaa_zn/10476956 |
|