2012年8月26日日曜日

KINECTサンプル(VB) RGBカメラ for SDK1.5

KINECTのサンプル VB版です。

C#と同じ内容です。

開発環境は

Windows7 Ultimate 64bit SP1
Visual Basic 2010 Express
KINECT SDK 1.5
KINECT for Windows

となります。

WPFアプリケーションです。

プロジェクトの参照の追加で「Microsoft.Kinect」を追加するようにしてください。


MainWindow.xaml
------------------------------------------------------------------------------

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="520" Width="700">
    <Grid>
        <Image Name="Rgb" Stretch="Uniform" Height="480" Width="640" />
    </Grid>
</Window>
------------------------------------------------------------------------------

C#とまったく同じです。イメージコントロールを1つ配置しています。


MainWindow.xaml.vb
------------------------------------------------------------------------------
Imports Microsoft.Kinect

Class MainWindow

    Inherits Window

    Private kinect As KinectSensor
    Private colorPixel As Byte()

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub New()

        ' この呼び出しはデザイナーで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後で初期化を追加します。

        ''接続の確認
        If KinectSensor.KinectSensors.Count = 0 Then
            MessageBox.Show("KINECTが見つかりません。")
            Exit Sub
        End If

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

        kinect = KinectSensor.KinectSensors(0)

        ''RGBデータ用配列の初期化
        colorPixel = New Byte(kinect.ColorStream.FramePixelDataLength - 1) {}

        ''RGBカメラの設定
        kinect.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30)

        ''イベントの登録
        AddHandler kinect.ColorFrameReady, AddressOf kinect_colorFrameReady

        ''KINECTのスタート
        kinect.Start()

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub kinect_colorFrameReady(ByVal sender As Object, ByVal e As ColorImageFrameReadyEventArgs)

        Using colorFrame As ColorImageFrame = e.OpenColorImageFrame
            If colorFrame Is Nothing = False Then

                colorFrame.CopyPixelDataTo(colorPixel)

                Rgb.Source = BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Bgr32, Nothing, colorPixel, colorFrame.Width * colorFrame.BytesPerPixel)

            End If
        End Using

    End Sub
End Class
------------------------------------------------------------------------------

C#と比べてほとんど違いはありません。NullがNothingになるのをよく間違えますけど^^;

画像データを生成している箇所の説明を少しします。
イメージコントロールのソースを「BitmapSource.Create」で行っていますが、構文は

BitmapSource.Create( 
               画像の幅、
               画像の高さ、
               表示するDPIのX値(通常は96に固定)、
               表示するDPIのY値(通常は96に固定)、
               ビットマップのピクセル形式(BGR32が推奨?)、
               ビットマップのパレット(使わない?)、
               ビットマップを表すバイト配列(KINECTのRGBデータ)、
               ストライド(ビットマップの幅×1ピクセル当りのバイト数 32ビットなので4バイト)
               )

となります。

KINECTからのRGBデータ(バイト配列)を加工することによっていろいろな画像表示が可能になります。




2012年8月25日土曜日

