-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHandGesture.py
194 lines (167 loc) · 8.04 KB
/
HandGesture.py
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
import csv
import numpy as np
from sklearn import metrics
import mediapipe as mp
import matplotlib.pyplot as plt
from DatasetHandler import Dataset
from xgboost import XGBClassifier
from sklearn.metrics import plot_confusion_matrix
from sklearn.calibration import CalibratedClassifierCV
from collections import Counter
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from xgboost import XGBClassifier
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
class PostureDetector:
def __init__(self, filename, modes, detectors, transform=False):
self.filename = filename
self.transform = transform
self.modes = modes
if modes['UseML']:
self.models = {
"DT": DecisionTreeClassifier(max_depth = 100),
"KNN": KNeighborsClassifier(n_neighbors = 15),
"RF": RandomForestClassifier(n_estimators=150),
"SVM": CalibratedClassifierCV(SVC(kernel = 'rbf', C = 10)),
"XGB": XGBClassifier(use_label_encoder=False, eval_metric='mlogloss'),
"NB": GaussianNB()
}
for detector in detectors:
if detector["Status"] == False:
if modes["Info"]:
print(detector["Name"], "has been disabled")
del self.models[detector["Alias"]]
else:
if modes["Info"]:
print(detector["Name"], "is being used")
self.scale = transform
if transform and modes['Info']:
print('Data transformation has been enabled')
if modes['UseML']:
self.InitTraining()
if self.models is not None:
for model in self.models.keys():
if modes['Debug']:
print(model, 'Parameters currently in use:\n')
print(self.models[model].get_params())
else:
self.predictor = ClassicShapePredictor(modes)
if modes['Info']:
print('Hand Gesture detector is ready using', filename)
def Predict(self, unknown, mapping):
if self.modes["UseML"]:
if self.models is not None:
unknown = np.array(unknown).reshape((1,-1))
if self.transform:
unknown = self.scaler.fit_transform(unknown)
res = []
for model in self.models.keys():
result = list(self.models[model].predict_proba(unknown)[0])
res.append(self.models[model].classes_[result.index(max(result))] if max(result) >= 0.9 else -1)
if self.modes['Debug']:
print(res)
majority = Counter(res).most_common()[0][0]
return self.classes[majority] if majority != -1 else 'Unknown'
else:
return 'Unknown'
else:
return self.predictor.Predict(mapping)
def InitTraining(self, show=False):
db = Dataset(self.filename, self.modes)
tupple = db.ReadCSV(self.scale)
if tupple:
X_train, X_test, y_train, y_test = train_test_split(tupple[0], tupple[1], random_state=42, test_size=0.3)
for model in self.models.keys():
self.models[model].fit(X_train, y_train)
if self.modes['Debug']:
y_pred=self.models[model].predict(X_test)
print("Accuracy", model, ": %.2f" % metrics.accuracy_score(y_test, y_pred))
if show:
plot_confusion_matrix(self.models[model], X_test, y_test)
plt.show()
self.classes = tupple[2]
else:
self.models = None
class ClassicShapePredictor:
def __init__(self, modes):
self.modes = modes
self.mp_hands = mp.solutions.hands
self.shapes = ['One', 'Two', 'Three', 'Four', 'Five', 'Fist', 'Left', 'Right', 'Fuck Of', 'Rocking']
if modes['Info']:
print('Classic Shape predictor is ready')
print('Available Classes', self.shapes)
def __Distance(self, point1, point2):
if point1 is not None and point2 is not None:
return int(np.linalg.norm(np.array(point1) - np.array(point2)))
else:
if self.modes["Warning"]:
print('Invalid landmark points for distance measuring')
return -1
def __IsFist(self, mapping):
points = []
points.append(self.__Distance(mapping['index'], mapping['middle']))
points.append(self.__Distance(mapping['ring'], mapping['pinky']))
isUp = self.__IsUP(mapping, ['index', 'middle', 'ring', 'pinky'])
distThumb = self.__Distance(mapping['index'], mapping['thumb'])
return abs(max(points) - min(points)) <= 3 and isUp == False and distThumb >= 100
def __IsUP(self, mapping, names):
criteria = []
for key in mapping.keys():
if key != 'thumb':
if key in names:
criteria.append(mapping[key][1] < mapping['thumb'][1] + 5)
else:
criteria.append(mapping[key][1] > mapping['thumb'][1] + 5)
return all(criteria)
def __IsRight(self, mapping):
points = []
points.append(self.__Distance(mapping['index'], mapping['middle']))
points.append(self.__Distance(mapping['ring'], mapping['pinky']))
isUp = self.__IsUP(mapping, ['index', 'middle', 'ring', 'pinky'])
distThumb = self.__Distance(mapping['index'], mapping['thumb'])
direction = mapping['index'][0] < mapping['thumb'][0]
return abs(max(points) - min(points)) <= 5 and isUp == False and distThumb < 100 and direction
def __IsLeft(self, mapping):
points = []
points.append(self.__Distance(mapping['index'], mapping['middle']))
points.append(self.__Distance(mapping['ring'], mapping['pinky']))
isUp = self.__IsUP(mapping, ['index', 'middle', 'ring', 'pinky'])
distThumb = self.__Distance(mapping['index'], mapping['thumb'])
direction = mapping['index'][0] > mapping['thumb'][0]
return abs(max(points) - min(points)) <= 3 and isUp == False and distThumb < 100 and direction
def Predict(self, mapping):
try:
mappings = {
"thumb": mapping[self.mp_hands.HandLandmark.THUMB_TIP],
"index": mapping[self.mp_hands.HandLandmark.INDEX_FINGER_TIP],
"middle": mapping[self.mp_hands.HandLandmark.MIDDLE_FINGER_TIP],
"ring": mapping[self.mp_hands.HandLandmark.RING_FINGER_TIP],
"pinky": mapping[self.mp_hands.HandLandmark.PINKY_TIP]
}
if self.__IsFist(mappings):
return self.shapes[5]
elif self.__IsUP(mappings, ['index']):
return self.shapes[0]
elif self.__IsUP(mappings, ['index', 'middle']):
return self.shapes[1]
elif self.__IsUP(mappings, ['index', 'middle', 'ring']):
return self.shapes[2]
elif self.__IsUP(mappings, ['index', 'middle', 'ring', 'pinky']) and mappings['index'][0] < mappings['thumb'][0]:
return self.shapes[3]
elif self.__IsUP(mappings, ['index', 'middle', 'ring', 'pinky']) and mappings['index'][0] > mappings['thumb'][0]:
return self.shapes[4]
elif self.__IsLeft(mappings):
return self.shapes[6]
elif self.__IsRight(mappings):
return self.shapes[7]
elif self.__IsUP(mappings, ['middle']):
return self.shapes[8]
elif self.__IsUP(mappings, ['index', 'pinky']):
return self.shapes[9]
else:
return 'Unknown'
except:
return ''