Your Complete Car: The Full Code, and Driving in CARLA
Download your whole self-driving car as one Python project: your drive() function, your perception networks, a camera model, lane finding, detection, traffic-light reading and tracking, in plain NumPy. Check it on your recordings, then put it in CARLA, a full 3D driving simulator, and retrain your networks on CARLA's images.
Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the camera and trained networks project, ready to run.OpenIn plain words
Your car is done; now you can take it home. This topic packs everything you built into one Python project for your own computer, and shows how to drive it in CARLA, a realistic 3D driving simulator used by researchers.
By the end of this topic you will be able to download your whole self-driving car as code, test it on your recordings, and run it in a 3D simulator.
Start with: Download your car.
Everything in one folder
Throughout the course, each piece of the car lived in its own topic. Here they come together as one project you can keep, run on your own computer and build on:
| File | What it is | Where you built it |
|---|---|---|
drive.py | your drive(car) function | the capstone |
perception.py | camera model, lane centre from the U-Net, detector decoding, traffic-light classification, tracker; Perception.step(image) gives lane, lead, pedestrian and light colour | Part 2 |
softmaxima_nn.py | runs your exported networks with NumPy only, no PyTorch needed | the export code in Part 2 |
models/ | the detector, U-Net and traffic-light classifier (examples: replace them with yours) | your Colab notebooks |
test_offline.py | checks perception against a recording's labels | Recording a labelled dataset |
carla_drive.py, carla_record.py | drive in CARLA; record CARLA data in the course's format | this topic |
Before CARLA, you can run this folder in your browser: the Simulator Studio (Camera + your networks) runs perception.py and your decisions on rendered camera images. Import your "Download your car" zip there.
Download your car
The zip contains the drive.py you last ran in the capstone, so finish that first. The capstone page has the same button.
Interactive: this part runs in your browser.
Going deeper
The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.
From camera pixels to the car object
In the capstone, drive() received ready-made perception. perception.py builds those same fields from a camera image with your networks, using everything from Part 2:
- Lane: the U-Net's "own lane" pixels are projected onto the road with the camera model, the middle of each 1 m slice is found, and a curve is fitted, exactly as in the U-Net topic. When the car ahead hides the lane, the last fit is kept for up to a second.
- The car ahead: detector boxes are matched between frames by the tracker. Where a car's box touches the road gives its distance, and the tracker's velocity gives its speed. The U-Net adds a second, independent opinion: its vehicle pixels and their depth. The detector can lose a car that fills much of the image; the U-Net still sees it. Using two different sources for the most dangerous mistake is called redundancy, and real cars rely on it (camera, radar and lidar all watch the road ahead).
- Pedestrians: tracked the same way; you get their distance, their offset to the side and their walking speed.
- Traffic light: the biggest (nearest) light box is cropped and classified by your traffic-light network.
- Thresholds per class: a missed pedestrian or red light costs much more than a false alarm, so their detection thresholds are lower (0.3 and 0.2) than for cars (0.5): the precision–recall trade-off from the detection topic, set by the cost of each mistake.
We tested this whole stack driving in the course's simulator, with the example networks seeing the simulator's camera and a drive() like the one the capstone asks for. In six test drives on all three tracks, with traffic, by day, at dusk, at night and in rain, it finished every lap without a collision or a red light. Getting there needed exactly the fixes above: the second opinion from the U-Net, keeping the lane briefly, and lower thresholds for lights. That is a typical lesson of integration: each part looked fine on its own, and the problems appeared only when they ran together.
Code: check your perception on a recording
Record at 240 × 120 in the course's simulator, then run this from the project folder on your computer.
"""Check your perception on a recording from the course's simulator, before trying it anywhere else.
python test_offline.py my_recording.npz
Record at 240 x 120 on the "Recording a labelled driving dataset" page. It compares what Perception reports
with the recording's labels: the lane centre 10 m ahead, the boxes, and the colour of the next traffic light.
"""
import sys
import time
import numpy as np
from perception import Perception, iou
d = np.load(sys.argv[1] if len(sys.argv) > 1 else "recording.npz")
images, boxes, lane10, light = d["images"], d["boxes"], d["lane10"], d["light"]
n = min(len(images), int(sys.argv[2]) if len(sys.argv) > 2 else 300)
H, W = images.shape[1:3]
P = Perception(image_size=(W, H))
lane_err, lane_missing, light_ok, light_n, light_seen, found, total, t0 = [], 0, 0, 0, 0, np.zeros(3), np.zeros(3), time.time()
for f in range(n):
r = P.step(images[f], float(d["speed"][f]), 1 / 30)
if r["lane"]:
lane_err.append(abs(r["lane"][9][1] - lane10[f])) # point 10 is 10 m ahead
else:
lane_missing += 1
if light[f] > 0: # a light is ahead within 50 m
light_n += 1
if r["light_state"]:
light_seen += 1
light_ok += r["light_state"] == ["", "red", "amber", "green"][light[f]]
for row in boxes[boxes[:, 0] == f]:
if row[5] - row[3] < 8:
continue # skip tiny, far objects
total[row[1]] += 1
found[row[1]] += any(b[1] == row[1] and iou(b[2:], row[2:6]) >= 0.5 for b in r["boxes"])
print(f"{n} frames, {(time.time() - t0) / n * 1000:.0f} ms per frame")
print(f"lane centre 10 m ahead: median error {np.median(lane_err):.2f} m, not found in {lane_missing} frames")
for c, name in enumerate(["cars", "pedestrians", "traffic lights"]):
if total[c]:
print(f"{name}: found {found[c] / total[c]:.0%} of {int(total[c])} (at least 8 px tall)")
if light_n:
print(f"a light ahead in {light_n} frames: one was detected in {light_seen / light_n:.0%} of them, "
f"and its colour was right in {light_ok / max(1, light_seen):.0%} of those")With the example networks you should see a lane error under 0.1 m, about 90% of cars found, and the light's colour right in about 90–97% of the frames where a light is detected. Pedestrians are found far less often (around 20%): the clearest place for your own detector to do better.
CARLA: a full 3D driving simulator
CARLA is a free, open-source driving simulator built for research (Dosovitskiy et al., 2017). It has realistic towns, traffic, pedestrians, traffic lights, weather and all the usual sensors. It is one of the most widely used tools for testing self-driving software without a car.
What you need: a computer with a dedicated graphics card (the CARLA documentation recommends an NVIDIA RTX 2070 or better with 8 GB of video memory), about 20 GB of disk space, and Python 3.7 to 3.12. CARLA will not run in Colab or in a browser.
- Download a packaged release (0.9.14 or later) from CARLA's GitHub releases page and unzip it.
- Install the Python client with the same version number, for example
pip install carla==0.9.16, andpip install numpy. - Start the simulator (
CarlaUE4.shon Linux,CarlaUE4.exeon Windows) and wait for the town to appear. - In your project folder, run
python carla_drive.py --town Town03 --weather day.
Code: drive in CARLA
The script mounts the course's camera on the car, runs your perception on every image, builds the same car object as the capstone (the road's curvature and the distance to the next stop line come from CARLA's map, as they come from the map in the course), calls your drive(), and checks the capstone's rules. The helpers it uses for the camera, the map and coordinate conversion are in carla_common.py.
"""Drive your car in CARLA: your perception networks see CARLA's camera, your drive() decides.
python carla_drive.py --town Town03 --weather day --cars 20 --walkers 20 --seconds 180
Start the CARLA simulator first (CarlaUE4.sh on Linux, CarlaUE4.exe on Windows). This script:
1. spawns your car with the course's camera (70 degrees, 1.4 m high, pitched 4 degrees down, 240 x 120),
2. every 0.05 s runs Perception (your U-Net, detector, light classifier and tracker) on the camera image,
3. builds the same "car" object the capstone gives drive(), using CARLA's map for the road's curvature and the
distance to the next stop line (like the course's map), and your networks for everything you can see,
4. sends your steering and throttle to CARLA, and checks the same rules as the capstone.
Options worth knowing:
--map-lane steer on the map's lane centre instead of your U-Net's (to tell perception and planning problems apart)
--true-lights use CARLA's own traffic-light state instead of your classifier's
"""
import argparse
import math
import time
import types
import numpy as np
import carla
import carla_common as cc
from drive import drive
from perception import Perception
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="localhost")
ap.add_argument("--port", type=int, default=2000)
ap.add_argument("--town", default="Town03")
ap.add_argument("--weather", default="day", choices=list(cc.WEATHERS))
ap.add_argument("--cars", type=int, default=20)
ap.add_argument("--walkers", type=int, default=20)
ap.add_argument("--spawn", type=int, default=0, help="which spawn point to start from")
ap.add_argument("--seconds", type=float, default=180)
ap.add_argument("--map-lane", action="store_true")
ap.add_argument("--true-lights", action="store_true")
args = ap.parse_args()
DT = 0.05
client, world, tm = cc.connect(args.host, args.port, args.town, DT)
cc.set_weather(world, args.weather)
actors, events = [], {"collision": None, "lane_crossings": 0, "red_lights": 0}
try:
ego = cc.spawn_ego(world, args.spawn)
actors.append(ego)
cam, q = cc.attach_camera(world, ego, "rgb")
actors.append(cam)
col = world.spawn_actor(world.get_blueprint_library().find("sensor.other.collision"), carla.Transform(), attach_to=ego)
col.listen(lambda e: events.update(collision=e.other_actor.type_id))
lane = world.spawn_actor(world.get_blueprint_library().find("sensor.other.lane_invasion"), carla.Transform(), attach_to=ego)
lane.listen(lambda e: events.update(lane_crossings=events["lane_crossings"] + 1))
actors += [col, lane]
actors += cc.spawn_traffic(client, world, tm, args.cars, args.walkers)
max_steer = math.radians(ego.get_physics_control().wheels[0].max_steer_angle)
stops = cc.stop_lines(world)
P = Perception(image_size=(cc.W, cc.H))
last_stop, distance, t0, ms = None, 0.0, time.time(), []
for k in range(int(args.seconds / DT)):
frame = world.tick()
rgb = cc.to_rgb(cc.image_for(q, frame))
pose = cc.Pose(ego)
route = cc.route_ahead(world, pose)
curv, centre, cte, heading_error = cc.map_info(route, pose)
stop, tl = cc.next_light(route, stops, pose)
t1 = time.time()
seen = P.step(rgb, pose.speed, DT)
ms.append((time.time() - t1) * 1000)
car = types.SimpleNamespace(speed=pose.speed, dt=DT, t=k * DT, curvatures=curv, cte=cte, heading_error=heading_error,
lead=seen["lead"], pedestrian=seen["pedestrian"], light=None)
car.lane = ([[x, cc.lane_at(centre, x)] for x in range(1, 31)] if args.map_lane or not seen["lane"] else seen["lane"])
if stop is not None:
state = cc.STATE.get(tl.get_state(), "unknown") if args.true_lights else (seen["light_state"] or "unknown")
car.light = {"distance": stop, "state": state}
steer, throttle = drive(car)
ego.apply_control(carla.VehicleControl(
steer=float(np.clip(-steer / max_steer, -1, 1)), # CARLA: + steers right, -1..1 of full lock
throttle=float(np.clip(throttle, 0, 1)), brake=float(np.clip(-throttle, 0, 1))))
# the capstone's rules
if last_stop is not None and stop is not None and last_stop > 0 >= stop and tl.get_state() == carla.TrafficLightState.Red:
events["red_lights"] += 1
print(f"{k * DT:6.1f} s drove through a red light")
last_stop = stop
distance += pose.speed * DT
if events["collision"]:
print(f"{k * DT:6.1f} s collision with {events['collision']}")
break
if k % 40 == 0:
print(f"{k * DT:6.1f} s {pose.speed * 3.6:5.1f} km/h lane {'U-Net' if seen['lane'] and not args.map_lane else 'map'}"
f" lead {seen['lead'] and round(seen['lead']['distance'], 1)} light {car.light and car.light['state']}")
print(f"\n{'CRASHED' if events['collision'] else 'no collision'} · {distance:.0f} m driven in {k * DT:.0f} s · "
f"{events['red_lights']} red lights run · {events['lane_crossings']} line crossings · "
f"perception {np.mean(ms):.0f} ms per frame")
finally:
settings = world.get_settings()
settings.synchronous_mode = False
world.apply_settings(settings)
tm.set_synchronous_mode(False)
cc.destroy(actors)Two switches help find where a problem is. --map-lane steers on the map's lane instead of your U-Net's, and --true-lights uses CARLA's own light colours instead of your classifier's. If the car drives well with both switches and badly without, the problem is perception, not drive().
Expect the first drive to go badly, and fix it
The example networks were trained on the course's simple simulator. CARLA's images look very different: textures, shadows, buildings, many kinds of car. The networks will miss things they would have seen in the course. This is the sim-to-real gap from the robustness topic (here, simulator to simulator), and it is exactly what happens when a real company moves to a new city or a new camera.
The fix is the same as in industry: collect data in the new world and retrain. carla_record.py lets CARLA's autopilot drive your car while it records images with labels in the course's format: the 7 segmentation classes (own lane and other lane worked out from the map), depth, boxes for cars, pedestrians and lights, and the light's colour. Upload the files to the same Colab notebooks you used in Part 2, train, export, copy the new files into models/, and drive again.
Record in several towns (CARLA has Town01 to Town07 and Town10HD) and all weathers, and keep one town only for testing. That tells you whether your networks learned driving scenes in general or only memorised one town.
Code: record a labelled dataset in CARLA
The same idea in code.
"""Record a labelled dataset in CARLA, in exactly the course's format, to retrain your networks on CARLA's images.
python carla_record.py --town Town03 --weather day --frames 3000 --out carla_day.npz
Networks trained on the course's simulator will not see CARLA's images well at first: the pictures look different
(the sim-to-real gap from the robustness topic, here sim-to-sim). Record a few datasets here in different towns and
weather, and run the same Colab notebooks from the course on them: the files have the same arrays as the course's
recordings (images, seg, depth, steer, speed, cte, lane10, light, weather, boxes), at 240 x 120.
Your car drives itself with CARLA's Traffic Manager while recording. Labels:
seg from CARLA's semantic camera, mapped to the course's 7 classes; "own lane" and "other lane" are the road
pixels inside and outside our lane, worked out from the map and the camera geometry (flat road assumed)
depth from CARLA's depth camera, in the course's units (0.25 m; 255 = sky or further than 63.5 m)
boxes cars, pedestrians and traffic lights: 3D boxes projected into the image, kept only if enough of the box
really shows that class (so hidden objects are dropped). Light colours are labelled only for the light
that controls our lane; other lights get state 0, like lights seen from behind in the course.
"""
import argparse
import math
import numpy as np
import carla
import carla_common as cc
from perception import Camera
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="localhost")
ap.add_argument("--port", type=int, default=2000)
ap.add_argument("--town", default="Town03")
ap.add_argument("--weather", default="day", choices=list(cc.WEATHERS))
ap.add_argument("--frames", type=int, default=3000)
ap.add_argument("--every", type=int, default=2, help="keep every n-th simulation step")
ap.add_argument("--cars", type=int, default=30)
ap.add_argument("--walkers", type=int, default=40)
ap.add_argument("--spawn", type=int, default=0)
ap.add_argument("--out", default="carla_recording.npz")
args = ap.parse_args()
def tags(*names):
"""CARLA's semantic tag numbers changed between versions, so look them up by name."""
return [int(getattr(carla.CityObjectLabel, n)) for n in names if hasattr(carla.CityObjectLabel, n)]
ROAD, LINES = tags("Roads"), tags("RoadLines")
VEHICLE = tags("Vehicles", "Car", "Truck", "Bus", "Motorcycle", "Bicycle")
PEDESTRIAN, LIGHT, SKY = tags("Pedestrians", "Rider"), tags("TrafficLight"), tags("Sky")
client, world, tm = cc.connect(args.host, args.port, args.town, 0.05)
cc.set_weather(world, args.weather)
cam_model = Camera(cc.W, cc.H, **cc.CAM)
actors = []
out = {k: [] for k in ["images", "seg", "depth", "steer", "speed", "cte", "lane10", "light", "weather"]}
boxes = []
try:
ego = cc.spawn_ego(world, args.spawn)
actors.append(ego)
cams = {}
for kind in ["rgb", "semantic_segmentation", "depth"]:
s, q = cc.attach_camera(world, ego, kind)
actors.append(s)
cams[kind] = q
actors += cc.spawn_traffic(client, world, tm, args.cars, args.walkers)
ego.set_autopilot(True, tm.get_port())
max_steer = math.radians(ego.get_physics_control().wheels[0].max_steer_angle)
stops, light_bbs = cc.stop_lines(world), world.get_level_bbs(carla.CityObjectLabel.TrafficLight)
lights = list(world.get_actors().filter("traffic.traffic_light"))
step = 0
while len(out["images"]) < args.frames:
frame = world.tick()
imgs = {k: cc.image_for(q, frame) for k, q in cams.items()}
step += 1
if step < 40 or step % args.every:
continue # let traffic start moving; then keep every n-th frame
f = len(out["images"])
rgb = cc.to_rgb(imgs["rgb"])
tag = np.frombuffer(imgs["semantic_segmentation"].raw_data, np.uint8).reshape(cc.H, cc.W, 4)[:, :, 2] # red channel
d = np.frombuffer(imgs["depth"].raw_data, np.uint8).reshape(cc.H, cc.W, 4).astype(np.float64)
metres = 1000 * (d[:, :, 2] + d[:, :, 1] * 256 + d[:, :, 0] * 65536) / (256 ** 3 - 1) # BGRA
pose = cc.Pose(ego)
route = cc.route_ahead(world, pose, n=60)
curv, centre, cte, _ = cc.map_info(route, pose)
width = route[0].lane_width
# the course's 7 classes: background, own lane, other lane, lane marking, vehicle, pedestrian, traffic light
seg = np.zeros((cc.H, cc.W), np.uint8)
road = np.isin(tag, ROAD)
gx, gy = np.nan_to_num(cam_model.gx), np.nan_to_num(cam_model.gy)
mid = np.interp(gx, [c[0] for c in centre], [c[1] for c in centre])
own = road & (np.abs(gy - mid) < width / 2) & (gx > 0) & (gx < max(c[0] for c in centre))
seg[road] = 2
seg[own] = 1
seg[np.isin(tag, LINES)] = 3
seg[np.isin(tag, VEHICLE)] = 4
seg[np.isin(tag, PEDESTRIAN)] = 5
seg[np.isin(tag, LIGHT)] = 6
depth = np.where(np.isin(tag, SKY) | (metres > 63.5), 255, np.round(metres / 0.25)).astype(np.uint8)
stop, tl = cc.next_light(route, stops, pose)
state = {"red": 1, "amber": 2, "green": 3}.get(cc.STATE.get(tl.get_state()), 0) if tl and stop < 50 else 0
def keep_box(corners, cls, st=0, min_share=0.15):
pts = [pose.to_car(c) for c in corners]
if min(p[0] for p in pts) < cam_model.fwd + 0.5:
return # behind or beside the camera
uv = [cam_model.project(*p)[:2] for p in pts]
x1, y1 = max(0, int(min(u for u, _ in uv))), max(0, int(min(v for _, v in uv)))
x2, y2 = min(cc.W, int(math.ceil(max(u for u, _ in uv)))), min(cc.H, int(math.ceil(max(v for _, v in uv))))
if x2 - x1 < 2 or y2 - y1 < 3:
return
want = {0: 4, 1: 5, 2: 6}[cls]
if (seg[y1:y2, x1:x2] == want).mean() < min_share:
return # mostly hidden behind something else
boxes.append([f, cls, x1, y1, x2, y2, st])
here = ego.get_location()
for a in world.get_actors().filter("vehicle.*"):
if a.id != ego.id and a.get_location().distance(here) < 60:
keep_box(a.bounding_box.get_world_vertices(a.get_transform()), 0)
for a in world.get_actors().filter("walker.pedestrian.*"):
if a.get_location().distance(here) < 40:
keep_box(a.bounding_box.get_world_vertices(a.get_transform()), 1)
for bb in light_bbs:
if bb.location.distance(here) < 60:
near = min(lights, key=lambda l: l.get_location().distance(bb.location)) if lights else None
st = state if (tl and near and near.id == tl.id) else 0
keep_box(bb.get_world_vertices(carla.Transform()), 2, st, min_share=0.05)
out["images"].append(rgb)
out["seg"].append(seg)
out["depth"].append(depth)
out["steer"].append(-ego.get_control().steer * max_steer) # back to the course's radians, + = left
out["speed"].append(pose.speed)
out["cte"].append(cte)
out["lane10"].append(cc.lane_at(centre, 10.0))
out["light"].append(state)
out["weather"].append(list(cc.WEATHERS).index(args.weather))
if f % 200 == 0:
print(f"{f} / {args.frames} frames, {len(boxes)} boxes")
dtypes = dict(images=np.uint8, seg=np.uint8, depth=np.uint8, steer=np.float32, speed=np.float32, cte=np.float32,
lane10=np.float32, light=np.int8, weather=np.int8)
np.savez_compressed(args.out, boxes=np.array(boxes, np.int16).reshape(-1, 7),
**{k: np.array(v, dtypes[k]) for k, v in out.items()})
print("saved", args.out)
finally:
settings = world.get_settings()
settings.synchronous_mode = False
world.apply_settings(settings)
tm.set_synchronous_mode(False)
cc.destroy(actors)Differences to keep in mind
- Coordinates: CARLA's world has y pointing to the right and turns to the right as positive.
carla_common.pyconverts everything into the course's car frame (y to the left), so your code does not change. - The camera: your networks only understand images from the camera they were trained with: 70° field of view, 1.4 m high, pitched 4° down, 240 × 120. The scripts mount exactly that. If you change it, record new data and retrain.
- Speeds and braking: CARLA's cars have real engine and brake models, so a throttle of 1 does not give exactly 3.5 m/s². Your
drive()may need retuning. - Junctions: the course's tracks are loops; CARLA's towns have junctions. The script follows the straightest road at every junction. Choosing turns is route planning, the first level of planning from Part 4: a good extension project.
- Untested here: the CARLA scripts follow CARLA's 0.9.x Python API, but they could not be run when this course was built, because CARLA needs a graphics card. The perception code, the coordinate conversions and the camera geometry were tested; if a CARLA call fails on your version, its error message and the CARLA Python API reference are the place to start.
With that, you have the complete car: from a camera image to a steering angle, built and trained by you, tested against 20 scenarios, and ready for a full 3D world.
Quiz
1. Why does perception.py also look at the U-Net's vehicle pixels when the detector already finds cars?
2. Why are the detection thresholds lower for pedestrians and lights than for cars?
3. Your car drives well in CARLA with --map-lane and --true-lights, but badly without them. Where is the problem?
4. The example networks miss many objects in CARLA. What is the best fix?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- CARLA documentation: Quick start ↗ installing CARLA and its Python client
- Dosovitskiy et al. (2017): CARLA: An Open Urban Driving Simulator ↗ the paper behind CARLA
- CARLA: an open-source driving simulator ↗ the research simulator used by many self-driving courses and papers