Looking for Caresses
SoRo project to let Miro interact as a pet would do
 All Classes Functions Variables Pages
Data_input.py
1 #!/usr/bin/env python
2 
3 ################################################################
4 
5 import rospy
6 from std_msgs.msg import String
7 from sensor_msgs.msg import Image,CompressedImage
8 from geometry_msgs.msg import Twist
9 import numpy as np
10 from look_caresses_pkg.msg import platform_config,platform_sensors,platform_state,platform_mics,platform_control,core_state,core_control,core_config,bridge_config,bridge_stream
11 import os
12 from os import listdir
13 from os.path import isfile, join
14 from sklearn.metrics import confusion_matrix
15 from pylab import *
16 
17 import math
18 import numpy
19 import time
20 import sys
21 from miro_constants import miro
22 from keras.models import Sequential
23 from keras.layers import Dense, Dropout, Activation
24 from keras.layers.recurrent import LSTM
25 from keras.layers import Embedding
26 from keras.preprocessing.sequence import pad_sequences
27 from keras.utils import np_utils
28 from datetime import datetime
29 import keras
30 from keras import metrics
31 from keras import backend as K
32 from keras import regularizers
33 import tensorflow as tf
34 
35 from keras.models import load_model
36 
37 
38 def fmt(x, f): #function used for conversion from byteArray to String (The values that we get for the head touch sensors are byteArrays)
39  s = ""
40  x = bytearray(x)
41  for i in range(0, len(x)):
42  if not i == 0:
43  s = s + ", "
44  s = s + f.format(x[i])
45  return s
46 
47 
48 
50  def callback_platform_sensors(self, subscriber_msg):
51  # ignore until active
52  if not self.active:
53  return
54  global touch_sensors
55  global new_data
56  global dataset
57  global send_data
58  global start_index
59  global end_index
60  global data_flag
61  global pattern
62  global count
63  global model
64  global graph
65 
66 
67  #print(fmt(subscriber_msg.touch_head, '{0:.0f}')) #Uncomment and see what happens in output, It converts from byteArray to str
68 
69  new_data = True #set receive flag
70  touch_sensors = [0,0,0,0,0,0,0,0]
71 
72  touch_sensors[0] = int(fmt(subscriber_msg.touch_head, '{0:.0f}')[0]) # Sensor at 16'oclock on head
73  touch_sensors[1] = int(fmt(subscriber_msg.touch_head, '{0:.0f}')[3]) # Sensor at 14'oclock on head
74  touch_sensors[2] = int(fmt(subscriber_msg.touch_head, '{0:.0f}')[6]) # Sensor at 10'oclock on head
75  touch_sensors[3] = int(fmt(subscriber_msg.touch_head, '{0:.0f}')[9]) # Sensor at 20'oclock on head
76  touch_sensors[4] = int(fmt(subscriber_msg.touch_body, '{0:.0f}')[0]) # Sensor at 16'oclock on head
77  touch_sensors[5] = int(fmt(subscriber_msg.touch_body, '{0:.0f}')[3]) # Sensor at 14'oclock on head
78  touch_sensors[6] = int(fmt(subscriber_msg.touch_body, '{0:.0f}')[6]) # Sensor at 10'oclock on head
79  touch_sensors[7] = int(fmt(subscriber_msg.touch_body, '{0:.0f}')[9]) # Sensor at 20'oclock on head
80  #print touch_sensors
81 
82  def loop(self):
83  global new_data
84  global touch_sensors
85  global dataset
86  global data_flag
87  global start_index
88  global end_index
89  global pattern
90  global send_data
91  gesture_str = ""
92  while not rospy.is_shutdown():
93  if new_data:
94  new_data = False #un-set flag
95 
96  #print aList
97  dataset.append(touch_sensors)
98  if len(dataset) == 105:
99  data_flag = True
100  #print "before %d",len(dataset)
101  if data_flag == True:
102  pattern = dataset
103  x_dataset = np.array(pattern)
104  dataset.pop(0)
105  X_train = np.reshape(x_dataset, (1,x_dataset.shape[0], x_dataset.shape[1]))
106  XDataset = pad_sequences(X_train, maxlen=None, dtype='int32',padding='pre', truncating='pre', value=0.)
107  aux =0
108  with self.graph.as_default():
109  predict = self.model.predict(X_train)
110  threshold = 0.5
111  for i in range(len(predict[0])):
112  if predict[0][i] >= threshold:
113  aux = 1
114 
115  if aux == 1:
116  index = np.argmax(predict) #index of the maximum value
117  if index == 0:
118  gesture_str = "CarBottomTop"
119  elif index == 1:
120  gesture_str = "FixedBody"
121  elif index == 2:
122  gesture_str = "PatHead"
123  elif index == 3:
124  gesture_str = "FixedHead"
125  elif index == 4:
126  gesture_str = "PatBody"
127  elif index == 5:
128  gesture_str = "CarTopBottom"
129  else:
130  gesture_str = "No_Gesture"
131 
132  rospy.loginfo(gesture_str) # It's like rosinfo in C++
133  self.pub.publish(gesture_str)
134 
135  self.rate.sleep()
136 
137 
138  def __init__(self):
139  # report
140  print("initialising...")
141  print(sys.version)
142  print(datetime.time(datetime.now()))
143 
144  # default data
145  self.platform_sensors = None
146 
147  # options
148  self.robot_name = ""
149 
150  # handle args
151  for arg in sys.argv[1:]:
152  f = arg.find('=')
153  if f == -1:
154  key = arg
155  val = ""
156  else:
157  key = arg[:f]
158  val = arg[f+1:]
159  if key == "robot":
160  self.robot_name = val
161  else:
162  error("argument not recognised \"" + arg + "\"")
163 
164 
165 
166  # check we got at least one
167  if len(self.robot_name) == 0:
168  error("argument \"robot\" must be specified")
169 
170  # set inactive
171  self.active = False
172 
173  # topic root
174  topic_root = "/miro/" + self.robot_name
175  print "topic_root", topic_root
176 
177  # publish
178  self.pub = rospy.Publisher('/miro/look4caresses/classifyGesture', String, queue_size=10) # classifyGesture is the name of the topic on which we will publish , string is the parameter
179 
180  ####### Deleated some functions from here (compared to the orignal file)
181 
182  # subscribe
183  self.sub_sensors = rospy.Subscriber(topic_root + "/platform/sensors", platform_sensors, self.callback_platform_sensors)
184  ####### Deleated some functions from here (compared to the orignal file)
185  global model
186  global graph
187 
188  self.model = load_model('my_model_new.h5')
189  self.model._make_predict_function()
190  self.graph = tf.get_default_graph()
191 
192  adm = keras.optimizers.Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
193  self.model.compile(loss='categorical_crossentropy',optimizer=adm ,metrics=['accuracy'])
194 
195  # set active
196  self.active = True
197 
198  self.rate = rospy.Rate(20)
199 
200 if __name__ == "__main__":
201  global count
202  global data_flag
203  global dataset
204  global pattern
205  global send_data
206  global start_index
207  global end_index
208  global model
209  global graph
210  global touch_sensors
211  global new_data
212  new_data = False
213  touch_sensors = []
214  start_index = 0
215  end_index = 105
216  pattern = []
217  send_data = []
218  dataset = []
219  data_flag = False
220  count = 0
221  rospy.init_node("miro_touch_control_ros_client_py", anonymous=True)
223  main.loop()
224  rospy.spin()
225 
model
Deleated some functions from here (compared to the orignal file)
Definition: Data_input.py:188
sub_sensors
Deleated some functions from here (compared to the orignal file)
Definition: Data_input.py:183