程序员的资源宝库

网站首页 > gitee 正文

OpenCV学习笔记(20)Kinect OpenNI OpenCV OpenGL 组合体验

sanyeah 2024-03-29 16:14:04 gitee 7 ℃ 0 评论

1. 项目源码详见:http://www.opencv.org.cn/forum.php?mod=viewthread&tid=13042&extra= (2014-05-21 更新链接)

2. 已更新了 OpenGL 部分的代码,实现了点云数据的三角化。

3. 关于“Can not open a capture object”问题,我机子上运行没遇到,不过大家可以尝试以下方案:

按照下文改写好代码并重新用Cmake和VS2008编译好后,在当前项目的 project->properties->Configuration Properties中的C/C++ -> additional Library directories 和 Linker -> additional Include directories 分别添加上OpenNI 的include 和 lib 。

参考自项目源码发布帖中 silan 童鞋的回复。谢谢!

 

 

============================================================= 

 

前几天刚入手了期待已久的 Kinect ,用于实验室机器人项目的视觉导航与环境理解。

首先要做的是破解-->连接PC-->获取深度数据和图像数据-->三维点云显示 这么几项基本工作。

开始仿照的是 饮水思源 博客的方法(使用VS2008在windows平台上试用Kinect ),利用 CL-NUI-Platform 来破解,它的最新版是1.0.0.1210,但我在XP上用会当机,后来换 1.0.0.1121 版的就可以用了。CL NUI 提供了十分简便易用的接口,在OpenCV 上调用很简单,另外它还提供了 Kinect 底座马达的控制接口和 LED 灯颜色的选择接口,其例程中可以操控 Kinect 上下摆动。如果只需要获取深度数据和图像数据,CL NUI 就够用了。不过要做深入的应用,比如人体姿态识别、骨架提取、深度数据与图像数据的合并等等,就该用到 OpenNI 了。

国内的 CNKINECT 是个不错的 Kinect 开发论坛,版块丰富,有很多资料可供借鉴。我通过论坛介绍的 方法 成功配置了 OpenNI + Kinect,先是用最新版的 OpenNI+SensorKinect+NITE ,但在 XP 下不能正常运行,可能跟 .net 平台有关,老实按上面论坛的方法装就成功了。另外用 CMake + VS2008 装了最新的 OpenCV_SVN,开始试过在 CMake 里选择 With TBB,但诡异的是 TBB 似乎只适用于VS2005,在 VS2008 编译后试用里面的 samples 老是提示报错找不到msvcp80.dll,重新用 CMake 配置取消了 With TBB,就一切正常了。

 

一、深度摄像机的视角调整 与 深度/彩色图像的合并

通过研究 OpenCV_SVN 与 OpenNI 相关的代码(cap_openni.cpp)发现,opencv 目前只支持对Kinect的深度图、视差图和彩色/灰度图及相关属性的读取,更进一步的设置还没有实现。参考台湾 Heresy’space 的博客文章《透過 OpneNI 合併 Kinect 深度以及彩色影像資料》,想把深度图和彩色图合并显示,但是由于 Kinect 的深度摄像机和彩色摄像机是在不同的位置,而且镜头本身的参数也不完全相同,所以两个摄像机所取得的画面会有些微的差异(如图1 左下角子图OpenGL三维点云显示窗口所示,天花板的两个日光灯对应深度图和彩色图的区域并没有重合,而是错位了)。

  图1

根据 Heresy 的分析,需要对深度摄像机的视角进行修正,在 OpenNI 下只需要一行代码就可以实现:

 

[cpp] view plain copy
 
  1. // 6. correct view port   
  2. mDepthGenerator.GetAlternativeViewPointCap().SetViewPoint( mImageGenerator );  

 

不过在 OpenCV 中并没有提供这一项设置,其源代码 modules/highgui/src/cap_openni.cpp 中 setDepthGeneratorProperty 并没有任何实质的属性设置。为此,需要改写该函数,并且要在相应的头文件 modules/highgui/include/opencv2/highgui/highgui_c.h 中添加新的参数 id,具体如下:

1、将  cap_openni.cpp 第 344 行的 setDepthGeneratorProperty 改写如下:

 

[cpp] view plain copy
 
  1. bool CvCapture_OpenNI::setDepthGeneratorProperty( int propIdx, double propValue )   
  2. {   
  3.     bool res = false;   
  4.     CV_Assert( depthGenerator.IsValid() );   
  5.     switch( propIdx )   
  6.     {   
  7.     case CV_CAP_PROP_OPENNI_VIEW_POINT :   
  8.         depthGenerator.GetAlternativeViewPointCap().SetViewPoint( imageGenerator );   
  9.         res = true;   
  10.         break;   
  11.     default :   
  12.         CV_Error( CV_StsBadArg, "Depth generator does not support such parameter for setting./n");   
  13.         res = false;   
  14.     }   
  15.     return res;      
  16. }  

 

