1+ #!/usr/bin/env python
2+
3+ # Import libraries
4+ import socketio
5+ import eventlet
6+ from flask import Flask
7+ import numpy as np
8+ import cv2
9+
10+ import autodrive
11+
12+ ################################################################################
13+
14+ # Load YOLO Model
15+ net = cv2 .dnn .readNet ("yolov3.weights" , "yolov3.cfg" )
16+
17+ # Load Classes
18+ with open ("coco.names" , 'r' ) as f :
19+ classes = [line .strip () for line in f .readlines ()]
20+
21+ # Configuration
22+ layer_name = net .getLayerNames ()
23+ output_layer = [layer_name [i - 1 ] for i in net .getUnconnectedOutLayers ()]
24+ colors = np .random .uniform (0 , 255 , size = (len (classes ), 3 ))
25+
26+ # Initialize environment
27+ environment = autodrive .Environment ()
28+
29+ # Initialize vehicle(s)
30+ rzr_1 = autodrive .RZR ()
31+ rzr_1 .id = 'V1'
32+
33+ # Initialize the server
34+ sio = socketio .Server ()
35+
36+ # Flask (web) app
37+ app = Flask (__name__ ) # '__main__'
38+
39+ # Registering "connect" event handler for the server
40+ @sio .on ('connect' )
41+ def connect (sid , environ ):
42+ print ('Connected!' )
43+
44+ # Registering "Bridge" event handler for the server
45+ @sio .on ('Bridge' )
46+ def bridge (sid , data ):
47+ if data :
48+
49+ ########################################################################
50+ # PERCEPTION
51+ ########################################################################
52+
53+ # Vehicle data
54+ rzr_1 .parse_data (data , verbose = False )
55+
56+ # Load image
57+ img = cv2 .resize (rzr_1 .right_camera_image , (640 , 360 ))
58+ contrast = 1.0 # Contrast control (1.0-3.0)
59+ brightness = 0 # Brightness control (0-100)
60+ img = cv2 .convertScaleAbs (img , alpha = contrast , beta = brightness ) # Adjusting
61+ height , width , channel = img .shape # Resizing
62+
63+ # Detect Objects
64+ blob = cv2 .dnn .blobFromImage (img , 0.00392 , (416 , 416 ), (0 , 0 , 0 ), True , crop = False )
65+ net .setInput (blob )
66+ outs = net .forward (output_layer )
67+
68+ # Display object detection information
69+ label = None
70+ confidence = None
71+ size = None
72+ class_ids = []
73+ confidences = []
74+ boxes = []
75+ for out in outs :
76+ for detection in out :
77+ scores = detection [5 :]
78+ class_id = np .argmax (scores )
79+ confidence = scores [class_id ]
80+ if confidence > 0.5 :
81+ center_x = int (detection [0 ] * width )
82+ center_y = int (detection [1 ] * height )
83+ w = int (detection [2 ] * width )
84+ h = int (detection [3 ] * height )
85+ x = int (center_x - w / 2 )
86+ y = int (center_y - h / 2 )
87+ boxes .append ([x , y , w , h ])
88+ confidences .append (float (confidence ))
89+ class_ids .append (class_id )
90+ indices = cv2 .dnn .NMSBoxes (boxes , confidences , 0.5 , 0.4 )
91+ font = cv2 .FONT_HERSHEY_PLAIN
92+ for i in range (len (boxes )):
93+ if i in indices :
94+ x , y , w , h = boxes [i ]
95+ label = str (classes [class_ids [i ]])
96+ confidence = np .round (confidences [i ]* 100 , 2 )
97+ size = w * h
98+ print ('Class: {} \t Confidence: {} % \t Size: {} px²' .format (label , confidence , size ))
99+ color = colors [i ]
100+ cv2 .rectangle (img , (x , y ), (x + w , y + h ), color , 2 )
101+ cv2 .putText (img , label , (x , y + 30 ), font , 3 , color , 3 )
102+ cv2 .imshow ("Object Detection" , img )
103+ cv2 .waitKey (1 )
104+
105+ ########################################################################
106+ # PLANNING
107+ ########################################################################
108+
109+ # Compute distance to collision and AEB trigger
110+ DTC = np .linalg .norm (rzr_1 .position - np .array ([483.45 , 44.81 , 351.41 ]))
111+ AEB = 1 if (label == "animal" and confidence >= 50 and size >= 4000 ) else 0
112+
113+ ########################################################################
114+ # CONTROL
115+ ########################################################################
116+
117+ # Environmental conditions
118+ environment .auto_time = "False" # ["False", "True"]
119+ environment .time_scale = 60 # [0, inf) (only used if auto_time==True)
120+ environment .time_of_day = 560 # [minutes in 24 hour format] (only used if auto_time==False)
121+ environment .weather_id = 3 # [0=Custom, 1=Sunny, 2=Cloudy, 3=LightFog, 4=HeavyFog, 5=LightRain, 6=HeavyRain, 7=LightSnow, 8=HeavySnow]
122+ environment .cloud_intensity = 0.0 # [0, 1] (only used if weather_id==0)
123+ environment .fog_intensity = 0.0 # [0, 1] (only used if weather_id==0)
124+ environment .rain_intensity = 0.0 # [0, 1] (only used if weather_id==0)
125+ environment .snow_intensity = 0.0 # [0, 1] (only used if weather_id==0)
126+
127+ # Vehicle co-simulation mode
128+ rzr_1 .cosim_mode = 0
129+
130+ # Vehicle actuator commands (only if cosim_mode==0)
131+ if AEB == 1 :
132+ rzr_1 .throttle_command = 0 # [-1, 1]
133+ rzr_1 .steering_command = 0 # [-1, 1]
134+ rzr_1 .brake_command = 1 # [0, 1]
135+ rzr_1 .handbrake_command = 0 # [0, 1]
136+ else :
137+ rzr_1 .throttle_command = 0.25 # [-1, 1]
138+ rzr_1 .steering_command = 0 # [-1, 1]
139+ rzr_1 .brake_command = 0 # [0, 1]
140+ rzr_1 .handbrake_command = 0 # [0, 1]
141+
142+ # Vehicle light commands
143+ if (0 <= environment .time_of_day <= 420 or 1080 <= environment .time_of_day <= 1440 ): # Night
144+ if (environment .weather_id != 1 or environment .weather_id != 2 or (environment .weather_id == 0 and environment .fog_intensity != 0 )): # Foggy night
145+ rzr_1 .headlights_command = 3 # Vehicle headlights command [0 = Disabled, 1 = Enabled, 2 = Signature Lights, 3 = 1+2]
146+ else : # Clear night
147+ rzr_1 .headlights_command = 3 # Vehicle headlights command [0 = Disabled, 1 = Enabled, 2 = Signature Lights, 3 = 1+2]
148+ elif (environment .weather_id != 1 or environment .weather_id != 2 or (environment .weather_id == 0 and environment .fog_intensity != 0 )): # Foggy day
149+ rzr_1 .headlights_command = 2 # Vehicle headlights command [0 = Disabled, 1 = Enabled, 2 = Signature Lights, 3 = 1+2]
150+ else : # Clear day
151+ rzr_1 .headlights_command = 2 # Vehicle headlights command [0 = Disabled, 1 = Enabled, 2 = Signature Lights, 3 = 1+2]
152+
153+ # Verbose
154+ print ("DTC: {} m\t AEB: {}" .format (np .round (DTC , 2 ), AEB == 1 ))
155+
156+ ########################################################################
157+
158+ json_msg = environment .generate_commands (verbose = False ) # Generate environment message
159+ json_msg .update (rzr_1 .generate_commands (verbose = False )) # Append vehicle 1 message
160+
161+ try :
162+ sio .emit ('Bridge' , data = json_msg )
163+ except Exception as exception_instance :
164+ print (exception_instance )
165+
166+ ################################################################################
167+
168+ if __name__ == '__main__' :
169+ app = socketio .Middleware (sio , app ) # Wrap flask application with socketio's middleware
170+ eventlet .wsgi .server (eventlet .listen (('' , 4567 )), app ) # Deploy as an eventlet WSGI server
0 commit comments