-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto.py
191 lines (161 loc) · 6.38 KB
/
auto.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
"""
.. module:: autopilot
:synopsis: Main routine for autopilot package
.. moduleauthor:: Adam Moss <[email protected]>
"""
import threading
import importlib
from autopilot.settings import api_settings
import collections
import cv2
import time
import logging
class AutoPilot:
def __init__(self, capture=None, front_wheels=None, back_wheels=None, camera_control=None,
debug=False, mode='drive', model=None, width=320, height=240, capture_src="/dev/video0", max_speed=35):
"""
:param capture:
:param front_wheels:
:param back_wheels:
:param camera_control:
:param debug:
:param mode:
:param model:
:param width:
:param height:
:param capture_src:
"""
try:
from art import text2art
print(text2art("MLiS AutoPilot"))
except ModuleNotFoundError:
print('MLiS AutoPilot')
assert mode in ['test', 'camera', 'drive', 'ludicrous', 'plaid']
# Try getting camera from already running capture object, otherwise get a new CV2 video capture object
if mode != 'test':
if capture is not None and hasattr(capture, 'camera'):
self.camera = capture.camera
else:
self.camera = cv2.VideoCapture(capture_src) #0, 1 or -1
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
if not self.camera.isOpened():
raise ValueError("Failed to open the camera")
else:
self.camera = None
# These are picar controls
self.front_wheels = front_wheels
self.back_wheels = back_wheels
self.camera_control = camera_control
self.max_speed = max_speed
self.debug = debug
self.mode = mode
# Thread variables
self._started = False
self._terminate = False
self._drive_thread = None
self._frame_thread = None
# Latest frame
self.current_frame = collections.deque(maxlen=1)
# Logging
self.inference_times = collections.deque(maxlen=10)
logging.basicConfig(filename="autopilot.log", level=logging.INFO)
# Load the model
self.load_model(model)
def load_model(self, model):
# NN Model
if model is None:
model = api_settings.MODEL
print('Using %s model' % model)
logging.info('Using %s model' % model)
module = importlib.import_module('autopilot.models.%s.model' % model)
self.model = module.Model()
logging.info('Loaded model')
def start(self):
"""
Starts autopilot in separate thread
:return:
"""
if self._started:
print('[!] Self driving has already been started')
return None
self._started = True
self._terminate = False
self._frame_thread = threading.Thread(target=self._update_frame, args=())
self._frame_thread.start()
self._drive_thread = threading.Thread(target=self._drive, args=())
self._drive_thread.start()
def stop(self):
"""
Stops autopilot
:return:
"""
self._started = False
self._terminate = True
if self._frame_thread is not None:
self._frame_thread.join()
if self._drive_thread is not None:
self._drive_thread.join()
if self.back_wheels is not None:
self.back_wheels.speed = 0
# Release the video device
if self.camera is not None:
self.camera.release()
def _update_frame(self):
"""
Separate thread to continually update latest frame
:return:
"""
if self.mode == 'test':
while not self._terminate:
frame = cv2.imread(api_settings.TEST_IMAGE)
self.current_frame.append(frame)
else:
while not self._terminate:
ret, frame = self.camera.read()
# Do not try to perform inference on a value of None
if not ret:
# self.stop()
# raise ValueError("Failed to fetch the frame")
print("Failed to fetch the next frame.")
continue
self.current_frame.append(frame)
def _drive(self):
"""
Drive routine for autopilot. Processes frame from camera
:return:
"""
while not self._terminate:
if len(self.current_frame) > 0:
frame = self.current_frame.pop()
start_time = time.time()
angle, speed = self.model.predict(frame)
inference_time = 1000 * (time.time() - start_time)
self.inference_times.append(inference_time)
angle = int(angle)
speed = max(min(int(speed), self.max_speed), 0)
if self.debug:
if len(self.inference_times) > 0:
mean_inference_time = sum(self.inference_times) / len(self.inference_times)
else:
mean_inference_time = inference_time
print('Inference time {0:0.2f} ms, mean {1:0.2f} ms'.format(inference_time, mean_inference_time))
print('Angle: {0}, Speed: {1}'.format(angle, speed))
if self.mode == 'test':
assert 70 <= angle <= 110, "The angle is not realistic for the test image"
assert 20 <= speed <= 35, "The speed is not realistic for the test image"
elif self.mode in ['drive', 'ludicrous', 'plaid']:
# Do not allow angle or speed to go out of allowed range
angle = max(min(angle, self.front_wheels._max_angle), self.front_wheels._min_angle)
if self.mode == 'ludicrous':
speed = 50
elif self.mode == 'plaid':
speed = 100
# Set picar angle and speed
self.front_wheels.turn(angle)
if speed > 0:
self.back_wheels.forward()
self.back_wheels.speed = speed
else:
self.back_wheels.backward()
self.back_wheels.speed = abs(speed)