+
105
-

回答

具体代码如下:

import cv2
import numpy as np

def detect_lanes(frame):
    """检测车道线"""
    # 转换为灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 高斯模糊
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    # Canny边缘检测
    edges = cv2.Canny(blur, 50, 150)
    # 定义感兴趣区域
    height, width = frame.shape[:2]
    roi_vertices = np.array([[(0, height), (width/2, height/1.5), (width, height)]], dtype=np.int32)
    mask = np.zeros_like(edges)
    cv2.fillPoly(mask, roi_vertices, 255)
    masked_edges = cv2.bitwise_and(edges, mask)
    # 霍夫变换检测直线
    lines = cv2.HoughLinesP(masked_edges, 1, np.pi/180, 50, minLineLength=100, maxLineGap=50)
    return lines

def draw_lanes(frame, lines):
    """绘制车道线"""
    line_image = np.zeros_like(frame)
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(line_image, (x1, y1), (x2, y2), (0, 255, 0), 5)
    return line_image

def main():
    try:
        # 打开视频文件
        video_path = "road.mp4"  # 替换为实际视频路径
        cap = cv2.VideoCapture(video_path)
        
        if not cap.isOpened():
            raise Exception("无法打开视频文件")

        # 获取视频属性
        frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = int(cap.get(cv2.CAP_PROP_FPS))

        # 创建视频写入器
        out = cv2.VideoWriter('output.mp4', 
                            cv2.VideoWriter_fourcc(*'mp4v'), 
                            fps, 
                            (frame_width, frame_height))

        # 创建显示窗口
        cv2.namedWindow('Lane Detection', cv2.WINDOW_NORMAL)

        while True:
            ret, frame = cap.read()
            if not ret:
                break

            # 检测和绘制车道线
            lines = detect_lanes(frame)
            line_image = draw_lanes(frame, lines)
            result = cv2.addWeighted(frame, 0.8, line_image, 1, 0)

            # 保存处理后的帧
            out.write(result)
            
            # 显示结果
            cv2.imshow('Lane Detection', result)
            
            # 按q键退出
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

    except Exception as e:
        print(f"发生错误: {str(e)}")
    
    finally:
        if 'cap' in locals():
            cap.release()
        if 'out' in locals():
            out.release()
        cv2.destroyAllWindows()
        cv2.waitKey(1)

if __name__ == '__main__':
    main()

网友回复

我知道答案,我要回答