KINECTサンプル(C#) RGBカメラ for SDK1.5

以前の投稿から時間が過ぎてしまいましたが、ここ最近また色々プログラムを書いているので備忘録として基本的なサンプルプログラムを掲載します。

開発環境は

Windows7 Ultimate 64bit SP1
Visual C# 2010 Express
KINECT SDK 1.5
KINECT for Windows

となります。

KINECT SDKは最新版をそのままインストールしているだけです。

サンプルはWPFアプリケーションです。

RGBカメラの画像を表示するサンプルです。

------------------------------------------------------------------------------
追記(2012/08/26)

プロジェクトの参照設定で「Microsoft.Kinect」を追加してください。
------------------------------------------------------------------------------


MainWindow.xaml
------------------------------------------------------------------------------

<Window x:Class="KinectRGBforSDK15.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="520" Width="700">
    <Grid>
        <Image Name="Rgb" Stretch="Uniform" Height="480" Width="640" />
    </Grid>
</Window>
------------------------------------------------------------------------------

イメージコントロールを1つだけ配置しています。

MainWindows.xaml.cs
------------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

using Microsoft.Kinect;

namespace KinectRGBforSDK15
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        KinectSensor kinect;

        public MainWindow()
        {
            InitializeComponent();

            //接続の確認
            if (KinectSensor.KinectSensors.Count == 0)
            {
                MessageBox.Show("KINECTが見つかりません。");
                Close();
            }

            kinect = KinectSensor.KinectSensors[0];

            //RGBカメラの設定
            kinect.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);

            //イベントの登録
            kinect.ColorFrameReady += new EventHandler<ColorImageFrameReadyEventArgs>(kinect_colorFrameReady);

            //KINECTのスタート
            kinect.Start();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void kinect_colorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {
            using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
            {
                if (colorFrame != null)
                {
                    //RGBカメラのビットイメージデータ
                    byte[] colorPixel = new byte[colorFrame.PixelDataLength];
                    colorFrame.CopyPixelDataTo(colorPixel);

                    //ビットマップイメージの作成
                    Rgb.Source = BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Bgr32, null, colorPixel, colorFrame.Width * colorFrame.BytesPerPixel);

                }
            }
        }

    }
}
------------------------------------------------------------------------------
エラー処理などは省略していますが、RGBカメラの画像を表示するだけならこれだけの記述でできます。

イベント内で取り出しているKINECTからのデータは32ビットのカラーイメージ(BGR8ビット+αチャンネル8ビット。ただしαチャンネルは0で固定  空きチャンネル8ビット)です。

これは640*480の画像1ピクセルを4バイトで表現していることになります。
WPFのイメージコントロールであつかえるビットマップイメージはBRG32形式に対応しているのでKINECTからのカラーイメージデータを元にそのままビットマップイメージを作ることができます。



2012年1月11日水曜日

WindowsAzure

はじめてKINECT以外のネタです。

WindowsAzureなんですが、ほとんど使ってません;;

インストールマニアックスに参加する時に使ったのですが、今のところ本業(業務システムの開発等)で使う機会がなくってそのままになってます。

どうせならKINECTと何か組み合わせてできればいいと思っているのですが、いいアイデアが浮かばないです。

ネタでAzureのキャラクターであるクラウディアさんとジャンケンするアプリを作っているところですが、Azureは全然使ってないです・・・・

2011年12月29日木曜日

KINECT SDK 日本語音声認識 SpeechPlatform11

今までのエントリーで利用してきた音声認識エンジンはSpeechPlatform10.2でした。
しかし、すでにSpeechPlatform11がリリースされています。
今回は新しいバージョンで動くのかチェックしてみました。

すでに10.2をインストールしている場合にはアンインストールする必要があります。

バージョン11のダウンロード先です。

SDK
http://www.microsoft.com/download/en/details.aspx?id=27226

リンク先にはx86用とx64用がありますが使用中のOSに合わせてダウンロードすればいいと思います。SDKは2つともインストールする必要はないでしょう。

Runtime
http://www.microsoft.com/download/en/details.aspx?id=27225

ランタイムはOSが64ビットの場合x86、x64ともにインストールする必要があると思います。


Runtime Languages
http://www.microsoft.com/download/en/details.aspx?id=27224

ダウンロードするファイルは「MSSpeech_SR_ja-JP_TELE.msi」になります。

上記のファイルをすべてインストールしてください。

プログラム上の変更点は認識エンジンのIDを設定する箇所を「SR_MS_ja-JP_TELE.11.0」に変更すればOKです。

ちなみにバージョン11では「SR_MS_en-US_Kinect.10.0」は利用できないので11用のRuntimeLanguageをダウンロードしましょう。


2011年12月26日月曜日

KINECT SDK 日本語で音声認識(VB+WPF)

KINECT SDKの音声認識サンプルプログラムはコンソールアプリでしたが、WPFでも動くようにしてみました。WPFの場合はUI部分と音声認識部分は別スレッドにする必要があります。

まずはXAMLソースです。

