Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
//----------------------------------------------------------------------- // <copyright file="DtwGestureRecognizer.cs" company="Rhemyst and Rymix"> // Open Source. Do with this as you will. Include this statement or // don't - whatever you like. // // No warranty or support given. No guarantees this will work or meet // your needs. Some elements of this project have been tailored to // the authors' needs and therefore don't necessarily follow best // practice. Subsequent releases of this project will (probably) not // be compatible with different versions, so whatever you do, don't // overwrite your implementation with any new releases of this // project! // // Enjoy working with Kinect! // </copyright> //----------------------------------------------------------------------- using System.Diagnostics; namespace FitnectApp { using System; using System.Collections; internal class Fitnect { /// <summary> /// Size of obeservations vectors. /// </summary> private readonly int _dimension; /// <summary> /// Maximum distance between the last observations of each sequence. /// </summary> private readonly double _firstThreshold; /// <summary> /// Minimum length of a gesture before it can be recognised /// </summary> private readonly double _minimumLength; /// <summary> /// Maximum DTW distance between an example and a sequence being classified. /// </summary> private readonly double _globalThreshold; /// <summary> /// The gesture names. Index matches that of the sequences array in _sequences /// </summary> private readonly ArrayList _labels; /// <summary> /// Maximum vertical or horizontal steps in a row. /// </summary> private readonly int _maxSlope; /// <summary> /// The recorded gesture sequences /// </summary> private readonly ArrayList _sequences; private int _currentMouvementId; private int _ScorePositif; private int _ScoreNegatif; private int _lastMouvement; /// <summary> /// Initializes a new instance of the DtwGestureRecognizer class /// First DTW constructor /// </summary> /// <param name="dim">Vector size</param> /// <param name="threshold">Maximum distance between the last observations of each sequence</param> /// <param name="firstThreshold">Minimum threshold</param> public Fitnect(int dim, double threshold, double firstThreshold, double minLen) { _dimension = dim; _sequences = new ArrayList(); _labels = new ArrayList(); _globalThreshold = threshold; _firstThreshold = firstThreshold; _maxSlope = int.MaxValue; _minimumLength = minLen; _ScoreNegatif = 0; _ScorePositif = 0; } /// <summary> /// Initializes a new instance of the DtwGestureRecognizer class /// Second DTW constructor /// </summary> /// <param name="dim">Vector size</param> /// <param name="threshold">Maximum distance between the last observations of each sequence</param> /// <param name="firstThreshold">Minimum threshold</param> /// <param name="ms">Maximum vertical or horizontal steps in a row</param> public Fitnect(int dim, double threshold, double firstThreshold, int ms, double minLen) { _dimension = dim; _sequences = new ArrayList(); _labels = new ArrayList(); _globalThreshold = threshold; _firstThreshold = firstThreshold; _maxSlope = ms; _minimumLength = minLen; } /// <summary> /// Add a seqence with a label to the known sequences library. /// The gesture MUST start on the first observation of the sequence and end on the last one. /// Sequences may have different lengths. /// </summary> /// <param name="seq">The sequence</param> /// <param name="lab">Sequence name</param> public void AddOrUpdate(ArrayList seq, string lab) { // First we check whether there is already a recording for this label. If so overwrite it, otherwise add a new entry int existingIndex = -1; for (int i = 0; i < _labels.Count; i++) { if ((string)_labels[i] == lab) { existingIndex = i; } } // If we have a match then remove the entries at the existing index to avoid duplicates. We will add the new entries later anyway if (existingIndex >= 0) { _sequences.RemoveAt(existingIndex); _labels.RemoveAt(existingIndex); } // Add the new entries _sequences.Add(seq); _labels.Add(lab); } /// <summary> /// Recognize gesture in the given sequence. /// It will always assume that the gesture ends on the last observation of that sequence. /// If the distance between the last observations of each sequence is too great, or if the overall DTW distance between the two sequence is too great, no gesture will be recognized. /// </summary> /// <param name="seq">The sequence to recognise</param> /// <returns>The recognised gesture name</returns> public string Recognize(ArrayList seq) { double minDist = double.PositiveInfinity; string classification = "__UNKNOWN"; for (int i = 0; i < _sequences.Count; i++) { var example = (ArrayList)_sequences[i]; ////Debug.WriteLine(Dist2((double[]) seq[seq.Count - 1], (double[]) example[example.Count - 1])); if (Dist2((double[])seq[seq.Count - 1], (double[])example[example.Count - 1]) < _firstThreshold) { double d = Dtw(seq, example) / example.Count; if (d < minDist) { minDist = d; classification = (string)_labels[i]; if (_currentMouvementId == i) { nextMouvment(); _ScorePositif++; } else if (minDist < _globalThreshold) { _lastMouvement = i; _ScoreNegatif++; } //else //{ // _ScoreNegatif++; //} } } } return (minDist < _globalThreshold ? classification : "__UNKNOWN") + " " /*+minDist.ToString()*/; } /// <summary> /// Retrieves a text represeantation of the _label and its associated _sequence /// For use in dispaying debug information and for saving to file /// </summary> /// <returns>A string containing all recorded gestures and their names</returns> public string RetrieveText() { string retStr = String.Empty; if (_sequences != null) { // Iterate through each gesture for (int gestureNum = 0; gestureNum < _sequences.Count; gestureNum++) { // Echo the label retStr += _labels[gestureNum] + "\r\n"; int frameNum = 0; //Iterate through each frame of this gesture foreach (double[] frame in ((ArrayList)_sequences[gestureNum])) { // Extract each double foreach (double dub in (double[])frame) { retStr += dub + "\r\n"; } // Signifies end of this double retStr += "~\r\n"; frameNum++; } // Signifies end of this gesture retStr += "----"; if (gestureNum < _sequences.Count - 1) { retStr += "\r\n"; } } } return retStr; } /// <summary> /// Compute the min DTW distance between seq2 and all possible endings of seq1. /// </summary> /// <param name="seq1">The first array of sequences to compare</param> /// <param name="seq2">The second array of sequences to compare</param> /// <returns>The best match</returns> public double Dtw(ArrayList seq1, ArrayList seq2) { // Init var seq1R = new ArrayList(seq1); seq1R.Reverse(); var seq2R = new ArrayList(seq2); seq2R.Reverse(); var tab = new double[seq1R.Count + 1, seq2R.Count + 1]; var slopeI = new int[seq1R.Count + 1, seq2R.Count + 1]; var slopeJ = new int[seq1R.Count + 1, seq2R.Count + 1]; for (int i = 0; i < seq1R.Count + 1; i++) { for (int j = 0; j < seq2R.Count + 1; j++) { tab[i, j] = double.PositiveInfinity; slopeI[i, j] = 0; slopeJ[i, j] = 0; } } tab[0, 0] = 0; // Dynamic computation of the DTW matrix. for (int i = 1; i < seq1R.Count + 1; i++) { for (int j = 1; j < seq2R.Count + 1; j++) { if (tab[i, j - 1] < tab[i - 1, j - 1] && tab[i, j - 1] < tab[i - 1, j] && slopeI[i, j - 1] < _maxSlope) { tab[i, j] = Dist2((double[])seq1R[i - 1], (double[])seq2R[j - 1]) + tab[i, j - 1]; slopeI[i, j] = slopeJ[i, j - 1] + 1; slopeJ[i, j] = 0; } else if (tab[i - 1, j] < tab[i - 1, j - 1] && tab[i - 1, j] < tab[i, j - 1] && slopeJ[i - 1, j] < _maxSlope) { tab[i, j] = Dist2((double[])seq1R[i - 1], (double[])seq2R[j - 1]) + tab[i - 1, j]; slopeI[i, j] = 0; slopeJ[i, j] = slopeJ[i - 1, j] + 1; } else { tab[i, j] = Dist2((double[])seq1R[i - 1], (double[])seq2R[j - 1]) + tab[i - 1, j - 1]; slopeI[i, j] = 0; slopeJ[i, j] = 0; } } } // Find best between seq2 and an ending (postfix) of seq1. double bestMatch = double.PositiveInfinity; for (int i = 1; i < (seq1R.Count + 1) - _minimumLength; i++) { if (tab[i, seq2R.Count] < bestMatch) { bestMatch = tab[i, seq2R.Count]; } } return bestMatch; } /// <summary> /// Computes a 1-distance between two observations. (aka Manhattan distance). /// </summary> /// <param name="a">Point a (double)</param> /// <param name="b">Point b (double)</param> /// <returns>Manhattan distance between the two points</returns> private double Dist1(double[] a, double[] b) { double d = 0; for (int i = 0; i < _dimension; i++) { d += Math.Abs(a[i] - b[i]); } return d; } /// <summary> /// Computes a 2-distance between two observations. (aka Euclidian distance). /// </summary> /// <param name="a">Point a (double)</param> /// <param name="b">Point b (double)</param> /// <returns>Euclidian distance between the two points</returns> private double Dist2(double[] a, double[] b) { double d = 0; for (int i = 0; i < _dimension; i++) { d += Math.Pow(a[i] - b[i], 2); } return Math.Sqrt(d); } private void nextMouvment() { _currentMouvementId++; _currentMouvementId = _currentMouvementId % _labels.Count; } public string getCurrentMouvement() { return (string)_labels[_currentMouvementId]; } public string getScorePositif() { return "" + _ScorePositif; } public string getScoreNegatif() { return "" + _ScoreNegatif; } } }
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
VinCheckUp
4 hours ago | 1.69 KB
Dark Warning 4
8 hours ago | 0.72 KB
Dark Warning 3
8 hours ago | 0.21 KB
Dark Warning 2
8 hours ago | 5.63 KB
Dark Warning 1
8 hours ago | 1.50 KB
BH V BD 2
8 hours ago | 2.07 KB
BH V BD 1
8 hours ago | 1.07 KB
Boba Fett Pursuit 3
8 hours ago | 6.33 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!