Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Xander44-4/traffic_reducer/llms.txt

Use this file to discover all available pages before exploring further.

Beyond counting vehicles to decide which lane gets the green light, Traffic Reducer monitors every processed frame for two safety-critical conditions: the presence of pedestrians in the intersection area and the appearance of emergency vehicles exhibiting characteristic light signatures. When either condition is detected it is surfaced immediately to the dashboard and can override normal signal-phase logic, ensuring that human safety and emergency response always take precedence over queue-length optimisation.

Pedestrian detection

COCO class 0 (person) is included in the YOLOv8 inference call alongside vehicle classes, but persons are handled on a separate path inside _run_yolo(). Instead of being tested against zone polygons, each person detection increments a dedicated counter:
if cls_id == 0:
    pedestrian_count += 1
    boxes.append(('ped', float(x1), float(y1), float(x2), float(y2)))
    continue
The count is stored in traffic_state['pedestrians'] and returned by the /stats endpoint. The frontend displays the raw count at all times and labels the current priority as "PEATONES" when the pedestrian count exceeds 5, indicating a crossing situation that should hold or redirect the active signal phase. Pedestrian bounding boxes are drawn in bright blue-white (255, 200, 0) on the annotated frame overlay so operators can visually verify detections in the dashboard video feed.

Emergency vehicle detection

Emergency vehicle identification is performed by _looks_like_emergency(), a method that analyses the HSV color distribution of a vehicle’s bounding-box crop to detect active emergency lighting. It is only called for class 5 (bus) and class 7 (truck) detections that have already passed the confidence threshold — smaller vehicle classes are excluded because their bounding boxes are rarely large enough to contain reliable lighting information.

Full method source

def _looks_like_emergency(self, frame, x1, y1, x2, y2, cls_id):
    h, w, _ = frame.shape
    x1 = max(0, int(x1)); y1 = max(0, int(y1))
    x2 = min(w, int(x2)); y2 = min(h, int(y2))
    if x2 <= x1 or y2 <= y1:
        return False

    crop = frame[y1:y2, x1:x2]
    if crop.size == 0:
        return False

    area = (x2 - x1) * (y2 - y1)
    if cls_id == 7 and area < 8000:
        return False
    if cls_id == 5 and area < 12000:
        return False

    hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
    total = crop.shape[0] * crop.shape[1]

    red1 = cv2.inRange(hsv, (0, 130, 110), (10, 255, 255))
    red2 = cv2.inRange(hsv, (170, 130, 110), (180, 255, 255))
    red_ratio = float(np.count_nonzero(red1 | red2)) / total

    yellow = cv2.inRange(hsv, (18, 130, 130), (35, 255, 255))
    yellow_ratio = float(np.count_nonzero(yellow)) / total

    blue = cv2.inRange(hsv, (95, 150, 100), (130, 255, 255))
    blue_ratio = float(np.count_nonzero(blue)) / total

    if red_ratio > 0.18 or yellow_ratio > 0.22:
        return True
    if red_ratio > 0.07 and blue_ratio > 0.05:
        return True
    return False

Detection logic breakdown

Step 1 — Minimum bounding-box area Small bounding boxes produce too few pixels for reliable color analysis and are rejected before any HSV computation:
Class IDVehicle typeMinimum area
7Truck8 000 px²
5Bus12 000 px²
Buses require a larger minimum because their bodies contain more structural color variation that can produce false positives at small scales. Step 2 — HSV color channel analysis The bounding-box region is cropped from the original BGR frame and converted to HSV. Three color masks are applied:
ChannelHSV range(s)Emergency threshold
Red(0,130,110)→(10,255,255) and (170,130,110)→(180,255,255)> 18 % of crop area
Yellow(18,130,130)→(35,255,255)> 22 % of crop area
Blue(95,150,100)→(130,255,255)Used in combined rule only
Red is split across two HSV ranges because the hue channel wraps around at 180°, placing deep reds near both 0° and 180°. Step 3 — Decision rules The method returns True (emergency detected) if either of the following conditions holds:
  • red_ratio > 0.18 OR yellow_ratio > 0.22 — a dominant single emergency color saturates most of the vehicle crop.
  • red_ratio > 0.07 AND blue_ratio > 0.05 — a combined red-and-blue signature, characteristic of police and ambulance light bars.

Emergency flag propagation

When _looks_like_emergency() returns True for any detection in a frame, _run_yolo() sets emergency_detected = True and appends the box with the label 'emergency'. After the YOLO future resolves, the flag flows into traffic_state:
self.traffic_state['emergency'] = data['emergency']
The /stats endpoint exposes it as a JSON boolean:
{
  "emergency": true,
  "phase": "NORTE",
  "norte": 8,
  "sur": 3,
  "este": 14,
  "oeste": 2
}
The dashboard reads emergency on every /stats poll (every 1 500 ms) and displays "SÍ" in red when true, labelling the active priority as "EMERGENCIA". Emergency vehicle bounding boxes are rendered with a vivid red border (0, 50, 255) at 3 px width to distinguish them clearly from ordinary vehicle detections on the video feed.

Priority hierarchy

When multiple conditions are active simultaneously, the dashboard applies the following precedence (highest to lowest):
  1. Emergency vehicle detected — takes absolute precedence; the "EMERGENCIA" label and red indicator are shown regardless of pedestrian count or vehicle counts.
  2. Pedestrian crossing (count > 5) — overrides the normal queue-based priority label with "PEATONES".
  3. Majority-rule lane selection — standard operation when neither override condition is active.
Emergency detection is a heuristic based on color-pixel ratios, not on strobe-pattern recognition or RF signals. False positives can occur with large vehicles that carry bright red or yellow livery — for example fire-engine-red sports cars, red articulated lorries, or yellow school buses. If your deployment region has a high density of such vehicles, tune the HSV threshold values and minimum area constants in _looks_like_emergency() to reduce false-positive rates before going live.

Build docs developers (and LLMs) love