首先要实例化我们需要的东西
先实例化一个Kinect
KinectSensor kinectSensor = KinectSensor.GetDefault();
然后打开深度摄像头
var depthFrameReader = this.kinectSensor.DepthFrameSource.OpenReader();
depthFrameReader.FrameArrived += Reader_FrameArrived;
depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription;
创建一个可写入的图像,我们要创建一个彩色的图像,所以选择Bgra32。512是Kinect分辨率的Width,424是Kinect分辨率的Height
WriteableBitmap depthBitmap= = new WriteableBitmap(512, 424, 96.0, 96.0, PixelFormats.Bgra32, null);
每当Kinect得到一帧深度图像的时候就会触发下面的这个事件。我们呢就在这个事件里处理每个像素的深度数据,然后以图片的形式展示出来。由于每次都会有512*424个像素的数据,这里执行的内容不能太过复杂,不然画面就非常卡
private void Reader_FrameArrived(object sender, DepthFrameArrivedEventArgs e)
{
using (DepthFrame depthFrame = e.FrameReference.AcquireFrame())
{
if (depthFrame != null)
{
ushort[] DepthValueData = new ushort[depthFrame.FrameDescription.LengthInPixels];
//将Kicent获取的深度值拷贝存储像素的矩阵中
depthFrame.CopyFrameDataToArray(DepthValueData);
byte[] imageBytes = new byte[DepthValueData.Length * 4];
double maxDepth = DepthValueData.Max(p => p);
for (int i = 0; i < DepthValueData.Length; i++)
{
//DepthValueData[i]就是距离,通过判断这个值就可以创建不同的颜色了
//B
imageBytes[i * 4 + 0] = DepthValueData[i] > 10 ? 255 : 0;
//G
imageBytes[i * 4 + 1] = DepthValueData[i] > 10 ? 128: 0;
//R
imageBytes[i * 4 + 2] = DepthValueData[i] > 10 ? 64: 0;
//A
imageBytes[i * 4 + 3] = 255;
}
//在这里就可以将我们创建好的像素点写到图像里展示出来了
depthBitmap.WritePixels(new Int32Rect(0, 0, 512, 424),imageBytes,512 * 4,0);
}
}
}
最后的效果: