-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataRecognizer.py
More file actions
214 lines (167 loc) · 9.17 KB
/
DataRecognizer.py
File metadata and controls
214 lines (167 loc) · 9.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#Biblioteca para Interfaz grafica
import Tkinter as tk
from Tkinter import *
#Biblioteca para utilizar los comandos del Leap
import Leap
#Biblioteca para enviar datos en formato JSON
import json
#Bilbioteca para comunicacion por red
import paho.mqtt.client as mqtt
import os
def cargarImagen(nombre):
ruta = os.path.join('Imagen',nombre)
imagen = PhotoImage(file=ruta)
return imagen
#Clase del Leap Motion que incluye todos sus metodos
class Listener(Leap.Listener):
#Metodo de inicializacion
def __init__(self):
Leap.Listener.__init__(self)
self.listenerEnabled = False
self.lastFrame = Leap.Frame
self.lastFrames = [Leap.Frame, Leap.Frame, Leap.Frame, Leap.Frame, Leap.Frame]
self.numberOfFramesAnalyzed = 0
self.listOfEightyFrames=[]
self.getFrames = False #Variable de control para obtener datos del Leap
print(str(self.listenerEnabled))
def on_init(self, controller):
print "Initialized"
#Metodo que identifica cuando el Leap Motion es conectado
def on_connect(self, controller):
print "Connected"
#Metodo que identifica cuando el Leap Motion es desconectado
def on_disconnect(self, controller):
print("Disconnected")
#Metodo principal encargado de obtener frames con los datos del Leap
def on_frame(self, controller):
#if self.listenerEnabled == True:
self.lastFrame = controller.frame()
for n in range(79): #Ciclo encargado de ir actualizando los ultimos 80 cuadros que lee el Leap
if(len(self.lastFrames) == 80):
self.lastFrames.pop(0)
self.lastFrames.append(controller.frame(n))
else:
self.lastFrames.append(controller.frame(n))
if (self.getFrames == True and len(self.listOfEightyFrames) != 80):
self.listOfEightyFrames.append(controller.frame())
else:
self.getFrames = False
class Reader(Tk):
def __init__(self):
Tk.__init__(self)
#Inicializacion de controlador para utilizar el Leap
self.leap = Leap.Controller()
#Metodos de interfaz de Tkinter
self.title("Interfaz de entrenamiento")
self.geometry("800x600")
self.mainFrame = Frame(self, width=800, height=600, bg="#0b486b")
self.mainFrame.place(x=0,y=0)
self.logo = cargarImagen('Lescompi.gif')
self.logoLabel = Label(self, image=self.logo)
self.logoLabel.place(x=200, y=400)
self.listener = Listener()
self.leap.add_listener(self.listener)
self.labelSignToRead = Label(self, bg="#0b486b", fg="#a8dba8", text="Por favor presione\n el boton para\n realizar sus gestos", font=("Consolas", 50))
self.labelSignToRead.place(x=20, y=0)
self.lastFrameProcessed = Leap.Frame
self.frameToCompare = Leap.Frame
self.gestureToReadCode = 0
self.finger_names = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']
self.client = mqtt.Client("leapLesco")
self.client.connect("iot.eclipse.org", 1883, 60)
self.client.on_connect = self.on_connect_mqtt
self.client.on_message = self.on_message_mqtt
self.client.loop_start()
def on_connect_mqtt(self, client, userdata, flags, rc):
client.subscribe("LeapBoton")
def on_message_mqtt(self,client, userdata, msg):
print(msg.payload)
m_in=json.loads(msg.payload)
if(m_in['command']=='start reading'):
# self.gestureToReadCode = int(self.entrySign.get())
self.getLastFrame()
#Funcion que indica al Interprete que debe analizar los gestos enviados
def analyze(self):
msgJson = {'command': 'analyze'}
self.client.publish("leapLesco", json.dumps(msgJson))
print("analisis solicitado")
def deleteLastFrame(self):
msgJson = {'command': 'delete_last'}
self.client.publish("leapLescoTraining", json.dumps(msgJson))
print("ultimo borrado")
def setSignToRead(self, event):
try:
self.gestureToReadCode = int(self.entrySign.get())
self.getLastFrame()
except Exception as ValueError:
print(self.entrySign.get(), '\n', 'Error de Entrada')
#Funcion encargada de obtener el ultimo cuadro y el primero desde que se empezo a obtener datos
def getLastFrame(self):
self.lastFrameProcessed = self.listener.lastFrame
self.lastFiveFramesProcessed = self.listener.lastFrames
self.listener.getFrames = True
print("inicia muestra")
while(len(self.listener.listOfEightyFrames) != 80):
pass
print("finaliza muestra")
self.getFrameInfo(self.listener.listOfEightyFrames[-1], self.listener.listOfEightyFrames)
self.listener.listOfEightyFrames = []
self.listener.getFrames = False
#Funcion encargada de obtener los datos de las manos que se observan en el cuadro final e inicial para posteriormente
#enviar el JSON a la biblioteca Keras
def getFrameInfo(self, frame, lastEightyFrames):
self.handType = ""
self.frameToCompare = lastEightyFrames[0]
if(len(frame.hands) != 0):
for n in range(len(frame.hands)):
if frame.hands[n].is_right: self.handType = "Right"
else: self.handType = "Left"
print(str(self.handType))
print ("Hand Movement: \n" + " Position X LastFrame: "+ str(frame.hands[n].palm_position.x)+
" Position X FirstFrame: "+ str(self.frameToCompare.hands[n].palm_position.x)+ " \nDelta X: " +
str(frame.hands[n].palm_position.x - self.frameToCompare.hands[n].palm_position.x) +
" \nPosition Y LastFrame: " + str(frame.hands[n].palm_position.y) + " Position Y FirstFrame: "+ str(self.frameToCompare.hands[n].palm_position.y)+
" \nDelta Y: " + str(
frame.hands[n].palm_position.y - self.frameToCompare.hands[n].palm_position.y) +
" \nPosition Z LastFrame: " + str(frame.hands[n].palm_position.z) + " Position Z FirstFrame: "+ str(self.frameToCompare.hands[n].palm_position.z)+
" \nDelta Z: " + str(
frame.hands[n].palm_position.z - self.frameToCompare.hands[n].palm_position.z))
"""for m in range(len(frame.hands[n].fingers)):
print ("Finger Type: " + self.finger_names[frame.hands[n].fingers[m].type] + " Tip Direction X: " + str(
frame.hands[n].fingers[m].direction.x) + " Tip Direction Y: " + str(frame.hands[n].fingers[m].direction.y) + " Tip Direction Z: " + str(
frame.hands[n].fingers[m].direction.z))"""
self.createJSON(frame, self.frameToCompare)
else:#En caso de que no haya manos, se indica un espacio al interprete
msgJson = {'command': 'space'}
self.client.publish("leapLesco", json.dumps(msgJson))
print("ESPACIO")
#Last frame es el primero de los 80, first frame es el ultimo de los 80
#Funcion encargada de crear y enviar el JSON por mqtt, solo se envian datos de la mano derecha
def createJSON(self, firstFrame, lastFrame):
if(len(lastFrame.hands) >=1):
frameJson = {'valid': lastFrame.is_valid, 'frameId': lastFrame.id, 'hands': []}
for hand in lastFrame.hands:
handtype = 0 if hand.is_left else 1
if(handtype == 1):#Solo se envian datos de la mano derecha
handJson = {'valid': hand.is_valid, 'type': handtype, 'id': hand.id, 'fingers': [], 'gesture': self.gestureToReadCode}
handJson['direction'] = {'x': hand.direction.x, 'y': hand.direction.y, 'z': hand.direction.z}
handJson['deltas'] = {'x': firstFrame.hands[0].palm_position.x - hand.palm_position.x,'y': firstFrame.hands[0].palm_position.y -hand.palm_position.y,
'z': firstFrame.hands[0].palm_position.z - hand.palm_position.z}
for finger in hand.fingers:
fingerJson = {'valid': finger.is_valid, 'bones': [], 'type': finger.type, 'id': finger.id,
'direction': {'x': finger.direction.x, 'y': finger.direction.y, 'z': finger.direction.z}}
for index in range(4):
fingerJson['bones'].append({'valid': finger.bone(index).is_valid, 'type': finger.bone(index).type,
'direction': {'x': finger.bone(index).direction.x,
'y': finger.bone(index).direction.y,
'z': finger.bone(index).direction.z}})
handJson['fingers'].append(fingerJson)
frameJson['hands'].append(handJson)
if (lastFrame.hands):
msgJson={'command':'frame', 'frame':frameJson}
self.client.publish("leapLesco", json.dumps(msgJson))
print json.dumps(frameJson)
def main():
Reader().mainloop()
if __name__ == "__main__":
main()