[KinectWPF程序]Kinect初始化&彩色&深度数据 注册AllFrameReady同步事件方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
KinectSensor kinectSensor;
//初始化Kinect直接调用InitKinect()即可;注册的同步事件为AllFramesReadyEventArgs
/// <summary>
/// 启动Kinect设备,初始化选项,并注册AllFrameReady同步事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void kinectSensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
//彩色图像像素矩阵为byte[]型,深度数据存储矩阵为shor[]型
//获取彩色图像
//using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
//{
// if (colorFrame != null)
// {
// //建立存储像素的矩阵,一维矩阵
// //colorFrame.PixelDataLength每一帧的数据长度
// byte[] ColorPixelData = new byte[colorFrame.PixelDataLength];
// //将Kicent获取的彩色像素拷贝存储像素的矩阵中
// colorFrame.CopyPixelDataTo(ColorPixelData);
// //显示图像,ShowImage为Image控件
// this.ShowImage.Source = BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96,
// PixelFormats.Bgr32, null, ColorPixelData, colorFrame.Width * colorFrame.BytesPerPixel);
// }
//}
//获取深度图像
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame != null)
{
//建立存储深度值的矩阵,一维矩阵
//depthFrame.PixelDataLength每一帧的数据长度
short[] DepthValueData = new short[depthFrame.PixelDataLength];
//将Kicent获取的深度值拷贝存储像素的矩阵中
depthFrame.CopyPixelDataTo(DepthValueData);
}
}
}
private void InitKinect()
{
if (KinectSensor.KinectSensors.Count > 0)
{
kinectSensor = (from sensor in KinectSensor.KinectSensors
where sensor.Status == KinectStatus.Connected
select sensor).FirstOrDefault();
kinectSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
kinectSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
kinectSensor.SkeletonStream.Enable();
kinectSensor.Start();
kinectSensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(kinectSensor_AllFramesReady);
}
else
{
MessageBox.Show("没有检测到Kinect设备");
}
}
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
InitKinect();
}
}
}