Skip to content

Commit 964870d

Browse files
Merge pull request #438 from JdeRobot/issue-437
Added brain for memory based models with previous V and 3-image input
2 parents 32fe59d + b6c2729 commit 964870d

File tree

1 file changed

+225
-0
lines changed

1 file changed

+225
-0
lines changed
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
import csv
4+
import cv2
5+
import math
6+
import numpy as np
7+
import threading
8+
import time
9+
import carla
10+
from os import path
11+
from albumentations import (
12+
Compose, Normalize, RandomRain, RandomBrightness, RandomShadow, RandomSnow, RandomFog, RandomSunFlare
13+
)
14+
from utils.constants import PRETRAINED_MODELS_DIR, ROOT_PATH
15+
from utils.logger import logger
16+
from traceback import print_exc
17+
18+
PRETRAINED_MODELS = ROOT_PATH + '/' + PRETRAINED_MODELS_DIR + 'carla_tf_models/'
19+
20+
from tensorflow.python.framework.errors_impl import NotFoundError
21+
from tensorflow.python.framework.errors_impl import UnimplementedError
22+
import tensorflow as tf
23+
gpus = tf.config.experimental.list_physical_devices('GPU')
24+
for gpu in gpus:
25+
tf.config.experimental.set_memory_growth(gpu, True)
26+
27+
class Brain:
28+
29+
def __init__(self, sensors, actuators, handler, model, config=None):
30+
self.camera_0 = sensors.get_camera('camera_0')
31+
self.camera_1 = sensors.get_camera('camera_1')
32+
self.camera_2 = sensors.get_camera('camera_2')
33+
self.camera_3 = sensors.get_camera('camera_3')
34+
35+
self.cameras_first_images = []
36+
37+
self.pose = sensors.get_pose3d('pose3d_0')
38+
39+
self.bird_eye_view = sensors.get_bird_eye_view('bird_eye_view_0')
40+
41+
self.motors = actuators.get_motor('motors_0')
42+
self.handler = handler
43+
self.config = config
44+
self.inference_times = []
45+
self.gpu_inference = True if tf.test.gpu_device_name() else False
46+
47+
self.threshold_image = np.zeros((640, 360, 3), np.uint8)
48+
self.color_image = np.zeros((640, 360, 3), np.uint8)
49+
'''
50+
self.lock = threading.Lock()
51+
self.threshold_image_lock = threading.Lock()
52+
self.color_image_lock = threading.Lock()
53+
'''
54+
self.cont = 0
55+
self.iteration = 0
56+
57+
# self.previous_timestamp = 0
58+
# self.previous_image = 0
59+
60+
self.previous_commanded_throttle = None
61+
self.previous_commanded_steer = None
62+
self.previous_commanded_brake = None
63+
self.suddenness_distance = []
64+
65+
client = carla.Client('localhost', 2000)
66+
client.set_timeout(10.0) # seconds
67+
world = client.get_world()
68+
69+
time.sleep(5)
70+
self.vehicle = world.get_actors().filter('vehicle.*')[0]
71+
72+
if model:
73+
if not path.exists(PRETRAINED_MODELS + model):
74+
logger.info("File " + model + " cannot be found in " + PRETRAINED_MODELS)
75+
logger.info("** Load TF model **")
76+
self.net = tf.keras.models.load_model(PRETRAINED_MODELS + model)
77+
logger.info("** Loaded TF model **")
78+
else:
79+
logger.info("** Brain not loaded **")
80+
logger.info("- Models path: " + PRETRAINED_MODELS)
81+
logger.info("- Model: " + str(model))
82+
83+
self.previous_speed = 0
84+
85+
self.image_1 = 0
86+
self.image_2 = 0
87+
self.image_3 = 0
88+
89+
90+
def update_frame(self, frame_id, data):
91+
"""Update the information to be shown in one of the GUI's frames.
92+
93+
Arguments:
94+
frame_id {str} -- Id of the frame that will represent the data
95+
data {*} -- Data to be shown in the frame. Depending on the type of frame (rgbimage, laser, pose3d, etc)
96+
"""
97+
if data.shape[0] != data.shape[1]:
98+
if data.shape[0] > data.shape[1]:
99+
difference = data.shape[0] - data.shape[1]
100+
extra_left, extra_right = int(difference/2), int(difference/2)
101+
extra_top, extra_bottom = 0, 0
102+
else:
103+
difference = data.shape[1] - data.shape[0]
104+
extra_left, extra_right = 0, 0
105+
extra_top, extra_bottom = int(difference/2), int(difference/2)
106+
107+
108+
data = np.pad(data, ((extra_top, extra_bottom), (extra_left, extra_right), (0, 0)), mode='constant', constant_values=0)
109+
110+
self.handler.update_frame(frame_id, data)
111+
112+
def update_pose(self, pose_data):
113+
self.handler.update_pose3d(pose_data)
114+
115+
def execute(self):
116+
image = self.camera_0.getImage().data
117+
image_1 = self.camera_1.getImage().data
118+
image_2 = self.camera_2.getImage().data
119+
image_3 = self.camera_3.getImage().data
120+
121+
bird_eye_view_1 = self.bird_eye_view.getImage(self.vehicle)
122+
123+
if self.cameras_first_images == []:
124+
self.cameras_first_images.append(image)
125+
self.cameras_first_images.append(image_1)
126+
self.cameras_first_images.append(image_2)
127+
self.cameras_first_images.append(image_3)
128+
self.cameras_first_images.append(bird_eye_view_1)
129+
130+
self.cameras_last_images = [
131+
image,
132+
image_1,
133+
image_2,
134+
image_3,
135+
bird_eye_view_1
136+
]
137+
138+
self.update_frame('frame_1', image_1)
139+
self.update_frame('frame_2', image_2)
140+
self.update_frame('frame_3', image_3)
141+
142+
self.update_frame('frame_0', bird_eye_view_1)
143+
144+
self.update_pose(self.pose.getPose3d())
145+
146+
image_shape=(50, 150)
147+
img_base = cv2.resize(bird_eye_view_1, image_shape)
148+
149+
AUGMENTATIONS_TEST = Compose([
150+
Normalize()
151+
])
152+
image = AUGMENTATIONS_TEST(image=img_base)
153+
img = image["image"]
154+
155+
if type(self.image_1) is int:
156+
self.image_1 = img
157+
if type(self.image_2) is int:
158+
self.image_2 = img
159+
else:
160+
self.image_1 = self.image_2
161+
self.image_2 = self.image_1
162+
self.image_3 = img
163+
164+
velocity_dim = np.full((150, 50), self.previous_speed/30)
165+
self.image_1 = np.dstack((self.image_1, velocity_dim))
166+
self.image_2 = np.dstack((self.image_2, velocity_dim))
167+
self.image_3 = np.dstack((self.image_3, velocity_dim))
168+
169+
img = [self.image_3, self.image_2 , self.image_1]
170+
171+
img = np.expand_dims(img, axis=0)
172+
start_time = time.time()
173+
try:
174+
prediction = self.net.predict(img, verbose=0)
175+
self.inference_times.append(time.time() - start_time)
176+
throttle = prediction[0][0]
177+
steer = prediction[0][1] * (1 - (-1)) + (-1)
178+
break_command = prediction[0][2]
179+
speed = self.vehicle.get_velocity()
180+
vehicle_speed = 3.6 * math.sqrt(speed.x**2 + speed.y**2 + speed.z**2)
181+
self.previous_speed = vehicle_speed
182+
183+
if vehicle_speed > 300:
184+
self.motors.sendThrottle(0)
185+
self.motors.sendSteer(steer)
186+
self.motors.sendBrake(0)
187+
else:
188+
if vehicle_speed < 2:
189+
self.motors.sendThrottle(1.0)
190+
self.motors.sendSteer(0.0)
191+
self.motors.sendBrake(0)
192+
else:
193+
self.motors.sendThrottle(throttle)
194+
self.motors.sendSteer(steer)
195+
self.motors.sendBrake(0)
196+
197+
if self.previous_commanded_throttle != None:
198+
a = np.array((throttle, steer, break_command))
199+
b = np.array((self.previous_commanded_throttle, self.previous_commanded_steer, self.previous_commanded_brake))
200+
distance = np.linalg.norm(a - b)
201+
self.suddenness_distance.append(distance)
202+
203+
self.previous_commanded_throttle = throttle
204+
self.previous_commanded_steer = steer
205+
self.previous_commanded_brake = break_command
206+
except NotFoundError as ex:
207+
logger.info('Error inside brain: NotFoundError!')
208+
logger.warning(type(ex).__name__)
209+
print_exc()
210+
raise Exception(ex)
211+
except UnimplementedError as ex:
212+
logger.info('Error inside brain: UnimplementedError!')
213+
logger.warning(type(ex).__name__)
214+
print_exc()
215+
raise Exception(ex)
216+
except Exception as ex:
217+
logger.info('Error inside brain: Exception!')
218+
logger.warning(type(ex).__name__)
219+
print_exc()
220+
raise Exception(ex)
221+
222+
223+
224+
225+

0 commit comments

Comments
 (0)