---------------------------------------------------------------------------------

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="241" Width="668">
    <Grid Name="Grid1" Height="151">
     
        <TextBox Height="54" HorizontalAlignment="Left" Margin="0,12,0,0" Name="TextBox1" VerticalAlignment="Top" Width="634" FontSize="20" Grid.ColumnSpan="2" Grid.RowSpan="2" />
        <TextBox Height="54" HorizontalAlignment="Left" Margin="0,72,0,0" Name="TextBox2" VerticalAlignment="Top" Width="634" FontSize="20" Grid.ColumnSpan="2" Grid.Row="1" Grid.RowSpan="2" />
    </Grid>
</Window>
--------------------------------------------------------------------------------- 

テキストボックスを2つ配置しています。

メインソースです。
--------------------------------------------------------------------------------- 

Imports Microsoft.Research.Kinect.Audio
Imports Microsoft.Research.Kinect.Nui
Imports Microsoft.Speech.AudioFormat
Imports Microsoft.Speech.Recognition
Imports System.Media
Imports System.IO
Imports System.Threading
Imports System.Windows.Threading

Class MainWindow
    Inherits Window

    Private nui As Runtime
    Private cam As Camera
    Private readerThread As Thread

    Const ri_ID As String = "SR_MS_ja-JP_TELE_10.0"

    Public Sub New()

        ' この呼び出しはデザイナーで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後で初期化を追加します。
        If Runtime.Kinects.Count > 0 Then
            ''KINECT初期化
            nui = Runtime.Kinects(0)
            nui.Initialize(RuntimeOptions.UseColor)
            cam = nui.NuiCamera

            camInit()
        Else
            MsgBox("KINECTが見つかりません。")
            Exit Sub
        End If

    End Sub

    Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

        ''音声認識スレッド
        readerThread = New Thread(New ThreadStart(AddressOf SpeechThread))

        ''スレッドスタート
        readerThread.Start()

    End Sub

    Private Sub SpeechThread()


        ''音声認識準備
        Dim source = New KinectAudioSource()

        With source
            .FeatureMode = True
            .AutomaticGainControl = False
            .SystemMode = SystemMode.OptibeamArrayOnly
        End With

        ''認識エンジン選択
        Dim ri As RecognizerInfo = GetKinectRecognizer()

        If IsNothing(ri) = True Then
            MsgBox("認識エンジンが見つかりませんでした。")
            Exit Sub
        End If

        Me.Dispatcher.BeginInvoke(DispatcherPriority.Background, New Action(
                                  Sub()
                                      TextBox1.Text = ri.Name
                                  End Sub))


        Dim sre As New SpeechRecognitionEngine(ri.Id)
        Dim w As New Choices

        With w
            .Add("うえ")
            .Add("した")
            .Add("最初")
            .Add("終わり")
        End With

        Dim gb As New GrammarBuilder

        gb.Culture = ri.Culture
        gb.Append(w)

        Dim g As New Grammar(gb)

        sre.LoadGrammar(g)

        AddHandler sre.SpeechRecognized, AddressOf SreSpeechRecognized
        AddHandler sre.SpeechRecognitionRejected, AddressOf SreSpeechRecognitionRejected


        Dim s As Stream = source.Start
        sre.SetInputToAudioStream(s,
                                  New SpeechAudioFormatInfo(EncodingFormat.Pcm,
                                                            16000,
                                                            16,
                                                            1,
                                                            32000,
                                                            2,
                                                            Nothing))



        sre.RecognizeAsync(RecognizeMode.Multiple)

    End Sub

    Private Sub camInit()
        ''カメラ初期位置
        cam.ElevationAngle = 0
    End Sub

    Private Sub camUp()
        ''カメラ上向き
        Dim nowangle = cam.ElevationAngle + 5
        If nowangle > 25 Then
            cam.ElevationAngle = 25
        Else
            cam.ElevationAngle = nowangle
        End If
    End Sub

    Private Sub camDown()
        ''カメラ下向き
        Dim nowangle = cam.ElevationAngle - 5
        If nowangle < -25 Then
            cam.ElevationAngle = -25
        Else
            cam.ElevationAngle = nowangle
        End If
    End Sub

    Private Function GetKinectRecognizer()
        Return SpeechRecognitionEngine.InstalledRecognizers().Where(Function(r) r.Id = ri_ID).FirstOrDefault
    End Function

    Private Sub SreSpeechRecognized(ByVal sender As Object, ByVal e As SpeechRecognizedEventArgs)
        Me.Dispatcher.BeginInvoke(DispatcherPriority.Background, New Action(
                                  Sub()
                                      TextBox2.Text = "認識しました:" & e.Result.Text
                                  End Sub))


        Select Case e.Result.Text
            Case "うえ"
                camUp()
            Case "した"
                camDown()
            Case "最初"
                camInit()
                ''Case "終わり"

        End Select
    End Sub

    Private Sub SreSpeechRecognitionRejected(ByVal sender As Object, ByVal e As SpeechRecognitionRejectedEventArgs)
        Me.Dispatcher.BeginInvoke(DispatcherPriority.Background, New Action(
                                  Sub()
                                      TextBox2.Text = "認識できません。"
                                  End Sub))

    End Sub

    Private Sub Window_Unloaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Unloaded

        ''KINECT終了
        nui.Uninitialize()

        ''スレッド終了
        readerThread.Abort()

        readerThread.Join()

    End Sub
