Archive for category Code Sample
[#KINECTSDK] Kinect Missile Launcher (V): Video y codigo fuente
Publicado por elbruno en Code Sample, Kinect, KinectSdk, Video, Visual Studio 11 el 27 abril, 2012
Buenas.
Primero vamos con los links de la serie
- Identificando el dispositivo HID
- Moviendo el lanza misiles
- Otra forma de averiguar los valores para trabajar con el lanza misiles con C#
- Controlando el lanza misiles con Kinect
- Video y código fuente de ejemplo
Y ahora un video de 30 segundos donde muestro un pequeño ejemplo de la aplicación en funcionamiento.
Link : http://youtu.be/ATxtYes6pBQ
Un detalle, el misil sale con una potencia que ni en HALO, con lo que los pocos frames de la cámara de Kinect no lo pueden capturar en su vuelo. Otro detalle es que como puse el lanza misiles delante del Kinect para poder grabar el video, la captura del skeleton va un poco así así, con lo que puede hacer unos raros.
Y para terminar, el código fuente de la aplicación se puede descargar desde https://skydrive.live.com/redir.aspx?cid=bef06dffdb192125&resid=BEF06DFFDB192125!4275&parid=BEF06DFFDB192125!1932&authkey=!AOhNmp_md8XLYbo
Saludos @ Home
El Bruno
[#KINECTSDK] Kinect Missile Launcher (IV): Using the Rocket Launcher with Kinect
Publicado por elbruno en Code Sample, EnglishPost, KinectSdk, Visual Studio 11 el 26 abril, 2012
Buenas,
today already we will create an application that allows us to control the Lance missiles using Kinect gestures. For this I have thought of the following controls
- The right hand controls the direction of the Lance missiles. You can go to the right, left, up or down.
- The left hand controls the firing of the missile, shoot is raise your hand above the head.
- If both hands are below the waist stop movements of the Lance missile
On this basis, and taking advantage of Visual controls of "Microsoft.Samples.Kinect.WpfViewers" I created a WPF application with the following code in the main window
1: using System.Linq;
2: using System.Windows;
3: using Microsoft.Kinect;
4:
5: namespace ElBruno.Rocket.Ui
6: {
7: public partial class MainWindow
8: {
9: private KinectSensor _sensor;
10: private Rocket _rocket;
11: public MainWindow()
12: {
13: InitializeComponent();
14: Loaded += MainWindowLoaded;
15: }
16:
17: private void MainWindowLoaded(object sender, RoutedEventArgs e)
18: {
19: InitRocket();
20: InitKinectSensor();
21: }
22:
23: private void InitRocket()
24: {
25: _rocket = new Rocket(@"vid_0a81", @"pid_ff01");
26: _rocket.Connect();
27: }
28:
29: private void InitKinectSensor()
30: {
31: // validate
32: if (KinectSensor.KinectSensors.Count == 0) return;
33:
34: // init Kinect
35: var parameters = new TransformSmoothParameters
36: {
37: Smoothing = 0.75f,
38: Correction = 0.1f,
39: Prediction = 0.0f,
40: JitterRadius = 0.05f,
41: MaxDeviationRadius = 0.08f
42: };
43:
44: _sensor = KinectSensor.KinectSensors[0];
45: _sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
46: _sensor.DepthStream.Enable(DepthImageFormat.Resolution320x240Fps30);
47: _sensor.SkeletonStream.Enable(parameters);
48: _sensor.Start();
49: colorViewer.Kinect = _sensor;
50: skeletonViewer.Kinect = _sensor;
51: _sensor.SkeletonFrameReady += SensorSkeletonFrameReady;
52: }
53:
54: private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
55: {
56: Skeleton[] skeletons = null;
57: using (var frame = e.OpenSkeletonFrame())
58: {
59: if (frame != null)
60: {
61: skeletons = new Skeleton[frame.SkeletonArrayLength];
62: frame.CopySkeletonDataTo(skeletons);
63: }
64: }
65:
66: if (skeletons == null) return;
67:
68: foreach (var kinectRocketGestures in (
69: from skeleton in skeletons
70: where skeleton.TrackingState == SkeletonTrackingState.Tracked
71: let headJoint = skeleton.Joints[JointType.Head]
72: where headJoint.TrackingState != JointTrackingState.NotTracked
73: select skeleton).Select(skeleton => new KinectRocketGestures(skeleton, _rocket)))
74: {
75: var gesture = kinectRocketGestures.ValidateGestures();
76: textBlockInformation.Text = gesture;
77: }
78: }
79: }
80: }
It is important to note that this window has almost nothing interesting logic only starts the sensors of the Kinect and the Lance missiles and then subscribe to the skeleton update notifications.
In this notification (line 54), it validates that the tracking of the skeleton is correct and then we use a class KinectRocketGestures that is what makes a little magic between Kinect and the Lance missiles.
This class code is as follows
1: using Microsoft.Kinect;
2:
3: namespace ElBruno.Rocket.Ui
4: {
5: class KinectRocketGestures
6: {
7: private readonly Skeleton _skeleton;
8: private readonly Rocket _rocket;
9:
10: public KinectRocketGestures(Skeleton skeleton, Rocket rocket)
11: {
12: _skeleton = skeleton;
13: _rocket = rocket;
14: }
15:
16: public string ValidateGestures()
17: {
18: var gesture = @"Not defined";
19: // STOP
20: // Right hand and Left hand hanging at the side
21: if (_skeleton.Joints[JointType.HandRight].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y &&
22: _skeleton.Joints[JointType.HandLeft].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y)
23: {
24: _rocket.StopAll();
25: _rocket.StopFiring();
26: _rocket.StopMovements();
27: gesture = @"STOP";
28: return gesture;
29: }
30:
31: // FIRE
32: if (_skeleton.Joints[JointType.HandLeft].Position.Y > _skeleton.Joints[JointType.Head].Position.Y)
33: {
34: gesture = @"FIRE";
35: _rocket.FireOnce();
36: }
37:
38: // MOVE RIGHT OR LEFT
39: // Right hand in front of right shoulder
40: // Right hand below shoulder height but above hip height
41: if (
42: (_skeleton.Joints[JointType.HandRight].Position.Z < _skeleton.Joints[JointType.ElbowRight].Position.Z &&
43: _skeleton.Joints[JointType.HandLeft].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y)
44: &&
45: (_skeleton.Joints[JointType.HandRight].Position.Y < _skeleton.Joints[JointType.Head].Position.Y &&
46: _skeleton.Joints[JointType.HandRight].Position.Y > _skeleton.Joints[JointType.HipCenter].Position.Y)
47: )
48: {
49: // Right hand right of right shoulder
50: if (_skeleton.Joints[JointType.HandRight].Position.X > _skeleton.Joints[JointType.ShoulderRight].Position.X)
51: {
52: gesture = @"MOVE RIGHT";
53: _rocket.MoveRight();
54: }
55: // Right hand left of left Shoulder
56: if (_skeleton.Joints[JointType.HandRight].Position.X < _skeleton.Joints[JointType.ShoulderLeft].Position.X)
57: {
58: gesture = @"MOVE LEFT";
59: _rocket.MoveLeft();
60: }
61: }
62:
63: // MOVE UP OR DOWN
64: // Right hand in front of body with Left hand hanging at the side
65: // Right hand between shoulders
66: if (
67: (_skeleton.Joints[JointType.HandRight].Position.Z < _skeleton.Joints[JointType.ShoulderCenter].Position.Z &&
68: _skeleton.Joints[JointType.HandLeft].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y)
69: &&
70: (_skeleton.Joints[JointType.HandRight].Position.X < _skeleton.Joints[JointType.ShoulderRight].Position.X &&
71: _skeleton.Joints[JointType.HandRight].Position.X > _skeleton.Joints[JointType.ShoulderLeft].Position.X)
72: )
73: {
74: // Right hand above the shoulders
75: if (_skeleton.Joints[JointType.HandRight].Position.Y > _skeleton.Joints[JointType.ShoulderCenter].Position.Y)
76: {
77: gesture = @"MOVE UP";
78: _rocket.MoveUp();
79: }
80: // Right hand below the chest/gut
81: if (_skeleton.Joints[JointType.HandRight].Position.Y < _skeleton.Joints[JointType.Spine].Position.Y)
82: {
83: gesture = @"MOVE DOWN";
84: _rocket.MoveDown();
85: }
86: return gesture;
87: }
88: }
89: }
90: }
And that’s it! A bit of validation of the right hand and left hand positions and have control of the Lance missiles using Kinect.
Now I’m going fast to the MadridDotNet event and in the next post I put a video and the example of the application code.
Saludos @ La Finca
El Bruno
[#KINECTSDK] Kinect Missile Launcher (IV): Controlando el lanza misiles con Kinect
Publicado por elbruno en Code Sample, KinectSdk, Visual Studio 11 el 26 abril, 2012
Buenas,
hoy ya vamos a crear una aplicación que nos permita controlar el lanza misiles utilizando gestos de Kinect. Para esto he pensado en los siguientes controles
- La mano derecha controla la dirección del lanza misiles. Puede ir a la derecha, a la izquierda, arriba o abajo.
- La mano izquierda controla el disparo del misil, la forma de disparar es levantar la mano encima de la cabeza.
- Si ambos manos están por debajo de la cintura se detienen los movimientos del lanza misiles
Con esta base, y aprovechando los controles visuales de “Microsoft.Samples.Kinect.WpfViewers” he creado una aplicación WPF con el siguiente código en la ventana principal
1: using System.Linq;
2: using System.Windows;
3: using Microsoft.Kinect;
4:
5: namespace ElBruno.Rocket.Ui
6: {
7: public partial class MainWindow
8: {
9: private KinectSensor _sensor;
10: private Rocket _rocket;
11: public MainWindow()
12: {
13: InitializeComponent();
14: Loaded += MainWindowLoaded;
15: }
16:
17: private void MainWindowLoaded(object sender, RoutedEventArgs e)
18: {
19: InitRocket();
20: InitKinectSensor();
21: }
22:
23: private void InitRocket()
24: {
25: _rocket = new Rocket(@"vid_0a81", @"pid_ff01");
26: _rocket.Connect();
27: }
28:
29: private void InitKinectSensor()
30: {
31: // validate
32: if (KinectSensor.KinectSensors.Count == 0) return;
33:
34: // init Kinect
35: var parameters = new TransformSmoothParameters
36: {
37: Smoothing = 0.75f,
38: Correction = 0.1f,
39: Prediction = 0.0f,
40: JitterRadius = 0.05f,
41: MaxDeviationRadius = 0.08f
42: };
43:
44: _sensor = KinectSensor.KinectSensors[0];
45: _sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
46: _sensor.DepthStream.Enable(DepthImageFormat.Resolution320x240Fps30);
47: _sensor.SkeletonStream.Enable(parameters);
48: _sensor.Start();
49: colorViewer.Kinect = _sensor;
50: skeletonViewer.Kinect = _sensor;
51: _sensor.SkeletonFrameReady += SensorSkeletonFrameReady;
52: }
53:
54: private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
55: {
56: Skeleton[] skeletons = null;
57: using (var frame = e.OpenSkeletonFrame())
58: {
59: if (frame != null)
60: {
61: skeletons = new Skeleton[frame.SkeletonArrayLength];
62: frame.CopySkeletonDataTo(skeletons);
63: }
64: }
65:
66: if (skeletons == null) return;
67:
68: foreach (var kinectRocketGestures in (
69: from skeleton in skeletons
70: where skeleton.TrackingState == SkeletonTrackingState.Tracked
71: let headJoint = skeleton.Joints[JointType.Head]
72: where headJoint.TrackingState != JointTrackingState.NotTracked
73: select skeleton).Select(skeleton => new KinectRocketGestures(skeleton, _rocket)))
74: {
75: var gesture = kinectRocketGestures.ValidateGestures();
76: textBlockInformation.Text = gesture;
77: }
78: }
79: }
80: }
1: using Microsoft.Kinect;
2:
3: namespace ElBruno.Rocket.Ui
4: {
5: class KinectRocketGestures
6: {
7: private readonly Skeleton _skeleton;
8: private readonly Rocket _rocket;
9:
10: public KinectRocketGestures(Skeleton skeleton, Rocket rocket)
11: {
12: _skeleton = skeleton;
13: _rocket = rocket;
14: }
15:
16: public string ValidateGestures()
17: {
18: var gesture = @"Not defined";
19: // STOP
20: // Right hand and Left hand hanging at the side
21: if (_skeleton.Joints[JointType.HandRight].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y &&
22: _skeleton.Joints[JointType.HandLeft].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y)
23: {
24: _rocket.StopAll();
25: _rocket.StopFiring();
26: _rocket.StopMovements();
27: gesture = @"STOP";
28: return gesture;
29: }
30:
31: // FIRE
32: if (_skeleton.Joints[JointType.HandLeft].Position.Y > _skeleton.Joints[JointType.Head].Position.Y)
33: {
34: gesture = @"FIRE";
35: _rocket.FireOnce();
36: }
37:
38: // MOVE RIGHT OR LEFT
39: // Right hand in front of right shoulder
40: // Right hand below shoulder height but above hip height
41: if (
42: (_skeleton.Joints[JointType.HandRight].Position.Z < _skeleton.Joints[JointType.ElbowRight].Position.Z &&
43: _skeleton.Joints[JointType.HandLeft].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y)
44: &&
45: (_skeleton.Joints[JointType.HandRight].Position.Y < _skeleton.Joints[JointType.Head].Position.Y &&
46: _skeleton.Joints[JointType.HandRight].Position.Y > _skeleton.Joints[JointType.HipCenter].Position.Y)
47: )
48: {
49: // Right hand right of right shoulder
50: if (_skeleton.Joints[JointType.HandRight].Position.X > _skeleton.Joints[JointType.ShoulderRight].Position.X)
51: {
52: gesture = @"MOVE RIGHT";
53: _rocket.MoveRight();
54: }
55: // Right hand left of left Shoulder
56: if (_skeleton.Joints[JointType.HandRight].Position.X < _skeleton.Joints[JointType.ShoulderLeft].Position.X)
57: {
58: gesture = @"MOVE LEFT";
59: _rocket.MoveLeft();
60: }
61: }
62:
63: // MOVE UP OR DOWN
64: // Right hand in front of body with Left hand hanging at the side
65: // Right hand between shoulders
66: if (
67: (_skeleton.Joints[JointType.HandRight].Position.Z < _skeleton.Joints[JointType.ShoulderCenter].Position.Z &&
68: _skeleton.Joints[JointType.HandLeft].Position.Y < _skeleton.Joints[JointType.HipCenter].Position.Y)
69: &&
70: (_skeleton.Joints[JointType.HandRight].Position.X < _skeleton.Joints[JointType.ShoulderRight].Position.X &&
71: _skeleton.Joints[JointType.HandRight].Position.X > _skeleton.Joints[JointType.ShoulderLeft].Position.X)
72: )
73: {
74: // Right hand above the shoulders
75: if (_skeleton.Joints[JointType.HandRight].Position.Y > _skeleton.Joints[JointType.ShoulderCenter].Position.Y)
76: {
77: gesture = @"MOVE UP";
78: _rocket.MoveUp();
79: }
80: // Right hand below the chest/gut
81: if (_skeleton.Joints[JointType.HandRight].Position.Y < _skeleton.Joints[JointType.Spine].Position.Y)
82: {
83: gesture = @"MOVE DOWN";
84: _rocket.MoveDown();
85: }
86: return gesture;
87: }
88: }
89: }
90: }
Y listo! Un poco de validación de posiciones de la mano derecha y la mano izquierda y ya tenemos el control del lanza misiles utilizando Kinect.
Ahora me voy rápido al evento de MadridDotNet y en el próximo post pongo un video y el código de ejemplo de la aplicación.
Saludos @ La Finca
El Bruno
[# KINECTSDK] HowTo: Paint a skeleton
Publicado por elbruno en Code Sample, EnglishPost, HowTo, Kinect, KinectSdk, Visual Studio 11 el 20 marzo, 2012
Buenas,
a couple of days ago I asked how to paint a skeleton with the new KinectSDK in this post. Today’s post explains the basics in a few steps to paint the skeleton.
For this example we will use a form of WPF, which add a Canvas brush where the skeleton.
1: <Window x:Class="KinectSkeleton01.MainWindow"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="MainWindow" Height="480" Width="640">
5: <Grid>
6: <Canvas Name="skeletonCanvas"
7: Height="480" Width="640"
8: HorizontalAlignment="Center"/>
9: </Grid>
10: </Window>
The following to keep in mind is to work with the sensor Kinect as a local variable of the form. In this post (link) talk a little in this regard.
Once controlled the State of the Kinect, the following is initialize the capture of skeleton (line 6 and 7) and subscribe to the event of change of frame for the skeleton (line 8).
In the implementation of this event, firstly we clean the canvas (line 14) and once validated the received frame (line 19) copy the array of skeletons to a local variable (line 21 and 22).
The concluding lines verify the State of the Joint of the head to see if tracking is correct and then use a helper of ElBruno.Kinect to paint the skeleton.
1: void MainWindowLoaded(object sender, RoutedEventArgs e)
2: {
3: if(KinectSensor.KinectSensors.Count == 0)
4: return;
5: _kinect = KinectSensor.KinectSensors[0];
6: _kinect.SkeletonStream.Enable();
7: _kinect.Start();
8: _kinect.SkeletonFrameReady += KinectSkeletonFrameReady;
9: }
10:
11: void KinectSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
12: {
13: // Remove the old skeleton
14: skeletonCanvas.Children.Clear();
15: Skeleton[] skeletons = null;
16:
17: using (var frame = e.OpenSkeletonFrame())
18: {
19: if (frame != null)
20: {
21: skeletons = new Skeleton[frame.SkeletonArrayLength];
22: frame.CopySkeletonDataTo(skeletons);
23: }
24: }
25:
26: if (skeletons == null) return;
27:
28: foreach (var skeleton in skeletons)
29: {
30: if (skeleton.TrackingState != SkeletonTrackingState.Tracked) continue;
31: var headJoint = skeleton.Joints[JointType.Head];
32: if (headJoint.TrackingState != JointTrackingState.NotTracked)
33: {
34: var skeletonDraw = new SkeletonDraw();
35: skeletonDraw.DrawSkeleton(_kinect, skeletonCanvas, skeleton);
36: }
37: }
38: }
The class responsible for painting the skeleton basically paints lines between each of the joints of the same. As we can see in the following code lines are painted between 2 points with the canvas and the sensor as benchmarks.
1: void AddLine(KinectSensor kinectSensor, Canvas drawCanvas, Joint j1, Joint j2)
2:
3: var boneLine = new Line {Stroke = SkeletonBrush, StrokeThickness = 5};
4:
5: var j1P = kinectSensor.MapSkeletonPointToDepth(j1.Position, DepthImageFormat.Resolution640x480Fps30);
6: boneLine.X1 = j1P.X;
7: boneLine.Y1 = j1P.Y;
8:
9: DepthImagePoint j2P = kinectSensor.MapSkeletonPointToDepth(j2.Position, DepthImageFormat.Resolution640x480Fps30);
10: boneLine.X2 = j2P.X;
11: boneLine.Y2 = j2P.Y;
12:
13: drawCanvas.Children.Add(boneLine);
14:
15:
16: ublic float JointDistance(Joint first, Joint second)
17:
18: float dx = first.Position.X - second.Position.X;
19: float dy = first.Position.Y - second.Position.Y;
20: float dz = first.Position.Z - second.Position.Z;
21:
22: return (float)Math.Sqrt((dx * dx) + (dy * dy) + (dz * dz));
The sample code can be downloaded from
Saludos @ Home
El Bruno
Resources
http://elbruno.com/2012/03/06/kinectsdk-HOWTO-detectar-El-Cambio-de-Estado-o-desconexion-del-sensor/
[#KINECTSDK] HowTo: Pintar un skeleton
Publicado por elbruno en Code Sample, HowTo, Kinect, KinectSdk, Visual Studio 11 el 20 marzo, 2012
Buenas,
hace un par de días me preguntaban como hacer para pintar un skeleton con el nuevo KinectSDK, en este post. El post de hoy explica en pocos pasos los conceptos básicos para pintar el skeleton.
Para este ejemplo utilizaremos un formulario WPF, en el que agregaremos un Canvas donde pintaremos el skeleton.
1: <Window x:Class="KinectSkeleton01.MainWindow"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="MainWindow" Height="480" Width="640">
5: <Grid>
6: <Canvas Name="skeletonCanvas"
7: Height="480" Width="640"
8: HorizontalAlignment="Center"/>
9: </Grid>
10: </Window>
Lo siguiente a tener en cuenta es trabajar con el sensor Kinect como una variable local del form. En este post (link) hable un poco al respecto.
Una vez controlado el estado del Kinect, lo siguiente es inicializar la captura de skeleton (línea 6 y 7) y suscribirse al evento de cambio de frame para el skeleton (línea 8).
En la implementación de este evento, en primer lugar limpiaremos el canvas (línea 14) y una vez validado el frame recibido (línea 19) copiaremos el array de skeletons a una variable local (línea 21 y 22).
Las líneas finales verifican el estado del Joint de la cabeza para ver si el seguimiento es correcto y luego utilizan un helper de ElBruno.Kinect para pintar el skeleton.
1: void MainWindowLoaded(object sender, RoutedEventArgs e)
2: {
3: if(KinectSensor.KinectSensors.Count == 0)
4: return;
5: _kinect = KinectSensor.KinectSensors[0];
6: _kinect.SkeletonStream.Enable();
7: _kinect.Start();
8: _kinect.SkeletonFrameReady += KinectSkeletonFrameReady;
9: }
10:
11: void KinectSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
12: {
13: // Remove the old skeleton
14: skeletonCanvas.Children.Clear();
15: Skeleton[] skeletons = null;
16:
17: using (var frame = e.OpenSkeletonFrame())
18: {
19: if (frame != null)
20: {
21: skeletons = new Skeleton[frame.SkeletonArrayLength];
22: frame.CopySkeletonDataTo(skeletons);
23: }
24: }
25:
26: if (skeletons == null) return;
27:
28: foreach (var skeleton in skeletons)
29: {
30: if (skeleton.TrackingState != SkeletonTrackingState.Tracked) continue;
31: var headJoint = skeleton.Joints[JointType.Head];
32: if (headJoint.TrackingState != JointTrackingState.NotTracked)
33: {
34: var skeletonDraw = new SkeletonDraw();
35: skeletonDraw.DrawSkeleton(_kinect, skeletonCanvas, skeleton);
36: }
37: }
38: }
La clase encargada de pintar el skeleton básicamente pinta líneas entre cada uno de los joints del mismo. Como podemos ver en el siguiente código las líneas se pintan entre 2 puntos con el canvas y el sensor como elementos de referencia.
1: void AddLine(KinectSensor kinectSensor, Canvas drawCanvas, Joint j1, Joint j2)
2:
3: var boneLine = new Line {Stroke = SkeletonBrush, StrokeThickness = 5};
4:
5: var j1P = kinectSensor.MapSkeletonPointToDepth(j1.Position, DepthImageFormat.Resolution640x480Fps30);
6: boneLine.X1 = j1P.X;
7: boneLine.Y1 = j1P.Y;
8:
9: DepthImagePoint j2P = kinectSensor.MapSkeletonPointToDepth(j2.Position, DepthImageFormat.Resolution640x480Fps30);
10: boneLine.X2 = j2P.X;
11: boneLine.Y2 = j2P.Y;
12:
13: drawCanvas.Children.Add(boneLine);
14:
15:
16: ublic float JointDistance(Joint first, Joint second)
17:
18: float dx = first.Position.X - second.Position.X;
19: float dy = first.Position.Y - second.Position.Y;
20: float dz = first.Position.Z - second.Position.Z;
21:
22: return (float)Math.Sqrt((dx * dx) + (dy * dy) + (dz * dz));
El código de ejemplo se puede descargar desde
Saludos @ Home
El Bruno
Recursos
http://elbruno.com/2012/03/06/kinectsdk-howto-detectar-el-cambio-de-estado-o-desconexion-del-sensor/
[# RESHARPER] HowTo: Convert string + string in string.format()
Publicado por elbruno en Code Sample, EnglishPost, HowTo, ReSharper, Visual Studio 2010 el 3 febrero, 2012
Hi,
After 12 hours of Visual Studio from last Tuesday, I grabbed me a virus that almost killed me. But little by little I will remove the earrings, we start by some emails.
Good, I was the other day watching with my coworkers 12 hours of Visual Studio, and part of seem very interesting items that you enseñasteis, we are left with the question of how to make a “trick” that we found to be quite useful in day to day… how to convert a string of the type “Hello” + < variable > + “que tal” in the string.Format(“hola_{0}_que_tal”,<variable>) automatically. We see you do it in the talk, but we do not know how, hehe.
Therefore, that becomes so well live and also much better in the code is thanks to ReSharper. To show an example, I have a console application with the following code:
1: using System;
2: namespace ConsoleApplication2
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: const string Name = @"Valentino";
9: var msg = "Hola mi nombre es " + Name;
10: Console.WriteLine(msg);
11: }
12: }
13: }
If we are positioned on line 9, we see that ReSharper offers us the possibility of using format string for concatenation of strings.
After selecting this option, we have no more a sum of strings
But this is not all, the second option offered to us by ReSharper is also interesting, “Compute constant value”. In the same R # identifies that we are working with a constant and offers us the possibility of using the same value instead of working with a chain. The end result would be as follows:
1: using System;
2: namespace ConsoleApplication2
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: const string Name = @"Valentino";
9: var msg = string.Format("Hola mi nombre es {0}", Name);
10: Console.WriteLine(msg);
11: }
12: }
13: }
1: using System;
2: namespace ConsoleApplication2
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: const string Name = @"Valentino";
9: var msg = "Hola mi nombre es Valentino";
10: Console.WriteLine(msg);
11: }
12: }
13: }
Obviously, if we change the value of the constant we are more fried than the Chicago Bulls without Derrick Rose, but that topic for another post.
Greetings @ Home
El Bruno
[#RESHARPER] HowTo: Convertir string + string en string.format()
Publicado por elbruno en Code Sample, HowTo, ReSharper, Visual Studio 2010 el 3 febrero, 2012
Buenas,
después de las 12 horas de Visual Studio del pasado martes, me agarro un virus que casi me mata. Pero de a poco voy a sacar los pendientes, empezamos por algunos correos.
Buenas, estuve el otro día viendo con mis compañeros de trabajo las 12 horas de Visual Studio, y a parte de parecernos muy interesantes los temas que enseñasteis, nos quedamos con la duda de como hacer un "truco" que nos pareció bastante útil en el día a día… como convertir un string del tipo "hola " + <variable> + " que tal" en string.Format("hola {0} que tal",<variable>) automáticamente. Te vimos hacerlo en la charla, pero no sabemos como, jeje.
Pues bien, eso que queda tan bien en vivo y además mucho mejor en el código se debemos agradecer a ReSharper. Para muestra un ejemplo, tengo una aplicación de Consola con el siguiente código:
1: using System;
2: namespace ConsoleApplication2
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: const string Name = @"Valentino";
9: var msg = "Hola mi nombre es " + Name;
10: Console.WriteLine(msg);
11: }
12: }
13: }
Si nos posicionamos sobre la línea 9, veremos que ReSharper nos ofrece la posibilidad de utilizar format string para la concatenación de cadenas.
Una vez seleccionada esta opción, ya no tenemos más una suma de strings
1: using System;
2: namespace ConsoleApplication2
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: const string Name = @"Valentino";
9: var msg = string.Format("Hola mi nombre es {0}", Name);
10: Console.WriteLine(msg);
11: }
12: }
13: }
Pero esto no es todo, la segunda opción que nos ofrece ReSharper también es interesante, “Compute constant value”. En la misma R# identifica que estamos trabajando con una constante y nos ofrece la posibilidad de utilizar el valor de la misma en lugar de trabajar con una cadena. El resultado final sería el siguiente:
1: using System;
2: namespace ConsoleApplication2
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: const string Name = @"Valentino";
9: var msg = "Hola mi nombre es Valentino";
10: Console.WriteLine(msg);
11: }
12: }
13: }
Obviamente, si cambiamos el valor de la constante estamos más frito que los Chicago Bulls sin Derrick Rose, pero ese tema para otro post.
Saludos @ Home
El Bruno
[# KINECT] HowTo: Soften the detection of movements in the skeleton
Publicado por elbruno en Code Sample, EnglishPost, Kinect, Visual Studio 2010 el 24 enero, 2012
Hi,
While we await the final SDK for developers with Kinectleave in a few days, we still have to adjust quite a bit to make the SDK will allow us to make robust applications. One of these “debts” Kinect has with us is the ability to remove the “tembleque / tremor” have at each point of the skeleton when working with the same point to point or Joint to Joint. If you run the application that shows both skeletons in a Canvas of WPF, you’ll see that it works pretty well.
Now, if we modify it with a bit of the code base of this post, to add 2 worlds in each hand (I have ‘ s got the whole world in his hands!) in will see something similar to the following image. While I have not well adjusted the size of the form so that the worlds coincide 100% with each hand, when you run the application you can see that it is a flickering or tembleque a little weird when examines the detail of the skeleton.
As well to solve this problem to our hands comes a fabulous property of the SDK called TransformSmooth. While there is lots of documentation in this respect, using this property we can define a series of buffers for deviations that will be processed during the analysis of the skeleton. Thus if we add the following lines before subscribe to the event of detection of skeletons, we can work in a smooth way.
1: Kinect.SkeletonEngine.TransformSmooth = true;
2: var parameters = new TransformSmoothParameters
3: {
4: Smoothing = 0.75f,
5: Correction = 0.1f,
6: Prediction = 0.0f,
7: JitterRadius = 0.05f,
8: MaxDeviationRadius = 0.08f
9: };
10: Kinect.SkeletonEngine.SmoothParameters = parameters;
11: Kinect.SkeletonFrameReady += KinectSkeletonFrameReady;
Now, to see that values have to apply to each property, it is best to go testing them to see that format is better suited to our application. In this post, is described a bit to represent each property and values by default of the same.
| Parameter | Description | Default Value | Comments |
| Smoothing | Specifies the amount of smoothing. | 0.5 | Higher values correspond to more smoothing and a value of 0 causes the raw data to be returned. Increasing smoothing tends to increase latency. Values must be in the range [0, 1.0]. |
| Correction | Specifies the amount of correction. | 0.5 | Lower values are slower to correct towards the raw data and appear smoother, while higher values correct toward the raw data more quickly. Values must be in the range [0, 1.0]. |
| Prediction | Specifies the number of predicted frames. | 0.5 | |
| Jitter Radius | Specifies the jitter-reduction radius, in meters. | 0.05 | The default value of 0.05 represents 5cm. Any jitter beyond the radius is clamped to the radius. |
| Maximum Deviation Radius | Specifies the maximum radius that filter positions can deviate from raw data, in meters. | 0.04 | Filtered values that would exceed the radius from the raw data are clamped at this distance, in the direction of the filtered value. |
And as always if you want to download the ´código of this post you can do from here
Greetings @ Home
El Bruno
Sources:
http://Channel9.msdn.com/series/KinectSDKQuickstarts/skeletal-tracking-fundamentals
http://cm-bloggers.blogspot.com/2011/07/kinect-SDK-smoothing-skeleton-data.html
[#KINECT] HowTo: Suavizar la detección de movimientos en el skeleton
Publicado por elbruno en Code Sample, Kinect, Visual Studio 2010 el 24 enero, 2012
Buenas,
mientras esperamos que en pocos días salga el SDK final para los desarrollos con Kinect, todavía tenemos que ajustar bastantes cosas para que el SDK nos permita hacer aplicaciones robustas. Una de estas “deudas” que Kinect posee con nosotros es la capacidad de quitar el “tembleque/temblor” que tenemos en cada punto del skeleton cuando trabajamos con el mismo punto a punto o Joint a Joint. Si ejecutas la aplicación que muestra ambos skeletons en un Canvas de WPF, verás que la misma funciona bastante bien.
Ahora bien, si modificamos la misma con un poco del código base de este post, para agregar 2 mundos en cada mano (he’s got the whole world in his hands!!!) in veremos algo similar a la siguiente imagen. Si bien no he ajustado bien el tamaño del form para que los mundos coincidan 100% con cada mano, cuando ejecutas la aplicación puedes ver que la misma tiene un flickering o tembleque un poco raro cuando analiza el detalle del skeleton.
Pues bien para solucionar este problema llega a nuestras manos una fabulosa propiedad del SDK llamada TransformSmooth. Si bien no hay mucha documentación al respecto, utilizando esta propiedad podemos definir una serie de buffers de desviaciones que se procesarán durante el análisis del skeleton. De esta forma si agregamos las siguientes líneas antes de suscribirnos al evento de detección de skeletons, podremos trabajar de una forma más suave.
1: _kinect.SkeletonEngine.TransformSmooth = true;
2: var parameters = new TransformSmoothParameters
3: {
4: Smoothing = 0.75f,
5: Correction = 0.1f,
6: Prediction = 0.0f,
7: JitterRadius = 0.05f,
8: MaxDeviationRadius = 0.08f
9: };
10: _kinect.SkeletonEngine.SmoothParameters = parameters;
11: _kinect.SkeletonFrameReady += KinectSkeletonFrameReady;
Ahora bien, para ver que valores tenemos que aplicar en cada propiedad, lo mejor es ir probando las mismas para ver que formato se adapta mejor a nuestra aplicación. En este post, se describe un poco que representa cada propiedad y los valores por defecto de las mismas.
| Parameter | Description | Default Value | Comments |
| Smoothing | Specifies the amount of smoothing. | 0.5 | Higher values correspond to more smoothing and a value of 0 causes the raw data to be returned. Increasing smoothing tends to increase latency. Values must be in the range [0, 1.0]. |
| Correction | Specifies the amount of correction. | 0.5 | Lower values are slower to correct towards the raw data and appear smoother, while higher values correct toward the raw data more quickly. Values must be in the range [0, 1.0]. |
| Prediction | Specifies the number of predicted frames. | 0.5 | |
| Jitter Radius | Specifies the jitter-reduction radius, in meters. | 0.05 | The default value of 0.05 represents 5cm. Any jitter beyond the radius is clamped to the radius. |
| Maximum Deviation Radius | Specifies the maximum radius that filter positions can deviate from raw data, in meters. | 0.04 | Filtered values that would exceed the radius from the raw data are clamped at this distance, in the direction of the filtered value. |
Y como siempre si quieres descargar el ´código de este post lo puedes hacer desde aqui
Saludos @ Home
El Bruno
Fuentes:
http://channel9.msdn.com/Series/KinectSDKQuickstarts/Skeletal-Tracking-Fundamentals
http://cm-bloggers.blogspot.com/2011/07/kinect-sdk-smoothing-skeleton-data.html
[# VISUALSTUDIO2010] HowTo: Formatting XAMLs with an attribute per line
Publicado por elbruno en Code Sample, HowTo, Visual Studio 2010 el 30 diciembre, 2011
Hi,
I’m going to point out now that have shown me it 10 times, because if not I dizziness. The issue is the next, when you fight with WPF, Silverlight, or any other technology to make excessive use of formats with tags, because the theme of the Edition text can be quite complicated. A great “visual” solution for these cases is to take advantage of the formatting that it offers Visual Studio, where an attribute is separated by line. This option is activated from the menu [Tools / / Options], in the section [Text Editor / / XAML / / Formatting / / Spacing] the option selected [Position each attribute on separate line ]]
For example, returning to the example I posted 2 days ago we can see part of the XAML in this format
1: <TextBlock Text="Merry Christmas" Grid.Row="0" Grid.Column="1" FontSize="24" Foreground="White"
2: FontFamily="Segoe UI Semilight" FontWeight="Bold" Margin="0" HorizontalAlignment="Center" />
3: <Canvas x:Name="canvasContent" Margin="10,10,0,0" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2">
4: <Grid Grid.Column="1" Grid.Row="1"><Border BorderThickness="3" BorderBrush="White" CornerRadius="10"
5: Padding="2" HorizontalAlignment="Center" VerticalAlignment="Center"> <Grid>
6: <Border x:Name="mask" Background="White" CornerRadius="7" /> <StackPanel><StackPanel.OpacityMask>
7: <VisualBrush Visual="{Binding ElementName=mask}" /></StackPanel.OpacityMask><Image x:Name="CameraViewer"
8: Stretch="UniformToFill" MaxWidth="640" MaxHeight="480" /></StackPanel></Grid></Border></Grid>
Or after a Ctrl+k, CTRL + d, we see it in a more “natural” way
1: <TextBlock Text="Merry Christmas"
2: Grid.Row="0"
3: Grid.Column="1"
4: FontSize="24"
5: Foreground="White"
6: FontFamily="Segoe UI Semilight"
7: FontWeight="Bold"
8: Margin="0"
9: HorizontalAlignment="Center" />
10: <Canvas x:Name="canvasContent"
11: Margin="10,10,0,0"
12: Grid.Row="0"
13: Grid.Column="0"
14: Grid.RowSpan="2">
15: <Grid Grid.Column="1"
16: Grid.Row="1">
17: <Border BorderThickness="3"
18: BorderBrush="White"
19: CornerRadius="10"
20: Padding="2"
21: HorizontalAlignment="Center"
22: VerticalAlignment="Center">
23: <Grid>
24: <Border x:Name="mask"
25: Background="White"
26: CornerRadius="7" />
27: <StackPanel>
28: <StackPanel.OpacityMask>
29: <VisualBrush Visual="{Binding ElementName=mask}" />
30: </StackPanel.OpacityMask>
31: <Image x:Name="CameraViewer"
32: Stretch="UniformToFill"
33: MaxWidth="640"
34: MaxHeight="480" />
35: </StackPanel>
36: </Grid>
37: </Border>
38: </Grid>
39: <ContentControl x:Name="contentControlHat1">
40: <Image x:Name="imageHat1"
41: Width="64"
42: Height="64"
43: Source="/ElBruno.KinectViewer;component/Images/santa-hat.png"
44: Visibility="Hidden" />
45: </ContentControl>
Anyways, that tastes there is nothing written and perhaps this option more than one does not like, because well… here there is an option to test and choose.
Greetings @ Home
The Bruno






SocialVibe