0% found this document useful (0 votes)
24 views3 pages

Vehicle Detection and Signal Timing Code

Uploaded by

Shweta Bagade
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views3 pages

Vehicle Detection and Signal Timing Code

Uploaded by

Shweta Bagade
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import cv2

import time
import numpy as np

# Load pre-trained vehicle detection model


vehicle_cascade = [Link]('[Link]')

# Video capture
cap1 = [Link]('traffic_video.mp4')
cap2 = [Link]('traffic_video2.mp4')
cap3 = [Link]('traffic_video3.mp4')
cap4 = [Link]('traffic_video1.mp4')

# Video dimensions
frame_width = int([Link](cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int([Link](cv2.CAP_PROP_FRAME_HEIGHT))

# Initialize signal timing parameters (in seconds)


total_time = 60 # Total time for one cycle of signals
green_time = 20 # Default green time for each signal
yellow_time = 5 # Default yellow time for each signal

# Function to calculate signal times based on vehicle density


def calculate_signal_times(vehicle_density):
# Adjust signal times based on vehicle density
# Example: Reduce green time and increase yellow time for higher vehicle
density
adjusted_green_time = max(5, green_time - vehicle_density)
adjusted_yellow_time = min(10, yellow_time + vehicle_density)
return adjusted_green_time, adjusted_yellow_time

# Initialize signal times for each quadrant


signal_times = [total_time] * 4

# Start time for signal timing


start_time = [Link]()

# Create window to display videos


[Link]("Multi-Window Display", cv2.WINDOW_NORMAL)
[Link]("Multi-Window Display", frame_width * 2, frame_height * 2)

# Middle line position for vehicle counting


middle_line_y = frame_height // 2

while True:
# Read frames from all four videos
ret1, frame1 = [Link]()
ret2, frame2 = [Link]()
ret3, frame3 = [Link]()
ret4, frame4 = [Link]()

if not (ret1 and ret2 and ret3 and ret4):


break

# Resize frames
frame1 = [Link](frame1, (frame_width, frame_height))
frame2 = [Link](frame2, (frame_width, frame_height))
frame3 = [Link](frame3, (frame_width, frame_height))
frame4 = [Link](frame4, (frame_width, frame_height))

# Combine frames into a single window


combined_frame = [Link]((frame_height * 2, frame_width * 2, 3),
dtype=np.uint8)

# Assign each frame to its corresponding quadrant in the combined frame


combined_frame[0:frame_height, 0:frame_width] = frame1
combined_frame[0:frame_height, frame_width:frame_width * 2] = frame2
combined_frame[frame_height:frame_height * 2, 0:frame_width] = frame3
combined_frame[frame_height:frame_height * 2, frame_width:frame_width * 2]
= frame4

# Detect vehicles and count them in each quadrant


total_vehicles = 0
for idx, quadrant in enumerate([frame1, frame2, frame3, frame4], start=1):
gray = [Link](quadrant, cv2.COLOR_BGR2GRAY)
vehicles = vehicle_cascade.detectMultiScale(gray, 1.1, 3)

# Count vehicles based on middle line position


for (x, y, w, h) in vehicles:
if y <= middle_line_y <= y + h:
total_vehicles += 1

# Display vehicle count and signal information


if signal_times[idx - 1] > 0:
signal_color = "Green"#(0, 255, 0) # Green
time_allotted = signal_times[idx - 1]
else:
signal_color = "Red" #(0, 0, 255) # Red
time_allotted = 0

# Draw black background rectangle for text


text = f'Quadrant {idx} - Vehicles: {total_vehicles} | Signal:
{signal_color} | Time Allotted: {time_allotted} sec'
text_size = [Link](text, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
[Link](combined_frame, (10 + (idx % 2) * frame_width,
frame_height * (idx // 3 + 1) - 30),
(10 + (idx % 2) * frame_width + text_size[0],
frame_height * (idx // 3 + 1)), (0, 0, 0), -1)

# Display text in white color


[Link](combined_frame, text,
(10 + (idx % 2) * frame_width, frame_height * (idx // 3 +
1) - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)

# Display the combined frame


[Link]('Multi-Window Display', combined_frame)

# Calculate average vehicle density across all quadrants


avg_vehicle_density = total_vehicles / 4

# Calculate signal times based on vehicle density


green_time, yellow_time = calculate_signal_times(avg_vehicle_density)

# Update signal times for each quadrant


signal_times = [green_time + yellow_time] * 4

# Check if the allotted time for the current signal has elapsed
elapsed_time = [Link]() - start_time
if elapsed_time >= total_time:
start_time = [Link]() # Reset start time
# Log signal times for the next cycle
print("Signal Times for Next Cycle:")
for idx, time_allotted in enumerate(signal_times, start=1):
print(f"Quadrant {idx}: Green Time: {green_time} sec, Yellow Time:
{yellow_time} sec")
print("")

# Check for user input to exit


if [Link](1) & 0xFF == ord('q'):
break

# Release video capture objects and close windows


[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

Common questions

Powered by AI

Using only four video feeds might limit the system's capacity to capture the full complexity of traffic conditions, especially in larger intersections with multiple lanes. This limitation could lead to an incomplete assessment of vehicle density, affecting signal timing efficiency. Additionally, blind spots or areas with less coverage might result in undetected traffic build-ups, challenging the system's ability to manage traffic effectively across all intersection angles .

The purpose of using a multi-window display system is to monitor multiple traffic video feeds simultaneously. This system integrates frames from four different video captures into a single window, allowing for comprehensive monitoring of different quadrants of an intersection. It enables easy comparison and analysis of traffic conditions across different areas in real time .

The vehicle detection system handles different video frame sizes by resizing all frames to a uniform dimension of (frame_width, frame_height) before they are integrated into the multi-window display. This ensures consistent processing and display, allowing for accurate vehicle detection and alignment across quadrants in the combined frame .

The system ensures continuous monitoring and updating of traffic signal information through a loop that constantly captures and processes video frames, calculates vehicle density, and updates signal times accordingly. By tracking elapsed signal times and resetting at the end of each cycle, the system maintains an adaptive cycle that matches current traffic conditions, recalibrating the timings for the subsequent cycle based on the latest density data .

Vehicle detection and counting are implemented using a pre-trained vehicle detection model loaded with cv2's CascadeClassifier. The model identifies vehicles in each video quadrant by detecting them in grayscale frames. The system counts vehicles based on their position relative to a middle line in each video frame, ensuring that vehicles are only counted when they pass a specific point .

The average vehicle density across all video quadrants is significant because it provides a unified measure of traffic conditions, allowing the system to allocate signal times dynamically across different intersection parts. By considering the average density, the system can better balance traffic flow, ensuring efficient use of green and yellow signal durations based on overall traffic levels rather than isolated observations .

The text overlay in the multi-window display system provides real-time information on vehicle counts and signal status for each quadrant. This information is displayed on rectangles drawn in black to ensure readability, showing the number of vehicles, current signal color, and time allotted. The text is written in white, using cv2.putText, to contrast against the background and enhance visibility .

The signal times algorithm might require further adjustments in scenarios of rapidly fluctuating traffic conditions, unexpected road events, or when specific traffic patterns not captured by average vehicle density analysis are observed. These factors can lead to inefficiencies in traffic flow if the system cannot adapt quickly enough, necessitating more complex algorithms or additional sensors to provide real-time responsiveness .

The system handles the completion and resetting of signal timing cycles by checking if the elapsed time for the current signal exceeds the total cycle time (total_time). If so, the start time is reset to the current time, marking the beginning of a new cycle. This ensures that signal times are recalculated based on the most recent vehicle density data, maintaining adaptability to changing traffic conditions .

The system uses a function calculate_signal_times to adjust signal times based on vehicle density. The adjustments are influenced by the density of vehicles observed: if the vehicle density is high, the system reduces the green time and increases the yellow time. This is achieved by using the calculations max(5, green_time - vehicle_density) for adjusted green time and min(10, yellow_time + vehicle_density) for adjusted yellow time .

You might also like