技术开发 频道

Kinect for Windows SDK开发应用初体验

  然后,在Loaded事件的处理函数中添加Runtime初始化的代码:

  private void Window_Loaded(object sender, RoutedEventArgs e)

  {

  nui
= new Runtime();

  nui.Initialize(RuntimeOptions.UseColor| RuntimeOptions.UseDepth | RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking);

  }

  接下来是Closed事件中关闭Runtime的代码:

  
private void Window_Closed(object sender, EventArgs e)

  {

  nui.Uninitialize();

  }

  Runtime对象是Kinect SDK中最主要的一个类,所有针对Kinect的操作都由Runtime类进行了封装。Runtime的构造函数没有接受任何参数,但有一个显式的初始化函数Initialize,接受RuntimeOptions参数,指定调用Kinect的哪些功能。其中RuntimeOptions.UseColor表示使用RGB Camera,而RuntimeOptions.UseDepth则表示使用Depth传感器。

  初始化工作完成之后,我们要通过RGB Camera来获取实时的图像数据了。我们首先要声明一个事件处理方法,来接收视频数据的信息:

  nui.VideoFrameReady += new EventHandler(nui_VideoFrameReady);

  然后是事件处理函数:

  void nui_VideoFrameReady(object sender, ImageFrameReadyEventArgs e)

  {

  PlanarImage imageData
= e.ImageFrame.Image;

  image1.Source
= BitmapSource.Create(imageData.Width, imageData.Height, 96, 96,

  PixelFormats.Bgr32,
null, imageData.Bits, imageData.Width * imageData.BytesPerPixel);

  
//image1.Source = e.ImageFrame.ToBitmapSource();

  }

  提示:Getting Started上提供的Sample Code有误,需要将最后一个参数中的data.Width改为imageData.Width才可以正常运行。

  VideoFrameReady事件会传递一个ImageFrameReadyEventArgs参数给事件处理函数,其中的ImageFrame会包含关于图片的各种信息,比如Type变量指定了图像是来自RGB还是Depth,Resolution变量指定了分辨率,而Image中以byte[]数组的方式保存了图像的真实数据。

  然后的工作就是根据PlanarImage中包括的数据来创建一个Bitmap对象,然后将其传递给Image控件,显示到WPF程序的界面上。

  最后,我们还要在构造函数里打开视频流,来获取视频数据:

  nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);

  第一个参数是ImageStreamType,用来指定打开的设备流类型;第二个参数是PoolSize,指定缓冲区的数量,至少为2,保证一个Buffer进行绘制,另一个Buffer进行数据填充;第三个参数指定Camera的分辨率;第四个参数则是获取的图片类型。

  显示效果如下图所示:

0
相关文章