End Class
--------------------------------------------------------------------------------- 
UIスレッドでは音声スレッドのスタートのみ行っています。
コンソール版での音声認識部分を音声認識スレッドとしています。

2011年12月19日月曜日

KINECT SDK Beta2 でスケルトンデータを扱う( VB+ WPF )

このエントリはKINECT SDK Advent Calendar : ATNDの12月19日分です。
kaorun55氏の「KINECT SDK Beta2 でスケルトンデータを扱う( C# + WPF ) のVB版になります。

いつもと同じようにXAMLソースから
--------------------------------------------------------------------------------

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="521" Width="661">
    <Grid>
        <Image Height="480" Name="Image1" Width="640" />
    </Grid>
</Window>
--------------------------------------------------------------------------------
特別なところはありません。Imageコントロールが1つだけです。

メインソースです。
--------------------------------------------------------------------------------
Imports System.Threading
Imports System.Windows.Threading
Imports System.Windows.Media
Imports Microsoft.Research.Kinect.Nui

Class MainWindow
    Inherits Window

    Private readerThread As Thread
    Private shouldRun As Boolean
    Private kinect As Runtime
    Private usercolor() As Color = {Color.FromRgb(0, 0, 0), Colors.Red, Colors.Green, Colors.Blue, Colors.Yellow, Colors.Magenta, Colors.Pink}

    Public Sub New()

        ' この呼び出しはデザイナーで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後で初期化を追加します。

        If Runtime.Kinects.Count > 0 Then
            ''KINECT初期化
            kinect = Runtime.Kinects(0)
            kinect.Initialize(RuntimeOptions.UseColor Or RuntimeOptions.UseDepthAndPlayerIndex Or RuntimeOptions.UseSkeletalTracking)
            kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color)
            kinect.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex)

            ''スレッドの開始
            shouldRun = True
            readerThread = New Thread(New ThreadStart(AddressOf RenderThread))
            readerThread.Start()

        End If

    End Sub

    Sub RenderThread()

        While (shouldRun)

            ''タイムアウトは100ms
            Dim video As ImageFrame = kinect.VideoStream.GetNextFrame(100)
            Dim depth As ImageFrame = kinect.DepthStream.GetNextFrame(100)
            Dim skeleton As SkeletonFrame = kinect.SkeletonEngine.GetNextFrame(100)

            ''メインスレッドにイメージデータの書き込みを指示
            Me.Dispatcher.BeginInvoke(DispatcherPriority.Background, New Action(
                Sub()
                    Dim drawingVisual As New DrawingVisual

                    Using drawingContext As DrawingContext = drawingVisual.RenderOpen()
                        drawingContext.DrawImage(DrawPixels(kinect, video, depth), New Rect(0, 0, video.Image.Width, video.Image.Height))

                        ''骨格の部位ごとに座標を求める
                        For Each s In skeleton.Skeletons
                            If s.TrackingState = SkeletonTrackingState.Tracked Then
                                For Each j In s.Joints
                                    Dim point As Point = GetVideoPoint(j)

                                    '円を描く
                                    drawingContext.DrawEllipse(New SolidColorBrush(Colors.Red), New Pen(Brushes.Red, 1), New Point(point.X, point.Y), 5, 5)

                                Next
                            End If
                        Next
                    End Using

                    '描画可能なビットマップを作る
                    Dim bitmap As RenderTargetBitmap = New RenderTargetBitmap(video.Image.Width, video.Image.Height, 96, 96, PixelFormats.Default)
                    bitmap.Render(drawingVisual)

                    Image1.Source = bitmap

                End Sub
            ))

        End While

    End Sub

    Function DrawPixels(ByVal kinect As Runtime, ByVal video As ImageFrame, ByVal depth As ImageFrame) As WriteableBitmap
        Dim x, y, index As Integer
        Dim playerIndex, distance As Integer
        Dim videoX, videoY, videoIndex As Integer
        Dim byte0, byte1 As Byte

        'ピクセルごとのユーザーID
        For y = 0 To depth.Image.Height - 1
            For x = 0 To depth.Image.Width - 1
                index = (x + (y * depth.Image.Width)) * 2
                byte0 = depth.Image.Bits(index)
                byte1 = depth.Image.Bits(index + 1)

                'ユーザーIDと距離
                playerIndex = byte0 And &H7
                distance = byte1 << 5 Or byte0 >> 3

                If playerIndex <> 0 Then
                    videoX = 0
                    videoY = 0

                    ''深度データの座標からカラーデータの座標へ変換
                    kinect.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, New ImageViewArea(), x, y, 0, videoX, videoY)
                    videoIndex = (videoX + (videoY * video.Image.Width)) * video.Image.BytesPerPixel
                    videoIndex = Math.Min(videoX, video.Image.Bits.Length - video.Image.BytesPerPixel)
                    video.Image.Bits(videoIndex) = usercolor(playerIndex).R
                    video.Image.Bits(videoIndex + 1) = usercolor(playerIndex).G
                    video.Image.Bits(videoIndex + 2) = usercolor(playerIndex).B
                End If

            Next
        Next

        'バイト列をビットマップに展開
        '描画可能なビットマップを作る
        Dim bitmap As WriteableBitmap = New WriteableBitmap(video.Image.Width, video.Image.Height, 96, 96, PixelFormats.Bgr32, Nothing)
        bitmap.WritePixels(New Int32Rect(0, 0, video.Image.Width, video.Image.Height), video.Image.Bits, video.Image.Width * video.Image.BytesPerPixel, 0)

        Return bitmap

    End Function

    Function GetVideoPoint(ByVal joint As Joint) As Point

        Dim kinect As Runtime = Runtime.Kinects(0)
        Dim depthX, depthY As Single
        Dim videoX, videoY As Integer

        depthX = 0
        depthY = 0

        ''骨格データ(ベクタ座標)から深度データの座標へ変換
        kinect.SkeletonEngine.SkeletonToDepthImage(joint.Position, depthX, depthY)
        depthX = Math.Min(depthX * kinect.DepthStream.Width, kinect.DepthStream.Width)
        depthY = Math.Min(depthY * kinect.DepthStream.Height, kinect.DepthStream.Height)

        videoX = 0
        videoY = 0

        ''深度データの座標をカラーデータの座標に変換
        kinect.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, New ImageViewArea(), CInt(depthX), CInt(depthY), 0, videoX, videoY)

        Return New Point(Math.Min(videoX, kinect.VideoStream.Width), Math.Min(videoY, kinect.VideoStream.Height))

    End Function

    Private Sub Window_Unloaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Unloaded

        shouldRun = False

    End Sub
