做项目时发现Kinect在抖动或者移动时,会无法识别人物,所以只能自己获取原始深度图像信息。以官方sdk的示例为目标,做了一个demo。
项目环境为win8 + unity2018.2.12 + Kinect v2 Examples with MS-SDK 2.16.2.unitypackage。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GetKinectDepthMsg : MonoBehaviour
{
public RawImage kinectDepthPic;
//public KinectDataServer dataServer;
private bool tempBool;
void Start()
{
StartCoroutine(SetTexture());
}
void Update()
{
}
IEnumerator SetTexture()
{
KinectInterop.SensorData data = KinectManager.Instance.GetSensorData();
Color[] colors = new Color[512 * 424];
Texture2D tempTex = new Texture2D(512, 424, TextureFormat.ARGB32, false);
tempTex.wrapMode = TextureWrapMode.Clamp;
tempTex.filterMode = FilterMode.Trilinear;
while (true)
{
if (KinectManager.Instance.IsInitialized() && data.depthImage != null)
{
#region 深度图
ushort[] depthImage = data.depthImage;// 获得原始数据
// 经测试,Kinect面对的空间,深度图原始数据数组从右上角开始,水平获取像素。
for (int i = 0; i < 424; i++)
{
for (int k = 0; k < 512; k++)
{
// 这个8000是为了达到和微软官方sdk示例一样效果调出来的
float r = ((float)data.depthImage[512 * i + k]) / 8000;
float g = ((float)data.depthImage[512 * i + k]) / 8000;
float b = ((float)data.depthImage[512 * i + k]) / 8000;
Color tempColor = new Color(r, g, b, 1);
colors[512 * i + k] = tempColor;
// 无法实现目标
//colors[512 * i + k].r = ((float)data.depthImage[512 * i + k]) / 8000;
//colors[512 * i + k].g = ((float)data.depthImage[512 * i + k]) / 8000;
//colors[512 * i + k].b = ((float)data.depthImage[512 * i + k]) / 8000;
}
if (i % 240 == 0)// 控制一帧的计算量
yield return null;
}
tempTex.SetPixels(colors);
tempTex.Apply();
kinectDepthPic.texture = tempTex;// 显示图片
#endregion
}
yield return null;
}
}
}