2、在 highgui_c.h 的第 348 行下添加改变视角的参数 ID 号:

 

[c-sharp] view plain copy
 
  1. CV_CAP_PROP_OPENNI_VIEW_POINT        = 24,   

 

然后在第 352 行下添加:

 

[cpp] view plain copy
 
  1. CV_CAP_OPENNI_DEPTH_GENERATOR_VIEW_POINT = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_VIEW_POINT  

  

 

从而使得 OpenCV 的 VideoCapture 属性关于 OpenNI 的如下所示:

 

[cpp] view plain copy
 
  1. // OpenNI map generators   
  2. CV_CAP_OPENNI_DEPTH_GENERATOR = 0,   
  3. CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 31,   
  4. CV_CAP_OPENNI_GENERATORS_MASK = 1 << 31,   
  5. // Properties of cameras avalible through OpenNI interfaces   
  6. CV_CAP_PROP_OPENNI_OUTPUT_MODE      = 20,   
  7. CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH  = 21, // in mm   
  8. CV_CAP_PROP_OPENNI_BASELINE         = 22, // in mm   
  9. CV_CAP_PROP_OPENNI_FOCAL_LENGTH     = 23, // in pixels   
  10. CV_CAP_PROP_OPENNI_VIEW_POINT        = 24,   
  11. CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE,   
  12. CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE,   
  13. CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH,   
  14. CV_CAP_OPENNI_DEPTH_GENERATOR_VIEW_POINT = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_VIEW_POINT  

 

改写完上述源代码后保存,并且用 CMake 和 VS2008 重新编译一次 OpenCV,我们就可以用 OpenCV 的接口来控制 Kinect 深度摄像头的视角,使其深度数据和图像数据能够很好的重合起来,如图2所示,注意与图1相比,右上角的伪彩色视差图四周出现了黑边,这就是视角调整后的效果:

  图2

 

二、三维点云坐标的计算

在 OpenCV 中实际上已经提供了三维点云坐标计算的接口,通过 Kinect 的深度数据可以很快换算出三维点云坐标,cap_openni.cpp 中这部分代码具体如下:

 

[cpp] view plain copy
 
  1. IplImage* CvCapture_OpenNI::retrievePointCloudMap()   
  2. {   
  3.     int cols = depthMetaData.XRes(), rows = depthMetaData.YRes();   
  4.     if( cols <= 0 || rows <= 0 )   
  5.         return 0;   
  6.     cv::Mat depth;   
  7.     getDepthMapFromMetaData( depthMetaData, depth, noSampleValue, shadowValue );   
  8.     const float badPoint = 0;   
  9.     cv::Mat pointCloud_XYZ( rows, cols, CV_32FC3, cv::Scalar::all(badPoint) );   
  10.     for( int y = 0; y < rows; y++ )   
  11.     {   
  12.         for( int x = 0; x < cols; x++ )   
  13.         {   
  14.             unsigned short d = depth.at(y, x);   
  15.             // Check for invalid measurements   
  16.             if( d == CvCapture_OpenNI::INVALID_PIXEL_VAL ) // not valid   
  17.                 continue;   
  18.             XnPoint3D proj, real;   
  19.             proj.X = x;   
  20.             proj.Y = y;   
  21.             proj.Z = d;   
  22.             depthGenerator.ConvertProjectiveToRealWorld(1, &proj, &real);   
  23.             pointCloud_XYZ.at(y,x) = cv::Point3f( real.X*0.001f, real.Y*0.001f, real.Z*0.001f); // from mm to meters   
  24.         }   
  25.     }   
  26.     outputMaps[CV_CAP_OPENNI_POINT_CLOUD_MAP].mat = pointCloud_XYZ;   
  27.     return outputMaps[CV_CAP_OPENNI_POINT_CLOUD_MAP].getIplImagePtr();   
  28. }  

 

 

不过可以看到上面核心的代码就一行:

 

[cpp] view plain copy
 
  1. depthGenerator.ConvertProjectiveToRealWorld(1, &proj, &real);  

 

