使用YOLOv8(You Only Look Once)和OpenCV实现车道线和车辆检测,目标是创建一个可以检测道路上的车道并识别车辆的系统,并估计它们与摄像头的距离。该项目结合了计算机视觉技术和深度学习物体检测。
1、系统主要功能
- 车道检测:使用边缘检测和霍夫线变换检测道路车道。
- 汽车检测:使用 YOLOv8 模型识别汽车并在汽车周围绘制边界框。
- 距离估计:使用边界框大小计算检测到的汽车与摄像头的距离。
2、环境要求
- OpenCV:用于图像处理和车道检测。
- Ultralytics YOLOv8:用于车辆检测。
- NumPy:用于数组操作。
pip install opencv-python-headless numpy ultralytics
opencv-python
和 opencv-python-headless
区别是 OpenCV 的 Python 包,主要区别在于是否包含 GUI 相关的功能。
opencv-python
- 包含 GUI 功能:支持窗口显示、鼠标事件等图形界面操作。
- 依赖:需要 GUI 库(如 GTK、Qt)支持。
- 适用场景:适用于需要显示图像或与用户交互的环境,如桌面应用。
opencv-python-headless
- 不包含 GUI 功能:去除了窗口显示和用户交互功能。
- 依赖:无需 GUI 库,适合无图形界面的环境。
- 适用场景:适用于服务器或无图形界面的环境,如远程服务器、Docker 容器。
选择建议
- 如果需要显示图像或与用户交互,选择
opencv-python
。 - 如果仅需图像处理且无图形界面需求,选择
opencv-python-headless
。
3、代码
import cv2
import numpy as np
import math
import time
from ultralytics import YOLO # YOLOv8 module
# Function to mask out the region of interest
def region_of_interest(img, vertices):
mask = np.zeros_like(img)
match_mask_color = 255
cv2.fillPoly(mask, vertices, match_mask_color)
masked_image = cv2.bitwise_and(img, mask)
return masked_image
# Function to draw the filled polygon between the lane lines
def draw_lane_lines(img, left_line, right_line, color=[0, 255, 0], thickness=10):
line_img = np.zeros_like(img)
poly_pts = np.array([[
(left_line[0], left_line[1]),
(left_line[2], left_line[3]),
(right_line[2], right_line[3]),
(right_line[0], right_line[1])
]], dtype=np.int32)
# Fill the polygon between the lines
cv2.fillPoly(line_img, poly_pts, color)
# Overlay the polygon onto the original image
img = cv2.addWeighted(img, 0.8, line_img, 0.5, 0.0)
return img
# The lane detection pipeline
def pipeline(image):
height = image.shape[0]
width = image.shape[1]
region_of_interest_vertices = [
(0, height),
(width / 2, height / 2),
(width, height),
]
# Convert to grayscale and apply Canny edge detection
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
cannyed_image = cv2.Cann