ホームに戻る
プレイヤー認識
0、はじめに
プレイヤーを認識して赤色で表示する。
Kinectから80cm以上後ろに下がること。
1、WPF
<Window x:Class="KinectTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="KinectTest" Height="200" Width="300"
HorizontalContentAlignment="Center" Closing="Window_Closing">
<Grid>
<Image Name="image1" Stretch="Uniform"/>
</Grid>
</Window>
2、コード
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
namespace KinectTest{
public partial class MainWindow : Window{
readonly int BytesPerPixel = 4;
public MainWindow(){
try{
InitializeComponent();
if(KinectSensor.KinectSensors.Count == 0){
throw new Exception("Connect Kinect.");
}
StartKinect(KinectSensor.KinectSensors[0]);
}
catch(Exception ex){
MessageBox.Show(ex.Message);
Close();
}
}
private void StartKinect(KinectSensor kinect){
// Resolution80x60Fps30
// Resolution320x240Fps30
// Resolution640x480Fps30
DepthImageFormat depthImageFormat = DepthImageFormat.Resolution80x60Fps30;
kinect.DepthStream.Enable(depthImageFormat);
kinect.DepthFrameReady += new EventHandler<DepthImageFrameReadyEventArgs>(kinect_DepthFrameReady);
kinect.SkeletonStream.Enable();
kinect.Start();
}
private void StopKinect(KinectSensor kinect){
if(kinect != null){
if(kinect.IsRunning){
kinect.DepthFrameReady -= kinect_DepthFrameReady;
kinect.Stop();
kinect.Dispose();
image1.Source = null;
}
}
}
void kinect_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e){
try{
KinectSensor kinect = sender as KinectSensor;
if(kinect == null){
return;
}
using(DepthImageFrame depthFrame = e.OpenDepthImageFrame()){
if(depthFrame != null){
DepthImageStream depthStream = kinect.DepthStream;
short[] depthPixel = new short[depthFrame.PixelDataLength];
depthFrame.CopyPixelDataTo(depthPixel);
byte[] bufferImage = new byte[depthFrame.PixelDataLength * BytesPerPixel];
for(int i = 0; i < depthPixel.Length; i++){
int player = depthPixel[i] & DepthImageFrame.PlayerIndexBitmask;
int distance = depthPixel[i] >> DepthImageFrame.PlayerIndexBitmaskWidth;
if(player != 0){
bufferImage[i * 4] = 0;
bufferImage[i * 4 + 1] = 0;
bufferImage[i * 4 + 2] = 255;
}
else{
bufferImage[i * 4] = 0;
bufferImage[i * 4 + 1] = 0;
bufferImage[i * 4 + 2] = 0;
}
}
image1.Source = BitmapSource.Create(depthFrame.Width, depthFrame.Height, 96, 96, PixelFormats.Bgr32, null, bufferImage, depthFrame.Width * BytesPerPixel);
}
}
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e){
StopKinect(KinectSensor.KinectSensors[0]);
}
}
}