具体是怎样实现的呢?我们可以进一步找 OpenNI 的源代码来分析。不过这里我是从原来双目视觉的经验上自己编写代码来实现三维点云坐标的计算。实际上 Kinect 的深度摄像头成像也类似于普通的双目立体视觉,只要获取了两个摄像头之间的基线(baseline)和焦距(focal length)、以及视差数据,通过构造矩阵 Q,利用 OpenCV 的 reprojectimageTo3D 函数,也可以计算出三维坐标。

下面我们通过以下代码看看矩阵 Q 的构造过程:

 

[cpp] view plain copy
 
  1. capture.set(CV_CAP_OPENNI_DEPTH_GENERATOR_VIEW_POINT, 1.0);  // 调整深度摄像头视角   
  2. double b = capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE ); // mm   
  3. double F = capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH ); // pixels   
  4. double q[] =   
  5. {   
  6.     1, 0, 0, -320.0,   
  7.     0, 1, 0, -240.0,   
  8.     0, 0, 0, F,   
  9.     0, 0, 1./b, 0          
  10. };   
  11. Mat matQ(4, 4, CV_64F, q);  

 

 

而三维点云坐标的计算,以及深度、视差、彩色图像的读取,则如下所示:

 

[cpp] view plain copy
 
  1. // 抓取数据   
  2. if( !capture.grab() )   
  3. {   
  4.     cout << "Can not grab images." << endl;   
  5.     return -1;   
  6. }   
  7. // 读取深度数据   
  8. capture.retrieve( depthMap, CV_CAP_OPENNI_DEPTH_MAP );   
  9. minMaxLoc( depthMap, &mindepth, &maxdepth );   
  10. // 读取视差数据   
  11. capture.retrieve( disparityMap, CV_CAP_OPENNI_DISPARITY_MAP_32F );          
  12. colorizeDisparity( disparityMap, colorDisparityMap, maxDisparity );   
  13. colorDisparityMap.copyTo( validColorDisparityMap, disparityMap != 0 );          
  14. imshow( "colorized disparity map", validColorDisparityMap );   
  15. // 读取彩色图像数据   
  16. capture.retrieve( bgrImage, CV_CAP_OPENNI_BGR_IMAGE );   
  17. imshow( "Color image", bgrImage );   
  18. // 利用视差数据计算三维点云坐标   
  19. cv::reprojectImageTo3D(disparityMap, xyzMap, matQ, true);  

 

 

这里值得注意的是,在计算视差时,如果视差图是采用默认的 CV_8UC1 格式(参数ID是CV_CAP_OPENNI_DISPARITY_MAP),由于视差被限制在[0-255]整数范围内,造成一定的误差,所得到的三维坐标数据会出现分层,如图3和图4所示:

图3 Matlab绘制的三维点云,不同深度上有明显分层

图4 左为直接得到的深度数据Mesh图,中为由8位视差数据计算得到的深度数据,右为对应的视差数据

 

而采用 32 位浮点格式来获取视差数据(参数ID:CV_CAP_OPENNI_DISPARITY_MAP_32F),则消除了这种因视差误差造成深度数值分层的现象,如图5、6所示:

 图5 深度数值的分层现象基本消除

 图6 两种方式得到的深度数据一致

 

三、利用OpenGL显示三维点云数据

这方面主要是基于 学习笔记(15) 的内容,不过当时是通过另设 OpenCV 窗口设置 Trackbar 来调整 OpenGL 的视点位置和摄像机位置。在这里则主要参考了 OpenCV 论坛的帖子《[HQ] OpenCV和OpenGL编程:关于显示点云数据-Stereo Vision源码分享》中 villager5 提供的方法来调整摄像机位置,做了一定的修改,使得鼠标左键拖曳能够实现对上下左右的视角变换,鼠标右键拖曳能够实现视距远近的变换,不再需要用 Trackbar 来调整。下面是相关的代码:

 

 

