Repository: LightBuzz/Kinect-Finger-Tracking Branch: master Commit: 4c26265f37c4 Files: 26 Total size: 76.6 KB Directory structure: gitextract_0v08iils/ ├── .gitattributes ├── .gitignore ├── KinectFingerTracking/ │ ├── KinectFingerTracking/ │ │ ├── App.config │ │ ├── App.xaml │ │ ├── App.xaml.cs │ │ ├── KinectFingerTracking.csproj │ │ ├── MainWindow.xaml │ │ ├── MainWindow.xaml.cs │ │ ├── Properties/ │ │ │ ├── AssemblyInfo.cs │ │ │ ├── Resources.Designer.cs │ │ │ ├── Resources.resx │ │ │ ├── Settings.Designer.cs │ │ │ └── Settings.settings │ │ └── Utilities/ │ │ └── Bitmaps.cs │ ├── KinectFingerTracking.sln │ └── LightBuzz.Vitruvius.FingerTracking/ │ ├── DepthPointEx.cs │ ├── Finger.cs │ ├── GrahamScan.cs │ ├── Hand.cs │ ├── HandCollection.cs │ ├── HandsController.cs │ ├── LightBuzz.Vitruvius.FingerTracking.csproj │ ├── PointFilter.cs │ └── Properties/ │ └── AssemblyInfo.cs ├── LICENSE └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ ############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### #*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ build/ bld/ [Bb]in/ [Oo]bj/ # Visual Studo 2015 cache/options directory .vs/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opensdf *.sdf *.cachefile # Visual Studio profiler *.psess *.vsp *.vspx # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding addin-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # NCrunch _NCrunch_* .*crunch*.local.xml # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # Windows Azure Build Output csx/ *.build.csdef # Windows Store app package directory AppPackages/ # Others *.[Cc]ache ClientBin/ [Ss]tyle[Cc]op.* ~$* *~ *.dbmdl *.dbproj.schemaview *.pfx *.publishsettings node_modules/ bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # Node.js Tools for Visual Studio .ntvs_analysis.dat # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt ================================================ FILE: KinectFingerTracking/KinectFingerTracking/App.config ================================================  ================================================ FILE: KinectFingerTracking/KinectFingerTracking/App.xaml ================================================  ================================================ FILE: KinectFingerTracking/KinectFingerTracking/App.xaml.cs ================================================ using System.Windows; namespace KinectFingerTracking { /// /// Interaction logic for App.xaml /// public partial class App : Application { } } ================================================ FILE: KinectFingerTracking/KinectFingerTracking/KinectFingerTracking.csproj ================================================  Debug AnyCPU {EFC6031A-3B01-418F-9E48-798DD0802D35} WinExe Properties KinectFingerTracking KinectFingerTracking v4.5 512 {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 4 AnyCPU true full true bin\Debug\ DEBUG;TRACE prompt 4 true AnyCPU pdbonly true bin\Release\ TRACE prompt 4 4.0 MSBuild:Compile Designer MSBuild:Compile Designer App.xaml Code MainWindow.xaml Code Code True True Resources.resx True Settings.settings True ResXFileCodeGenerator Resources.Designer.cs SettingsSingleFileGenerator Settings.Designer.cs {c7312bb5-22eb-4b9c-9552-c97f0ecd0663} LightBuzz.Vitruvius.FingerTracking ================================================ FILE: KinectFingerTracking/KinectFingerTracking/MainWindow.xaml ================================================  ================================================ FILE: KinectFingerTracking/KinectFingerTracking/MainWindow.xaml.cs ================================================ using LightBuzz.Vitruvius.FingerTracking; using Microsoft.Kinect; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace KinectFingerTracking { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { private KinectSensor _sensor = null; private InfraredFrameReader _infraredReader = null; private DepthFrameReader _depthReader = null; private BodyFrameReader _bodyReader = null; private IList _bodies; private Body _body; // Create a new reference of a HandsController. private HandsController _handsController = null; /// /// The main window of the app. /// public MainWindow() { InitializeComponent(); _sensor = KinectSensor.GetDefault(); if (_sensor != null) { _depthReader = _sensor.DepthFrameSource.OpenReader(); _depthReader.FrameArrived += DepthReader_FrameArrived; _infraredReader = _sensor.InfraredFrameSource.OpenReader(); _infraredReader.FrameArrived += InfraredReader_FrameArrived; _bodyReader = _sensor.BodyFrameSource.OpenReader(); _bodyReader.FrameArrived += BodyReader_FrameArrived; _bodies = new Body[_sensor.BodyFrameSource.BodyCount]; // Initialize the HandsController and subscribe to the HandsDetected event. _handsController = new HandsController(); _handsController.HandsDetected += HandsController_HandsDetected; _sensor.Open(); } } private void DepthReader_FrameArrived(object sender, DepthFrameArrivedEventArgs e) { canvas.Children.Clear(); using (DepthFrame frame = e.FrameReference.AcquireFrame()) { if (frame != null) { // 2) Update the HandsController using the array (or pointer) of the depth depth data, and the tracked body. using (KinectBuffer buffer = frame.LockImageBuffer()) { _handsController.Update(buffer.UnderlyingBuffer, _body); } } } } private void InfraredReader_FrameArrived(object sender, InfraredFrameArrivedEventArgs e) { using (var frame = e.FrameReference.AcquireFrame()) { if (frame != null) { camera.Source = frame.ToBitmap(); } } } private void BodyReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e) { using (var bodyFrame = e.FrameReference.AcquireFrame()) { if (bodyFrame != null) { bodyFrame.GetAndRefreshBodyData(_bodies); _body = _bodies.Where(b => b.IsTracked).FirstOrDefault(); } } } private void HandsController_HandsDetected(object sender, HandCollection e) { // Display the results! if (e.HandLeft != null) { // Draw contour. foreach (var point in e.HandLeft.ContourDepth) { DrawEllipse(point, Brushes.Green, 2.0); } // Draw fingers. foreach (var finger in e.HandLeft.Fingers) { DrawEllipse(finger.DepthPoint, Brushes.White, 4.0); } } if (e.HandRight != null) { // Draw contour. foreach (var point in e.HandRight.ContourDepth) { DrawEllipse(point, Brushes.Blue, 2.0); } // Draw fingers. foreach (var finger in e.HandRight.Fingers) { DrawEllipse(finger.DepthPoint, Brushes.White, 4.0); } } } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (_bodyReader != null) { _bodyReader.Dispose(); _bodyReader = null; } if (_depthReader != null) { _depthReader.Dispose(); _depthReader = null; } if (_infraredReader != null) { _infraredReader.Dispose(); _infraredReader = null; } if (_sensor != null) { _sensor.Close(); _sensor = null; } } private void DrawEllipse(DepthSpacePoint point, Brush brush, double radius) { Ellipse ellipse = new Ellipse { Width = radius, Height = radius, Fill = brush }; canvas.Children.Add(ellipse); Canvas.SetLeft(ellipse, point.X - radius / 2.0); Canvas.SetTop(ellipse, point.Y - radius / 2.0); } } } ================================================ FILE: KinectFingerTracking/KinectFingerTracking/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KinectFingerTracking")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("KinectFingerTracking")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //CultureYouAreCodingWith in your .csproj file //inside a . For example, if you are using US english //in your source files, set the to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: KinectFingerTracking/KinectFingerTracking/Properties/Resources.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace KinectFingerTracking.Properties { /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("KinectFingerTracking.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } } ================================================ FILE: KinectFingerTracking/KinectFingerTracking/Properties/Resources.resx ================================================  text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ================================================ FILE: KinectFingerTracking/KinectFingerTracking/Properties/Settings.Designer.cs ================================================ //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace KinectFingerTracking.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } } ================================================ FILE: KinectFingerTracking/KinectFingerTracking/Properties/Settings.settings ================================================  ================================================ FILE: KinectFingerTracking/KinectFingerTracking/Utilities/Bitmaps.cs ================================================ using Microsoft.Kinect; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace KinectFingerTracking { internal class InfraredBitmapGenerator { public int Width { get; protected set; } public int Height { get; protected set; } public ushort[] InfraredData { get; protected set; } public byte[] Pixels { get; protected set; } public WriteableBitmap Bitmap { get; protected set; } public void Update(InfraredFrame frame) { if (Bitmap == null) { Width = frame.FrameDescription.Width; Height = frame.FrameDescription.Height; InfraredData = new ushort[Width * Height]; Pixels = new byte[Width * Height * 4]; Bitmap = new WriteableBitmap(Width, Height, 96.0, 96.0, PixelFormats.Bgr32, null); } frame.CopyFrameDataToArray(InfraredData); int colorIndex = 0; for (int infraredIndex = 0; infraredIndex < InfraredData.Length; infraredIndex++) { ushort ir = InfraredData[infraredIndex]; byte intensity = (byte)(ir >> 6); Pixels[colorIndex++] = intensity; // Blue Pixels[colorIndex++] = intensity; // Green Pixels[colorIndex++] = intensity; // Red colorIndex++; } Bitmap.Lock(); Marshal.Copy(Pixels, 0, Bitmap.BackBuffer, Pixels.Length); Bitmap.AddDirtyRect(new Int32Rect(0, 0, Width, Height)); Bitmap.Unlock(); } } internal static class BitmapExtensions { private static InfraredBitmapGenerator _bitmapGenerator = new InfraredBitmapGenerator(); public static WriteableBitmap ToBitmap(this InfraredFrame frame) { _bitmapGenerator.Update(frame); return _bitmapGenerator.Bitmap; } } } ================================================ FILE: KinectFingerTracking/KinectFingerTracking.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KinectFingerTracking", "KinectFingerTracking\KinectFingerTracking.csproj", "{EFC6031A-3B01-418F-9E48-798DD0802D35}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightBuzz.Vitruvius.FingerTracking", "LightBuzz.Vitruvius.FingerTracking\LightBuzz.Vitruvius.FingerTracking.csproj", "{C7312BB5-22EB-4B9C-9552-C97F0ECD0663}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EFC6031A-3B01-418F-9E48-798DD0802D35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EFC6031A-3B01-418F-9E48-798DD0802D35}.Debug|Any CPU.Build.0 = Debug|Any CPU {EFC6031A-3B01-418F-9E48-798DD0802D35}.Release|Any CPU.ActiveCfg = Release|Any CPU {EFC6031A-3B01-418F-9E48-798DD0802D35}.Release|Any CPU.Build.0 = Release|Any CPU {C7312BB5-22EB-4B9C-9552-C97F0ECD0663}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C7312BB5-22EB-4B9C-9552-C97F0ECD0663}.Debug|Any CPU.Build.0 = Debug|Any CPU {C7312BB5-22EB-4B9C-9552-C97F0ECD0663}.Release|Any CPU.ActiveCfg = Release|Any CPU {C7312BB5-22EB-4B9C-9552-C97F0ECD0663}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/DepthPointEx.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Windows; namespace LightBuzz.Vitruvius.FingerTracking { internal struct DepthPointEx { public float X; public float Y; public float Z; public static DepthPointEx Zero = new DepthPointEx(0, 0, 0); public DepthPointEx(DepthPointEx point) : this() { X = point.X; Y = point.Y; Z = point.Z; } public DepthPointEx(float x, float y, float z) : this() { X = x; Y = y; Z = z; } public static double Distance(DepthPointEx p1, DepthPointEx p2) { return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2) + Math.Pow(p1.Z - p2.Z, 2)); } public static double Distance(double x1, double y1, double x2, double y2) { return Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2)); } public static DepthPointEx Center(DepthPointEx p1, DepthPointEx p2) { return new DepthPointEx((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2, (p1.Z + p2.Z) / 2); } public static DepthPointEx Center(IList points) { var center = DepthPointEx.Zero; if (points.Count > 0) { for (int index = 0; index < points.Count; index++) { var p = points[index]; center.X += p.X; center.Y += p.Y; center.Z += p.Z; } center.X /= points.Count; center.Y /= points.Count; center.Z /= points.Count; } return center; } public static DepthPointEx FindNearestPoint(DepthPointEx target, IEnumerable points) { var pointList = points.ToList(); return pointList[FindIndexOfNearestPoint(target, pointList)]; } public static int FindIndexOfNearestPoint(DepthPointEx target, IList points) { int index = 0; int resultIndex = -1; double minDist = double.MaxValue; foreach (DepthPointEx p in points) { var distance = Distance(p.X, p.Y, target.X, target.Y); if (distance < minDist) { resultIndex = index; minDist = distance; } index++; } return resultIndex; } public static double Angle(DepthPointEx center, DepthPointEx start, DepthPointEx end) { return Angle(center.X, center.Y, start.X, start.Y, end.X, end.Y); } public static double Angle(float centerX, float centerY, float startX, float startY, float endX, float endY) { Vector first = new Vector(startX - centerX, startY - centerY); Vector second = new Vector(endX - centerX, endY - centerY); return Vector.AngleBetween(first, second); } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/Finger.cs ================================================ using Microsoft.Kinect; namespace LightBuzz.Vitruvius.FingerTracking { /// /// Represents a finger tip. /// public class Finger { /// /// The position of the fingertip in the 3D Camera space. /// public CameraSpacePoint CameraPoint { get; set; } /// /// The position of the fingertip in the 2D Depth space. /// public DepthSpacePoint DepthPoint { get; set; } /// /// The position of the fingertip in the 2D Color space. /// public ColorSpacePoint ColorPoint { get; set; } internal Finger(DepthPointEx point, CoordinateMapper coordinateMapper) { ushort depth = (ushort)point.Z; DepthPoint = new DepthSpacePoint { X = point.X, Y = point.Y }; ColorPoint = coordinateMapper.MapDepthPointToColorSpace(DepthPoint, (ushort)point.Z); CameraPoint = coordinateMapper.MapDepthPointToCameraSpace(DepthPoint, (ushort)point.Z); } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/GrahamScan.cs ================================================ using System.Collections.Generic; using System.Linq; namespace LightBuzz.Vitruvius.FingerTracking { internal class GrahamScan { private IList _points; public IList ConvexHull(IList points) { if (points.Count <= 3) { return points; } _points = points; var pointsSortedByAngle = SortPoints(); int index = 1; while (index + 1 < pointsSortedByAngle.Count) { var value = PointAngleComparer.Compare(pointsSortedByAngle[index - 1], pointsSortedByAngle[index + 1], pointsSortedByAngle[index]); if (value < 0) { index++; } else { pointsSortedByAngle.RemoveAt(index); if (index > 1) { index--; } } } pointsSortedByAngle.Add(pointsSortedByAngle.First()); return pointsSortedByAngle; } private DepthPointEx GetMinimumPoint() { var minPoint = _points[0]; for (int index = 1; index < _points.Count; index++) { minPoint = GetMinimumPoint(minPoint, _points[index]); } return minPoint; } private DepthPointEx GetMinimumPoint(DepthPointEx p1, DepthPointEx p2) { if (p1.Y < p2.Y) { return p1; } else if (p1.Y == p2.Y) { if (p1.X < p2.X) { return p1; } } return p2; } private IList SortPoints() { var p0 = GetMinimumPoint(); var comparer = new PointAngleComparer(p0); var sortedPoints = new List(_points); sortedPoints.Remove(p0); sortedPoints.Insert(0, p0); sortedPoints.Sort(1, sortedPoints.Count - 1, comparer); return sortedPoints; } } internal class PointAngleComparer : IComparer { private DepthPointEx p0; public PointAngleComparer(DepthPointEx zeroPoint) { p0 = zeroPoint; } public int Compare(DepthPointEx p1, DepthPointEx p2) { if (p1.Equals(p2)) { return 0; } float value = Compare(p0, p1, p2); if (value == 0) { return 0; } if (value < 0) { return 1; } return -1; } public static float Compare(DepthPointEx p0, DepthPointEx p1, DepthPointEx p2) { return (p1.X - p0.X) * (p2.Y - p0.Y) - (p2.X - p0.X) * (p1.Y - p0.Y); } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/Hand.cs ================================================ using Microsoft.Kinect; using System.Collections.Generic; using System.Linq; namespace LightBuzz.Vitruvius.FingerTracking { /// /// Represents a hand. /// public class Hand { /// /// The tracking ID of the body the current hand belongs to. /// public ulong TrackingId { get; protected set; } /// /// A list of the detected fingers. /// public IList Fingers { get; protected set; } /// /// A list of the contour points in the 3D Camera space. /// public IList ContourCamera { get; protected set; } /// /// A list of the contour points in the 2D Depth space. /// public IList ContourDepth { get; protected set; } /// /// A list of the countour points in the 2D Color space. /// public IList ContourColor { get; protected set; } internal Hand(ulong trackingID, HandState state, IList contour, IList fingers, CoordinateMapper coordinateMapper) { TrackingId = trackingID; if (state == HandState.Open) { Fingers = fingers.Select(f => new Finger(f, coordinateMapper)).ToList(); } else { Fingers = new List(); } ushort[] depths = contour.Select(d => (ushort)d.Z).ToArray(); ContourDepth = contour.Select(p => new DepthSpacePoint { X = p.X, Y = p.Y }).ToArray(); ContourCamera = new CameraSpacePoint[ContourDepth.Count]; coordinateMapper.MapDepthPointsToCameraSpace((DepthSpacePoint[])ContourDepth, depths, (CameraSpacePoint[])ContourCamera); ContourColor = new ColorSpacePoint[ContourDepth.Count]; coordinateMapper.MapDepthPointsToColorSpace((DepthSpacePoint[])ContourDepth, depths, (ColorSpacePoint[])ContourColor); } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/HandCollection.cs ================================================ namespace LightBuzz.Vitruvius.FingerTracking { /// /// A collection of hands for a specific Body. /// public class HandCollection { /// /// The tracking ID of the current body. /// public ulong TrackingId { get; set; } /// /// The left hand data of the current body. /// public Hand HandLeft { get; set; } /// /// The right hand data of the current body. /// public Hand HandRight { get; set; } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/HandsController.cs ================================================ using Microsoft.Kinect; using System; using System.Collections.Generic; using System.Linq; namespace LightBuzz.Vitruvius.FingerTracking { /// /// Detects human hands in the 3D and 2D space. /// public class HandsController { private readonly int DEFAULT_DEPTH_WIDTH = 512; private readonly int DEFAULT_DEPTH_HEIGHT = 424; private readonly ushort MIN_DEPTH = 500; private readonly ushort MAX_DEPTH = ushort.MaxValue; private readonly float DEPTH_THRESHOLD = 80; // 8cm private GrahamScan _grahamScan = new GrahamScan(); private PointFilter _lineThinner = new PointFilter(); private byte[] _handPixelsLeft = null; private byte[] _handPixelsRight = null; /// /// The width of the depth frame. /// public int DepthWidth { get; set; } /// /// the height of the depth frame. /// public int DepthHeight { get; set; } /// /// The coordinate mapper that will be used during the finger detection process. /// public CoordinateMapper CoordinateMapper { get; set; } /// /// Determines whether the algorithm will detect the left hand. /// public bool DetectLeftHand { get; set; } /// /// Determines whether the algorithm will detect the right hand. /// public bool DetectRightHand { get; set; } /// /// Raised when a new pair of hands is detected. /// public event EventHandler HandsDetected; /// /// Creates a new instance of . /// public HandsController() { CoordinateMapper = KinectSensor.GetDefault().CoordinateMapper; DetectLeftHand = true; DetectRightHand = true; } /// /// Creates a new instance of with the specified coordinate mapper. /// /// The coordinate mapper that will be used during the finger detection process. public HandsController(CoordinateMapper coordinateMapper) { CoordinateMapper = coordinateMapper; } /// /// Updates the finger-detection engine with the new data. /// /// An array of depth values. /// The body to search for hands and fingers. public unsafe void Update(ushort[] data, Body body) { fixed (ushort* frameData = data) { Update(frameData, body); } } /// /// Updates the finger-detection engine with the new data. /// /// An IntPtr that describes depth values. /// The body to search for hands and fingers. public unsafe void Update(IntPtr data, Body body) { ushort* frameData = (ushort*)data; Update(frameData, body); } /// /// Updates the finger-detection engine with the new data. /// /// A pointer to an array of depth data. /// The body to search for hands and fingers. public unsafe void Update(ushort* data, Body body) { if (data == null || body == null) return; if (DepthWidth == 0) { DepthWidth = DEFAULT_DEPTH_WIDTH; } if (DepthHeight == 0) { DepthHeight = DEFAULT_DEPTH_HEIGHT; } if (_handPixelsLeft == null) { _handPixelsLeft = new byte[DepthWidth * DepthHeight]; } if (_handPixelsRight == null) { _handPixelsRight = new byte[DepthWidth * DepthHeight]; } Hand handLeft = null; Hand handRight = null; Joint jointHandLeft = body.Joints[JointType.HandLeft]; Joint jointHandRight = body.Joints[JointType.HandRight]; Joint jointWristLeft = body.Joints[JointType.WristLeft]; Joint jointWristRight = body.Joints[JointType.WristRight]; Joint jointTipLeft = body.Joints[JointType.HandTipLeft]; Joint jointTipRight = body.Joints[JointType.HandTipRight]; Joint jointThumbLeft = body.Joints[JointType.ThumbLeft]; Joint jointThumbRight = body.Joints[JointType.ThumbRight]; DepthSpacePoint depthPointHandLeft = CoordinateMapper.MapCameraPointToDepthSpace(jointHandLeft.Position); DepthSpacePoint depthPointWristLeft = CoordinateMapper.MapCameraPointToDepthSpace(jointWristLeft.Position); DepthSpacePoint depthPointTipLeft = CoordinateMapper.MapCameraPointToDepthSpace(jointTipLeft.Position); DepthSpacePoint depthPointThumbLeft = CoordinateMapper.MapCameraPointToDepthSpace(jointThumbLeft.Position); DepthSpacePoint depthPointHandRight = CoordinateMapper.MapCameraPointToDepthSpace(jointHandRight.Position); DepthSpacePoint depthPointWristRight = CoordinateMapper.MapCameraPointToDepthSpace(jointWristRight.Position); DepthSpacePoint depthPointTipRight = CoordinateMapper.MapCameraPointToDepthSpace(jointTipRight.Position); DepthSpacePoint depthPointThumbRight = CoordinateMapper.MapCameraPointToDepthSpace(jointThumbRight.Position); float handLeftX = depthPointHandLeft.X; float handLeftY = depthPointHandLeft.Y; float wristLeftX = depthPointWristLeft.X; float wristLeftY = depthPointWristLeft.Y; float tipLeftX = depthPointTipLeft.X; float tipLeftY = depthPointTipLeft.Y; float thumbLeftX = depthPointThumbLeft.X; float thumbLeftY = depthPointThumbLeft.Y; float handRightX = depthPointHandRight.X; float handRightY = depthPointHandRight.Y; float wristRightX = depthPointWristRight.X; float wristRightY = depthPointWristRight.Y; float tipRightX = depthPointTipRight.X; float tipRightY = depthPointTipRight.Y; float thumbRightX = depthPointThumbRight.X; float thumbRightY = depthPointThumbRight.Y; bool searchForLeftHand = DetectLeftHand && !float.IsInfinity(handLeftX) && !float.IsInfinity(handLeftY) && !float.IsInfinity(wristLeftX) && !float.IsInfinity(wristLeftY) && !float.IsInfinity(tipLeftX) && !float.IsInfinity(tipLeftY) && !float.IsInfinity(thumbLeftX) && !float.IsInfinity(thumbLeftY); bool searchForRightHand = DetectRightHand && !float.IsInfinity(handRightX) && !float.IsInfinity(handRightY) && !float.IsInfinity(wristRightX) && !float.IsInfinity(wristRightY) && !float.IsInfinity(tipRightX) && !float.IsInfinity(tipRightY) && !float.IsInfinity(thumbRightX) && !float.IsInfinity(thumbRightY); if (searchForLeftHand || searchForRightHand) { double distanceLeft = searchForLeftHand ? CalculateDistance(handLeftX, handLeftY, tipLeftX, tipLeftY, thumbLeftX, thumbLeftY) : 0.0; double distanceRight = searchForRightHand ? CalculateDistance(handRightX, handRightY, tipRightX, tipRightY, thumbRightX, thumbRightY) : 0.0; double angleLeft = searchForLeftHand ? DepthPointEx.Angle(wristLeftX, wristLeftY, wristLeftX, 0, handLeftX, handLeftY) : 0.0; double angleRight = searchForRightHand ? DepthPointEx.Angle(wristRightX, wristRightY, wristRightX, 0, handRightX, handRightY) : 0.0; int minLeftX = searchForLeftHand ? (int)(handLeftX - distanceLeft) : 0; int minLeftY = searchForLeftHand ? (int)(handLeftY - distanceLeft) : 0; int maxLeftX = searchForLeftHand ? (int)(handLeftX + distanceLeft) : 0; int maxLeftY = searchForLeftHand ? (int)(handLeftY + distanceLeft) : 0; int minRightX = searchForRightHand ? (int)(handRightX - distanceRight) : 0; int minRightY = searchForRightHand ? (int)(handRightY - distanceRight) : 0; int maxRightX = searchForRightHand ? (int)(handRightX + distanceRight) : 0; int maxRightY = searchForRightHand ? (int)(handRightY + distanceRight) : 0; float depthLeft = jointHandLeft.Position.Z * 1000; // m to mm float depthRight = jointHandRight.Position.Z * 1000; for (int i = 0; i < DepthWidth * DepthHeight; ++i) { ushort depth = data[i]; int depthX = i % DepthWidth; int depthY = i / DepthWidth; bool isInBounds = depth >= MIN_DEPTH && depth <= MAX_DEPTH; bool conditionLeft = depth >= depthLeft - DEPTH_THRESHOLD && depth <= depthLeft + DEPTH_THRESHOLD && depthX >= minLeftX && depthX <= maxLeftX && depthY >= minLeftY && depthY <= maxLeftY; bool conditionRight = depth >= depthRight - DEPTH_THRESHOLD && depth <= depthRight + DEPTH_THRESHOLD && depthX >= minRightX && depthX <= maxRightX && depthY >= minRightY && depthY <= maxRightY; _handPixelsLeft[i] = (byte)(isInBounds && searchForLeftHand && conditionLeft ? 255 : 0); _handPixelsRight[i] = (byte)(isInBounds && searchForRightHand && conditionRight ? 255 : 0); } List contourLeft = new List(); List contourRight = new List(); for (int i = 0; i < DepthWidth * DepthHeight; ++i) { ushort depth = data[i]; int depthX = i % DepthWidth; int depthY = i / DepthWidth; if (searchForLeftHand) { if (_handPixelsLeft[i] != 0) { byte top = i - DepthWidth >= 0 ? _handPixelsLeft[i - DepthWidth] : (byte)0; byte bottom = i + DepthWidth < _handPixelsLeft.Length ? _handPixelsLeft[i + DepthWidth] : (byte)0; byte left = i - 1 >= 0 ? _handPixelsLeft[i - 1] : (byte)0; byte right = i + 1 < _handPixelsLeft.Length ? _handPixelsLeft[i + 1] : (byte)0; bool isInContour = top == 0 || bottom == 0 || left == 0 || right == 0; if (isInContour) { contourLeft.Add(new DepthPointEx { X = depthX, Y = depthY, Z = depth }); } } } if (searchForRightHand) { if (_handPixelsRight[i] != 0) { byte top = i - DepthWidth >= 0 ? _handPixelsRight[i - DepthWidth] : (byte)0; byte bottom = i + DepthWidth < _handPixelsRight.Length ? _handPixelsRight[i + DepthWidth] : (byte)0; byte left = i - 1 >= 0 ? _handPixelsRight[i - 1] : (byte)0; byte right = i + 1 < _handPixelsRight.Length ? _handPixelsRight[i + 1] : (byte)0; bool isInContour = top == 0 || bottom == 0 || left == 0 || right == 0; if (isInContour) { contourRight.Add(new DepthPointEx { X = depthX, Y = depthY, Z = depth }); } } } } if (searchForLeftHand) { handLeft = GetHand(body.TrackingId, body.HandLeftState, contourLeft, angleLeft, wristLeftX, wristLeftY); } if (searchForRightHand) { handRight = GetHand(body.TrackingId, body.HandRightState, contourRight, angleRight, wristRightX, wristRightY); } } if (handLeft != null || handRight != null) { HandCollection hands = new HandCollection { TrackingId = body.TrackingId, HandLeft = handLeft, HandRight = handRight }; if (HandsDetected != null) { HandsDetected(this, hands); } } } private double CalculateDistance(float handLeftX, float handLeftY, float tipLeftX, float tipLeftY, float thumbLeftX, float thumbLeftY) { double distanceLeftHandTip = Math.Sqrt(Math.Pow(tipLeftX - handLeftX, 2) + Math.Pow(tipLeftY - handLeftY, 2)) * 2; double distanceLeftHandThumb = Math.Sqrt(Math.Pow(thumbLeftX - handLeftX, 2) + Math.Pow(thumbLeftY - handLeftY, 2)) * 2; return Math.Max(distanceLeftHandTip, distanceLeftHandThumb); } private Hand GetHand(ulong trackingID, HandState state, List contour, double angle, float wristX, float wristY) { IList convexHull = _grahamScan.ConvexHull(contour); IList filtered = _lineThinner.Filter(convexHull); IList fingers = new List(); if (angle > -90.0 && angle < 30.0) { // Hand "up". fingers = filtered.Where(p => p.Y < wristY).Take(5).ToList(); } else if (angle >= 30.0 && angle < 90.0) { // Thumb below wrist (sometimes). fingers = filtered.Where(p => p.X > wristX).Take(5).ToList(); } else if (angle >= 90.0 && angle < 180.0) { fingers = filtered.Where(p => p.Y > wristY).Take(5).ToList(); } else { fingers = filtered.Where(p => p.X < wristX).Take(5).ToList(); } if (contour.Count > 0 && fingers.Count > 0) { return new Hand(trackingID, state, contour, fingers, CoordinateMapper); } return null; } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/LightBuzz.Vitruvius.FingerTracking.csproj ================================================  Debug AnyCPU {C7312BB5-22EB-4B9C-9552-C97F0ECD0663} Library Properties LightBuzz.Vitruvius.FingerTracking LightBuzz.Vitruvius.FingerTracking v4.5 512 true full true bin\Debug\ DEBUG;TRACE prompt 4 true bin\Debug\LightBuzz.Vitruvius.FingerTracking.XML pdbonly true bin\Release\ TRACE prompt 4 true ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/PointFilter.cs ================================================ using System.Collections.Generic; using System.Linq; namespace LightBuzz.Vitruvius.FingerTracking { internal class PointFilter { private readonly float MINIMUM_DISTANCE = 18f; public IList Filter(IList points) { IList result = new List(); if (points.Count > 0) { var point = new DepthPointEx(points.First()); result.Add(point); foreach (var currentSourcePoint in points.Skip(1)) { if (!PointsAreClose(currentSourcePoint, point)) { point = new DepthPointEx(currentSourcePoint); result.Add(point); } } if (result.Count > 1) { CheckFirstAndLastPoint(result); } } return result; } private void CheckFirstAndLastPoint(IList points) { if (PointsAreClose(points.Last(), points.First())) { points.RemoveAt(points.Count - 1); } } private bool PointsAreClose(DepthPointEx sourcePoint, DepthPointEx destPoint) { return DepthPointEx.Distance(sourcePoint, destPoint) < MINIMUM_DISTANCE; } } } ================================================ FILE: KinectFingerTracking/LightBuzz.Vitruvius.FingerTracking/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LightBuzz.Vitruvius.FingerTracking")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LightBuzz.Vitruvius.FingerTracking")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c7312bb5-22eb-4b9c-9552-c97f0ecd0663")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Kinect Finger Tracking The most accurate way to track fingers using Kinect v2. Why is it the best solution out there? * Tracks both hands simultaneously. * It lets you access the contour of the hand and the positions of the fingertips. * You can get the coordinates in the Depth, Color, and Camera space (3D and 2D). * Works between 0.5 and 5 meters (1.6 to 16 feet). * It is blazingly fast! ## Video [Watch on YouTube](https://youtu.be/YH_yiaxUm7k) ![Finger tracking with Kinect - Vangos Pterneas](http://pterneas.com/wp-content/uploads/2016/01/kinect-finger-tracking.png) ## Usage Finger Tracking is under the LightBuzz.Vitruvius.FingerTracking namespace. This namespace should be imported whenever you need to use the figner tracking capabilities. using LightBuzz.Vitruvius.FingerTracking; Everything is encapsulated into the HandsController class. To use the HandsController class, first create a new instace: private HandsController _handsController = new HandsController(); You can specify whether the controller will detect the left hand (DetectLeftHand property), the right hand (DetectRightHand property), or both hands. By default, the controller tracks both hands. Then, you'll need to subscribe to the HandsDetected event. This event is raised when a new set of hands is detected. _handsController.HandsDetected += HandsController_HandsDetected; Then, you have to udpate the HandsController with Depth and Body data. You'll need a DepthReader and a BodyReader (check the sample project for more details). private void DepthReader_FrameArrived(object sender, DepthFrameArrivedEventArgs e) { using (DepthFrame frame = e.FrameReference.AcquireFrame()) { if (frame != null) { using (KinectBuffer buffer = frame.LockImageBuffer()) { _handsController.Update(buffer.UnderlyingBuffer, _body); } } } } Finally, you can access the finger data by handling the HandsDetected event: private void HandsController_HandsDetected(object sender, HandCollection e) { if (e.HandLeft != null) { // Contour in the 2D depth space. var depthPoints = e.HandLeft.ContourDepth; // Contour in the 2D color space. var colorPoints = e.HandLeft.ContourColor; // Contour in the 3D camera space. var cameraPoints = e.HandLeft.ContourCamera; foreach (var finger in e.HandLeft.Fingers) { // Finger tip in the 2D depth space. var depthPoint = finger.DepthPoint; // Finger tip in the 2D color space. var colorPoint = finger.ColorPoint; // Finger tip in the 3D camera space. var cameraPoint = finger.CameraPoint; } } if (e.HandRight != null) { // Do something with the data... } } ## Contributors * [Vangos Pterneas](http://pterneas.com) from [LightBuzz](http://lightbuzz.com) ## License You are free to use these libraries in personal and commercial projects by attributing the original creator of the project. [View full License](https://github.com/LightBuzz/Kinect-Finger-Tracking/blob/master/LICENSE).