End Class
--------------------------------------------------------------------------------

Skeletonの座標データはKINECTを中心にXYZの3D座標になります。
XYは-1~1までの単精度浮動小数になるのでこれを2Dの座標に変換しなければいけないのですが、手順としてSkeleton座標>Depth(深度)座標>Video(カラー)座標の順番に変換しています。

Skeleton>Depthの変換はSkeletonToDepthImageで変換します。
Depth>Videoの変換はGetColorPixelCoordinatesFromDepthPixelを使って変換しています。

変換した座標をもとにShapeを描画すればVideo,Depthのイメージに骨格情報を重ねて表示できます。

2011年12月18日日曜日

KINECT SDK Beta2 でユーザーデータを扱う( VB + WPF )


このエントリはKINECT SDK Advent Calendar : ATNDの12月18日分です。

kaorun55氏の「KINECT SDK Beta2 でユーザーデータを扱う( C# + WPF )」 を参考にVBに書き換えました。

まずはXAMLソースから

--------------------------------------------------------------------------------

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="521" Width="661">
    <Grid>
        <Image Height="480" Name="Image1" Width="640" />
    </Grid>
</Window>
--------------------------------------------------------------------------------
今までのサンプルと同様です。

メインソースです。

--------------------------------------------------------------------------------
Imports Microsoft.Research.Kinect.Nui
Imports System.Threading
Imports System.Windows.Threading

Class MainWindow

    Inherits Window

    Private readerThread As Thread
    Private shuldRun As Boolean
    Private kinect As Runtime
    Private usercolor() As Color = {Color.FromRgb(0, 0, 0), Colors.Red, Colors.Green, Colors.Blue, Colors.Yellow, Colors.Magenta, Colors.Pink}

    Public Sub New()

        ' この呼び出しはデザイナーで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後で初期化を追加します。

    End Sub

    Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

        If Runtime.Kinects.Count > 0 Then

            ''KINECT初期化
            kinect = Runtime.Kinects(0)
            kinect.Initialize(RuntimeOptions.UseColor Or RuntimeOptions.UseDepthAndPlayerIndex)
            kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color)
            kinect.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex)

            shuldRun = True
            ''スレッド作成
            readerThread = New Thread(New ThreadStart(AddressOf RenderThread))
            ''スレッド開始
            readerThread.Start()

        End If

    End Sub

    Sub RenderThread()

        ''Imageコントロールに書き込むスレッド

        While (shuldRun)

            ''映像データの取り込み
            kinect = Runtime.Kinects(0)
            ''タイムアウトは100ms
            Dim video As ImageFrame = kinect.VideoStream.GetNextFrame(100)
            Dim depth As ImageFrame = kinect.DepthStream.GetNextFrame(100)


            For y = 0 To depth.Image.Height - 1
                For x = 0 To depth.Image.Width - 1
                    Dim index As Integer = (x + (y * depth.Image.Width)) * 2
                    Dim byte0 As Byte = depth.Image.Bits(index)
                    Dim byte1 As Byte = depth.Image.Bits(index + 1)

                    Dim playerIndex As Integer = byte0 And &H7
                    Dim distance As Integer = byte1 << 5 Or byte0 >> 3

                    If playerIndex <> 0 Then
                        Dim videoX As Integer = 0
                        Dim videoY As Integer = 0

                        ''深度データからカラーデータに座標変換
                        kinect.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, New ImageViewArea(), x, y, 0, videoX, videoY)

                        Dim videoIndex As Integer = (videoX + (videoY * video.Image.Width)) * video.Image.BytesPerPixel
                        videoIndex = Math.Min(videoIndex, video.Image.Bits.Length - video.Image.BytesPerPixel)
                        video.Image.Bits(videoIndex) = usercolor(playerIndex).R
                        video.Image.Bits(videoIndex + 1) = usercolor(playerIndex).G
                        video.Image.Bits(videoIndex + 2) = usercolor(playerIndex).B

                    End If
                Next
            Next

            ''メインスレッド経由でイメージの書込み
            Me.Dispatcher.BeginInvoke(DispatcherPriority.Background, New Action(
                Sub()
                    Image1.Source = BitmapImage.Create(video.Image.Width, video.Image.Height, 96, 96, PixelFormats.Bgr32, Nothing, video.Image.Bits, video.Image.Width * video.Image.BytesPerPixel)
                End Sub))

        End While

    End Sub

    Private Sub Window_Unloaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Unloaded

        shuldRun = False

    End Sub
End Class
--------------------------------------------------------------------------------

7人まで認識するはずですが、試していません。