-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdrive.py
110 lines (96 loc) · 3.35 KB
/
drive.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
import argparse
import base64
import json
import cv2
import numpy as np
import socketio
import eventlet
import eventlet.wsgi
import time
from PIL import Image
from PIL import ImageOps
from flask import Flask, render_template
from io import BytesIO
from keras.models import model_from_json
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array
import tensorflow as tf
tf.python.control_flow_ops = tf
num = 0
Rows, Cols = 64, 64
steering = []
def crop_img(image):
""" crop unnecessary parts """
cropped_img = image[63:136, 0:319]
resized_img = cv2.resize(cropped_img, (Cols, Rows), cv2.INTER_AREA)
img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)
return img
"""
def smoothing(angles, pre_frame):
# collect frames & print average line
angles = np.squeeze(angles)
avg_angle = 0
for ii, ang in enumerate(reversed(angles)):
if ii == pre_frame:
break
avg_angle += ang
avg_angle = avg_angle / pre_frame
return avg_angle
"""
sio = socketio.Server()
app = Flask(__name__)
model = None
prev_image_array = None
@sio.on('telemetry')
def telemetry(sid, data):
# The current steering angle of the car
steering_angle = data["steering_angle"]
# The current throttle of the car
throttle = data["throttle"]
# The current speed of the car
speed = float(data["speed"])
# The current image from the center camera of the car
imgString = data["image"]
image = Image.open(BytesIO(base64.b64decode(imgString)))
image_pre = np.asarray(image)
image_array = crop_img(image_pre)
transformed_image_array = image_array[None, :, :, :]
# This model currently assumes that the features of the model are just the images. Feel free to change this.
steering_angle = 1.0*float(model.predict(transformed_image_array, batch_size=1))
# The driving model currently just outputs a constant throttle. Feel free to edit this.
# smoothing by using previous steering angles
#steering.append(steering_angle)
#if len(steering) > 3:
# steering_angle = smoothing(steering, 3)
#global num
#cv2.imwrite('center_'+ str(num) +'.png', image_array)
#num += 1
boost = 1 - speed/30.2 + 0.3
throttle = boost if (boost < 1) else 1
if abs(steering_angle) > 0.3:
throttle *= 0.2
#throttle = 0.3
print("steering_angle : {:.3f}, throttle : {:.2f}".format(steering_angle, throttle))
send_control(steering_angle, throttle)
@sio.on('connect')
def connect(sid, environ):
print("connect ", sid)
send_control(0, 0)
def send_control(steering_angle, throttle):
sio.emit("steer", data={
'steering_angle': steering_angle.__str__(),
'throttle': throttle.__str__()
}, skip_sid=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Remote Driving')
parser.add_argument('model', type=str,
help='Path to model definition json. Model weights should be on the same path.')
args = parser.parse_args()
with open(args.model, 'r') as jfile:
model = model_from_json(json.load(jfile))
model.compile("adam", "mse")
weights_file = args.model.replace('json', 'h5')
model.load_weights(weights_file)
# wrap Flask application with engineio's middleware
app = socketio.Middleware(sio, app)
# deploy as an eventlet WSGI server
eventlet.wsgi.server(eventlet.listen(('', 4567)), app)