OpenCV--基础车道线检测

import cv2
import numpy as np

video_path = "D:\\opencv\\lane_detection.mp4"
video_capture = cv2.VideoCapture(video_path)

def roi(img, vertices):

    # 定义一个和输入图像同样大小的全黑图像mask
    mask = np.zeros_like(img)

    # 判断输入图像的通道个数
    if len(img.shape) > 2:
        channel_count = img.shape[2]
        mask_color = (255,) * channel_count
    else:
        mask_color = 255

    # print(mask.shape)
    # [vertices]中的点组成了多边形,保留多边形内部的像素点,其余区域置为黑色
    cv2.fillPoly(mask, [vertices], mask_color)
    # print(vertices)
    # print(mask.max())

    # 与操作使用掩膜保留图像感兴趣区域
    mask_image = cv2.bitwise_and(img, mask)

    return mask_image

while True:
    ret, frame = video_capture.read()
    if ret is False:
        break
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    canny_image = cv2.Canny(gray_frame, 200, 255)

    #确定感兴趣区域多边形
    left_bottom = [0, canny_image.shape[0]]
    right_bottom = [canny_image.shape[1], canny_image.shape[0]]
    apex = [canny_image.shape[1] / 2 - 50, 150]
    vertices = np.array([left_bottom, right_bottom, apex], np.int32)
    roi_image = roi(canny_image, vertices)
    #霍夫概率变换
    lines = cv2.HoughLinesP(roi_image, 1, np.pi / 180, 10, np.array([]), 30, 30)
    # print(lines.shape)
    line_image = np.copy(frame) * 0
    # lines [b,1,(x1,y1,x2,y2)]  (x1,y1)、(x2,y2) 为直线的两个端点坐标
    for line in lines:
        for x1, y1, x2, y2 in line:
            cv2.line(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)

    cv2.imshow('line_image', frame)

    if cv2.waitKey(20) == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46278903/article/details/106879541
今日推荐