[cpp] view plain copy
 
  1. #define SIGN(x) ( (x)<0 ? -1:((x)>0?1:0 ) )  
  2. //////////////////////////////////////////////////////////////////////////  
  3. //   
  4. //---OpenGL 全局变量  
  5. float xyzdata[480][640][3];  
  6. float texture[480][640][3];  
  7. int glWinWidth = 640, glWinHeight = 480;  
  8. int width=640, height=480;  
  9. double eyex, eyey, eyez, atx, aty, atz;  // eye* - 摄像机位置,at* - 注视点位置  
  10. bool leftClickHold = false, rightClickHold = false;  
  11. int mx,my;          // 鼠标按键时在 OpenGL 窗口的坐标  
  12. int ry = 90, rx = 90;    // 摄像机相对注视点的观察角度  
  13. double mindepth, maxdepth;      // 深度数据的极值   
  14. double radius = 6000.0;     // 摄像机与注视点的距离  
  15.   
  16. /************************************************************************/  
  17. /*                                           OpenGL响应函数                                                 */  
  18. /************************************************************************/  
  19. //////////////////////////////////////////////////////////////////////////  
  20. // 鼠标按键响应函数  
  21. void mouse(int button, int state, int x, int y)  
  22. {  
  23.     if(button == GLUT_LEFT_BUTTON)  
  24.     {  
  25.         if(state == GLUT_DOWN)  
  26.         {  
  27.             leftClickHold=true;  
  28.         }  
  29.         else  
  30.         {  
  31.             leftClickHold=false;  
  32.         }  
  33.     }  
  34.     if (button== GLUT_RIGHT_BUTTON)  
  35.     {  
  36.         if(state == GLUT_DOWN)  
  37.         {  
  38.             rightClickHold=true;  
  39.         }  
  40.         else  
  41.         {  
  42.             rightClickHold=false;  
  43.         }  
  44.     }  
  45. }  
  46. //////////////////////////////////////////////////////////////////////////  
  47. // 鼠标运动响应函数  
  48. void motion(int x, int y)  
  49. {  
  50.     int rstep = 5;   
  51.     if(leftClickHold==true)  
  52.     {  
  53.         if( abs(x-mx) > abs(y-my) )  
  54.         {  
  55.             rx += SIGN(x-mx)*rstep;      
  56.         }  
  57.         else  
  58.         {  
  59.             ry -= SIGN(y-my)*rstep;      
  60.         }  
  61.           
  62.         mx=x;  
  63.         my=y;  
  64.         glutPostRedisplay();  
  65.     }  
  66.     if(rightClickHold==true)  
  67.     {  
  68.         if( y-my > 0 )  
  69.         {  
  70.             radius += 100.0;  
  71.         }  
  72.         else if( y-my < 0 )  
  73.         {  
  74.             radius -= 100.0;  
  75.         }  
  76.         radius = std::max( radius, 100.0 );  
  77.         mx=x;  
  78.         my=y;  
  79.         glutPostRedisplay();  
  80.     }  
  81. }  
  82. //////////////////////////////////////////////////////////////////////////  
  83. // 三维图像显示响应函数  
  84. void renderScene(void)   
  85. {  
  86.     // clear screen and depth buffer  
  87.     glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );  
  88.     // Reset the coordinate system before modifying   
  89.     glLoadIdentity();     
  90.     // set the camera position  
  91.     atx = 0.0f;  
  92.     aty = 0.0f;  
  93.     atz = ( mindepth - maxdepth ) / 2.0f;  
  94.     eyex = atx + radius * sin( CV_PI * ry / 180.0f ) * cos( CV_PI * rx/ 180.0f );   
  95.     eyey = aty + radius * cos( CV_PI * ry/ 180.0f );   
  96.     eyez = atz + radius * sin( CV_PI * ry / 180.0f ) * sin( CV_PI * rx/ 180.0f );  
  97.     gluLookAt (eyex, eyey, eyez, atx, aty, atz, 0.0, 1.0, 0.0);  
  98.     glRotatef(0,0,1,0);  
  99.     glRotatef(-180,1,0,0);  
  100.       
  101.     // 对点云数据进行三角化  
  102.     // 参考自:http://www.codeproject.com/KB/openGL/OPENGLTG.aspx  
  103.     // we are going to loop through all of our terrain's data points,  
  104.     // but we only want to draw one triangle strip for each set along the x-axis.  
  105.     for (int i = 0; i < height; i++)  
  106.     {  
  107.         glBegin(GL_TRIANGLE_STRIP);  
  108.         for (int j = 0; j < width; j++)  
  109.         {  
  110.             // for each vertex, we calculate the vertex color,   
  111.             // we set the texture coordinate, and we draw the vertex.  
  112.             /* 
  113.                the vertexes are drawn in this order: 
  114.                0  ---> 1 
  115.                       / 
  116.                     / 
  117.                   / 
  118.                2  ---> 3 
  119.             */  
  120.                   
  121.             // draw vertex 0  
  122.             glTexCoord2f(0.0f, 0.0f);  
  123.             glColor3f(texture[i][j][0]/255.0f, texture[i][j][1]/255.0f, texture[i][j][2]/255.0f);  
  124.             glVertex3f(xyzdata[i][j][0], xyzdata[i][j][1], xyzdata[i][j][2]);  
  125.             // draw vertex 1  
  126.             glTexCoord2f(1.0f, 0.0f);  
  127.             glColor3f(texture[i+1][j][0]/255.0f, texture[i+1][j][1]/255.0f, texture[i+1][j][2]/255.0f);  
  128.             glVertex3f(xyzdata[i+1][j][0], xyzdata[i+1][j][1], xyzdata[i+1][j][2]);  
  129.             // draw vertex 2  
  130.             glTexCoord2f(0.0f, 1.0f);  
  131.             glColor3f(texture[i][j+1][0]/255.0f, texture[i][j+1][1]/255.0f, texture[i][j+1][2]/255.0f);  
  132.             glVertex3f(xyzdata[i][j+1][0], xyzdata[i][j+1][1], xyzdata[i][j+1][2]);  
  133.             // draw vertex 3  
  134.             glTexCoord2f(1.0f, 1.0f);  
  135.             glColor3f(texture[i+1][j+1][0]/255.0f, texture[i+1][j+1][1]/255.0f, texture[i+1][j+1][2]/255.0f);  
  136.             glVertex3f(xyzdata[i+1][j+1][0], xyzdata[i+1][j+1][1], xyzdata[i+1][j+1][2]);  
  137.         }  
  138.         glEnd();  
  139.     }  
  140.     // enable blending  
  141.     glEnable(GL_BLEND);  
  142.     // enable read-only depth buffer  
  143.     glDepthMask(GL_FALSE);  
  144.     // set the blend function to what we use for transparency  
  145.     glBlendFunc(GL_SRC_ALPHA, GL_ONE);  
  146.     // set back to normal depth buffer mode (writable)  
  147.     glDepthMask(GL_TRUE);  
  148.     // disable blending  
  149.     glDisable(GL_BLEND);  
  150. /*  float x,y,z; 
  151.     // 绘制图像点云 
  152.     glPointSize(1.0);  
  153.     glBegin(GL_POINTS); 
  154.     for (int i=0;i<height;i++){  
  155.         for (int j=0;j<width;j++){ 
  156.             // color interpolation  
  157.             glColor3f(texture[i][j][0]/255, texture[i][j][1]/255, texture[i][j][2]/255); 
  158.             x= xyzdata[i][j][0]; 
  159.             y= xyzdata[i][j][1];  
  160.             z= xyzdata[i][j][2];  
  161.             glVertex3f(x,y,z);  
  162.         } 
  163.     } 
  164.     glEnd(); */  
  165.     glFlush();  
  166.     glutSwapBuffers();  
  167. }  
  168. //////////////////////////////////////////////////////////////////////////  
  169. // 窗口变化图像重构响应函数  
  170. void reshape (int w, int h)   
  171. {  
  172.     glWinWidth = w;  
  173.     glWinHeight = h;  
  174.     glViewport (0, 0, (GLsizei)w, (GLsizei)h);  
  175.     glMatrixMode (GL_PROJECTION);  
  176.     glLoadIdentity ();  
  177.     gluPerspective (45, (GLfloat)w / (GLfloat)h, 1.0, 15000.0);   
  178.     glMatrixMode (GL_MODELVIEW);  
  179. }  
  180. //////////////////////////////////////////////////////////////////////////  
  181. // 载入三维坐标数据  
  182. void load3dDataToGL(IplImage* xyz)  
  183. {  
  184.     CvScalar s;  
  185.     //accessing the image pixels  
  186.     for (int i=0;i<height;i++)  
  187.     {   
  188.         for (int j=0;j<width;j++)  
  189.         {  
  190.             s=cvGet2D(xyz,i,j);         // s.val[0] = x, s.val[1] = y, s.val[2] = z  
  191.             xyzdata[i][j][0] = s.val[0];  
  192.             xyzdata[i][j][1] = s.val[1];  
  193.             xyzdata[i][j][2] = s.val[2];  
  194.         }  
  195.     }   
  196. }  
  197. //////////////////////////////////////////////////////////////////////////  
  198. // 载入图像纹理数据  
  199. void loadTextureToGL(IplImage* img)  
  200. {     
  201.     CvScalar ss;  
  202.     //accessing the image pixels  
  203.     for (int i=0;i<height;i++)  
  204.     {   
  205.         for (int j=0;j<width;j++)  
  206.         {  
  207.             ss=cvGet2D(img,i,j);            // ss.val[0] = red, ss.val[1] = green, ss.val[2] = blue  
  208.             texture[i][j][2] = ss.val[0];  
  209.             texture[i][j][1] = ss.val[1];  
  210.             texture[i][j][0] = ss.val[2];  
  211.         }  
  212.     }     
  213. }  

 

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表