OpenNI结合OpenCV显示Kinect彩色、深度及融合图像

平台:win7 32、VS2010、OpenNI1.5.4.0、OpenCV2.4.9

图片在最后(注意图片中的日光灯,匹配的较好)

全部代码如下:

#include <stdlib.h>
#include <iostream>
#include <string>

#include <XnCppWrapper.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace xn;
using namespace cv;

void CheckOpenNIError(XnStatus eResult,string sStatus)//检测错误并返回错误的函数
{
	if(eResult != XN_STATUS_OK)
		cout << sStatus << "Error: " << xnGetStatusString(eResult) << endl;//P53
}

int main()
{
	XnStatus eResult = XN_STATUS_OK;
	ImageMetaData imageMD;
	DepthMetaData depthMD;
	namedWindow("Color Image");
	namedWindow("Depth Image");
	namedWindow("Fusion Image");

	Context mContext;//初始化上下文对象
	eResult = mContext.Init();
	CheckOpenNIError(eResult,"Initialize context");

	ImageGenerator mImageGenerator;//创建彩色图像生产节点
	eResult = mImageGenerator.Create(mContext);
	CheckOpenNIError(eResult,"Create image generator");
	
	DepthGenerator mDepthGenerator;//创建深度图像生产节点
	eResult = mDepthGenerator.Create(mContext);
	CheckOpenNIError(eResult,"Create depth generator");

	XnMapOutputMode mapMode;//设置图像分辨率
	mapMode.nXRes = 320;
	mapMode.nYRes = 240;
	mapMode.nXRes = 30;
	eResult = mImageGenerator.SetMapOutputMode(mapMode);
	eResult = mDepthGenerator.SetMapOutputMode(mapMode);

	mDepthGenerator.GetAlternativeViewPointCap().SetViewPoint(mImageGenerator);
        //深度图像视角转换成彩色图象视角

	eResult = mContext.StartGeneratingAll();//开始产生数据

	while(true)
	{
		eResult = mContext.WaitAndUpdateAll();
		if(eResult == XN_STATUS_OK)
		{
			mImageGenerator.GetMetaData(imageMD);
			Mat cvRGBImage(imageMD.FullYRes(),imageMD.FullXRes(),CV_8UC3,(char*) imageMD.Data());
			Mat cvBGRImage;
			cvtColor(cvRGBImage,cvBGRImage,CV_RGB2BGR);
                        //整幅图像颜色转换,因为opencv中采用BGR方式排列
			imshow("Color Image",cvBGRImage);

			mDepthGenerator.GetMetaData(depthMD);
			Mat cvDepthImage16UC1(depthMD.FullYRes(),
                                              depthMD.FullXRes(),
                                              CV_16UC1,(char*) depthMD.Data());
			Mat cvDepthImage8UC1;
			cvDepthImage16UC1.convertTo(cvDepthImage8UC1,CV_8UC1,255.0/(depthMD.ZRes()));//格式转换
			imshow("Depth Image",cvDepthImage8UC1);

			Mat cvDepthImage8UC3;
			cvtColor(cvDepthImage8UC1,cvDepthImage8UC3,CV_GRAY2BGR);//格式转换

			Mat cvFusionImage;
			cvFusionImage = 0.5*cvBGRImage + 0.5*cvDepthImage8UC3;//图像融合
			imshow("Fusion Image",cvFusionImage);

			waitKey(30);
		}
	}

	mContext.StopGeneratingAll();//停止产生数据
	mContext.Shutdown();
	return 0;
}

彩色图象:


深度图像:

视角校正后的融合图像:

OpenNI结合OpenCV显示Kinect彩色、深度及融合图像_第1张图片


你可能感兴趣的:(opencv,kinect,openni)