根据下面两个帖子改的程序
1~ 由于OpenNI获得的深度图片是12位无符号整数,而OpenCV显示的是8位的,所以要作转换。
RGB和BGR在内存对应的位置序列不同,所以也要转换。
2~ 编译环境不多说了吧?
http://www.javaforge.com/wiki/101904 有OpenNI的安装教程
OpenCV 2.2的… 配置好lib, include, dll那些就行了,http://www.opencv.org.cn 这里也有安装的东东
#include <stdlib.h>
#include <iostream>
#include <string>
#include <XnCppWrapper.h>
#include "opencv/cv.h"
#include "opencv/highgui.h"
using namespace std;
using namespace cv;
void testCheckOpenNIError( XnStatus eResult, string sStatus )
{
if( eResult != XN_STATUS_OK )
cerr << sStatus << " Error: " << xnGetStatusString( eResult ) << endl;
}
int test( int argc, char** argv )
{
XnStatus eResult = XN_STATUS_OK;
// 1. initial val
xn::DepthMetaData m_DepthMD;
xn::ImageMetaData m_ImageMD;
// for opencv Mat
Mat m_depth16u( 480,640,CV_16UC1);
Mat m_rgb8u( 480,640,CV_8UC3);
Mat m_DepthShow( 480,640,CV_8UC1);
Mat m_ImageShow( 480,640,CV_8UC3);
cvNamedWindow("depth");
cvNamedWindow("image");
char key=0;
// 2. initial context
xn::Context mContext;
eResult = mContext.Init();
CheckOpenNIError( eResult, "initialize context" );
// 3. create depth generator
xn::DepthGenerator mDepthGenerator;
eResult = mDepthGenerator.Create( mContext );
CheckOpenNIError( eResult, "Create depth generator" );
// 4. create image generator
xn::ImageGenerator mImageGenerator;
eResult = mImageGenerator.Create( mContext );
CheckOpenNIError( eResult, "Create image generator" );
// 5. set map mode
XnMapOutputMode mapMode;
mapMode.nXRes = 640;
mapMode.nYRes = 480;
mapMode.nFPS = 30;
eResult = mDepthGenerator.SetMapOutputMode( mapMode );
eResult = mImageGenerator.SetMapOutputMode( mapMode );
// 6. correct view port
mDepthGenerator.GetAlternativeViewPointCap().SetViewPoint( mImageGenerator );
// 7. tart generate data
eResult = mContext.StartGeneratingAll();
// 8. read data
eResult = mContext.WaitNoneUpdateAll();
while( (key!=27) && !(eResult = mContext.WaitNoneUpdateAll( )) )
{
// 9a. get the depth map
mDepthGenerator.GetMetaData(m_DepthMD);
memcpy(m_depth16u.data,m_DepthMD.Data(),640*480*2);
// 9b. get the image map
mImageGenerator.GetMetaData(m_ImageMD);
memcpy(m_rgb8u.data,m_ImageMD.Data(),640*480*3);
m_depth16u.convertTo(m_DepthShow,CV_8U,255/2096.0);
cvtColor(m_rgb8u,m_ImageShow,CV_RGB2BGR);
imshow("depth", m_DepthShow);
imshow("image", m_ImageShow);
key=cvWaitKey(20);
}
// 10. stop
mContext.StopGeneratingAll();
mContext.Shutdown();
return 0;
}