-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_slope.py
141 lines (124 loc) · 7.07 KB
/
app_slope.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
from flask import Flask
from flask import Response
from flask import request
from flask import jsonify
import json
import pandas as pd
import numpy as np
import glob
import sys
import pickle
import scipy.signal as signal
import matplotlib.pyplot as plt
from scipy.fftpack import fft, fftshift
from numpy import linalg as LA
import copy
from matplotlib.colors import ListedColormap
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, log_loss, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier, RadiusNeighborsClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis, LinearDiscriminantAnalysis
from sklearn.svm import SVC, LinearSVC, NuSVC
from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from operator import itemgetter
def read_test_data(data): # only one sample
columns = ['score_overall', 'nose_score', 'nose_x', 'nose_y', 'leftEye_score', 'leftEye_x', 'leftEye_y',
'rightEye_score', 'rightEye_x', 'rightEye_y', 'leftEar_score', 'leftEar_x', 'leftEar_y',
'rightEar_score', 'rightEar_x', 'rightEar_y', 'leftShoulder_score', 'leftShoulder_x', 'leftShoulder_y',
'rightShoulder_score', 'rightShoulder_x', 'rightShoulder_y', 'leftElbow_score', 'leftElbow_x',
'leftElbow_y', 'rightElbow_score', 'rightElbow_x', 'rightElbow_y', 'leftWrist_score', 'leftWrist_x',
'leftWrist_y', 'rightWrist_score', 'rightWrist_x', 'rightWrist_y', 'leftHip_score', 'leftHip_x',
'leftHip_y', 'rightHip_score', 'rightHip_x', 'rightHip_y', 'leftKnee_score', 'leftKnee_x', 'leftKnee_y',
'rightKnee_score', 'rightKnee_x', 'rightKnee_y', 'leftAnkle_score', 'leftAnkle_x', 'leftAnkle_y',
'rightAnkle_score', 'rightAnkle_x', 'rightAnkle_y']
csv_data = np.zeros((len(data), len(columns)))
for i in range(csv_data.shape[0]):
one = []
one.append(data[i]['score'])
for obj in data[i]['keypoints']:
one.append(obj['score'])
one.append(obj['position']['x'])
one.append(obj['position']['y'])
csv_data[i] = np.array(one)
test_case= pd.DataFrame(csv_data, columns=columns)
return test_case # the format is pandas dataframe
def edistance(x1, x2, y1, y2): # inputs are pandas series
# this function will accept 4 vectors x1,y1, x2,y2 of the same length and calculate the euclidean distance[sqrt((x1-x2)^2 + (y1-y2)^2)] of them and return a vector of the same length
x_ = x1-x2
x = pow(x_, 2)
y_ = y1-y2
y = pow(y_, 2)
return pd.Series(np.round(np.sqrt(x+y),3))
def get_feature_onesample(sample):
scale_x = edistance(sample['leftHip_x'], sample['rightHip_x'], sample['leftHip_y'], sample['rightHip_y'])
x_hip_middle = (sample['leftHip_x']+ sample['rightHip_x'])/2.000
y_hip_middle = (sample['leftHip_y'] + sample['rightHip_y'])/2.000
scale_y = edistance (sample['nose_x'],x_hip_middle ,sample['nose_y'], y_hip_middle)
norm_sample = sample.copy()
collist_x = [ 'leftShoulder_x', 'rightShoulder_x', 'leftElbow_x','rightElbow_x', 'leftWrist_x', 'rightWrist_x']
collist_y = [ 'leftShoulder_y','rightShoulder_y','leftElbow_y', 'rightElbow_y', 'leftWrist_y', 'rightWrist_y']
for colname_x in collist_x:
str = 'norm_'
norm_sample[str+colname_x] = (norm_sample[colname_x]-norm_sample['nose_x'])/scale_x
for colname_y in collist_y:
norm_sample[str+colname_y] = (norm_sample[colname_y]-norm_sample['nose_y'])/scale_y
feature_one_sample = pd.DataFrame()
feature_one_sample['leftwrist_nose_slope'] = np.divide((norm_sample['norm_rightWrist_y'] - norm_sample['nose_y']) , (norm_sample['norm_leftWrist_x'] - norm_sample['nose_x']))
feature_one_sample['rightwrist_nose_slope'] = np.divide((norm_sample['norm_rightWrist_y'] - norm_sample['nose_y']),(norm_sample['norm_rightWrist_x'] - norm_sample['nose_x']))
feature_one_sample['leftElbow_nose_slope'] = np.divide((norm_sample['norm_leftElbow_y'] - norm_sample['nose_y']),(norm_sample['norm_leftElbow_x'] - norm_sample['nose_x']))
feature_one_sample['rightElbow_nose_slope'] = np.divide((norm_sample['norm_rightElbow_y'] - norm_sample['nose_y']),(norm_sample['norm_rightElbow_x'] - norm_sample['nose_x']))
feature_one_sample['rightwrist_rightshoulder_slope'] = np.divide((norm_sample['norm_rightWrist_y'] - norm_sample['norm_rightShoulder_x']),(norm_sample['norm_rightWrist_x'] - norm_sample['norm_rightShoulder_y']))
feature_one_sample['rightwrist_rightshoulder_distance'] = edistance(norm_sample['norm_rightWrist_x'],norm_sample['norm_rightShoulder_y'],norm_sample['norm_rightShoulder_x'],norm_sample['norm_rightShoulder_y'] )
feature_one_sample['leftwrist_leftShoulder_distance'] = edistance(norm_sample['norm_leftWrist_x'],norm_sample['norm_leftShoulder_x'], norm_sample['norm_leftWrist_y'], norm_sample['norm_leftShoulder_y'])
feature_one_sample = np.asarray(np.round(feature_one_sample.mean(axis=0), 3)).reshape(1,-1)
return feature_one_sample
def predict_gesture(json_object):
trained_models_loaded = pickle.load(open('trained_classifier.pkl', 'rb'))
test_case = read_test_data(json_object)
x_test = get_feature_onesample(test_case)
label_dict = {0: 'buy', 1: 'communicate', 2: 'fun', 3: 'hope', 4: 'mother', 5: 'really'}
predictions = {}
for i, name in enumerate(trained_models_loaded.keys()):
clf = trained_models_loaded[name]
y_pred = clf.predict(x_test)
predictions[str(i+1)] = label_dict[y_pred[0]]
print "y_pred[0] = ", y_pred[0], " ", name, " ", predictions[str(i+1)]
return predictions
app = Flask(__name__)
@app.route('/')
def root():
html = "<html>" \
+ "<head><title>CSE535-Gesture Predictor</title></head>" \
+ "<body>" \
+ "<h1>Gesture Predictor - CSE 535 Assignment 2 - Group 3</h1>" \
+ "<h2>API Endpoints:</h2>" \
+ "<ul>"\
+ "<li>" + "<b>Gesture Prediction:</b> " + request.host_url + "api/predict_gesture" + " [POST] 'application/json'" + "</li>" \
+ "</ul>" \
+ "</body>" \
+ "</html>"
return html
@app.route('/api/predict_gesture', methods=[ 'POST' ])
def api_predict_gesture():
pose_frames = request.get_json()
if(pose_frames == None):
return "ERROR reading json data from request"
result = predict_gesture(pose_frames)
print("result: ", result)
return Response(json.dumps(result), mimetype='application/json')
@app.route('/api/test_json', methods=['POST'])
def test_json():
pose_frames = request.get_json()
if(pose_frames == None):
return "ERROR reading json data from request"
return Response(json.dumps(pose_frames), mimetype='application/json')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')