python opencv 车道线检测图片---and---视频

在这里插入图片描述

import cv2
import numpy as np

# 步骤1:边缘检测
def canyEdgeDetector(image):
    edged = cv2.Canny(image, 50, 150)
    return edged


# 步骤2:定义ROI(感兴趣区域)
def getROI(image):
    height = image.shape[0]
    width = image.shape[1]
    # Defining Triangular ROI: The values will change as per your camera mounts
    triangle = np.array([[(100, height), (width, height), (width-300, int(height/1.9))]])
    # creating black image same as that of input image


    black_image = np.zeros_like(image)
    # Put the Triangular shape on top of our Black image to create a mask
    mask = cv2.fillPoly(black_image, triangle, 255)
    # applying mask on original image
    masked_image = cv2.bitwise_and(image, mask)
    return masked_image


# 步骤3:获取图像中的所有直线
def getLines(image):
    # lines=cv2.HoughLinesP(image,bin_size,precision,threshold,dummy 2d array--no use,minLineLength,maxLineGap)
    # lets take bin size to be 2 pixels
    # lets take precision to be 1 degree= pi/180 radians
    # threshold is the votes that a bin should have to be accepted to draw a line
    # minLineLength --the minimum length in pixels a line should have to be accepted.
    # maxLineGap --the max gap between 2 broken line which we allow for 2 lines to be connected together.
    lines = cv2.HoughLinesP(image, 1, np.pi / 180, 100, np.array([]), minLineLength=70, maxLineGap=20)
    #lines = cv2.HoughLinesP(image, 1, np.pi / 180, 100, 10, 100)
    return lines


#display lines over a image
def displayLines(image, lines):
    if lines is not None:
        for line in lines:
            # print(line) --output like [[704 418 927 641]] this is 2d array representing [[x1,y1,x2,y2]] for each line
            x1, y1, x2, y2 = line.reshape(4)  # converting to 1d array []

            # draw line over black image --(255,0,0) tells we want to draw blue line (b,g,r) values 10 is line thickness
            cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 10)
    return image



def getLineCoordinatesFromParameters(image, line_parameters):
    slope = line_parameters[0]
    intercept = line_parameters[1]
    y1 = image.shape[0]  # since line will always start from bottom of image
    y2 = int(y1 * (3.4 / 5))  # some random point at 3/5
    x1 = int((y1 - intercept) / slope)
    x2 = int((y2 - intercept) / slope)
    return np.array([x1, y1, x2, y2])



#Avergaes all the left and right lines found for a lane and retuns single left and right line for the the lane
def getSmoothLines(image, lines):
    left_fit = []  # will hold m,c parameters for left side lines
    right_fit = []  # will hold m,c parameters for right side lines

    for line in lines:
        x1, y1, x2, y2 = line.reshape(4)
        # polyfit gives slope(m) and intercept(c) values from input points
        # last parameter 1 is for linear..so it will give linear parameters m,c
        parameters = np.polyfit((x1, x2), (y1, y2), 1)
        slope = parameters[0]
        intercept = parameters[1]

        if slope < 0:
            left_fit.append((slope, intercept))
        else:
            right_fit.append((slope, intercept))

    # take averages of all intercepts and slopes separately and get 1 single value for slope,intercept
    # axis=0 means vertically...see its always (row,column)...so row is always 0 position.
    # so axis 0 means over row(vertically)
    left_fit_average = np.average(left_fit, axis=0)
    right_fit_average = np.average(right_fit, axis=0)

    # now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters
    left_line = getLineCoordinatesFromParameters(image, left_fit_average)
    right_line = getLineCoordinatesFromParameters(image, right_fit_average)
    return np.array([left_line, right_line])



def show_image(name, image):
    cv2.imshow(name, image)
    # cv2.waitKey(0)



image = cv2.imread("lane.jpg") #Load Image
print(image.shape)
show_image('image', image)

edged_image = canyEdgeDetector(image)   # Step 1
print(edged_image.shape)
show_image('edged_image', edged_image)

roi_image = getROI(edged_image)         # Step 2
print(roi_image.shape)
show_image('roi_image', roi_image)

lines = getLines(roi_image)             # Step 3
print(lines)
#image_with_lines = displayLines(image, lines)


smooth_lines = getSmoothLines(image, lines)    # Step 5
print(smooth_lines)
image_with_smooth_lines = displayLines(image, smooth_lines) # Step 4

cv2.imshow("Output", image_with_smooth_lines)
cv2.waitKey(0)


在这里插入图片描述
在这里插入图片描述

import cv2
import numpy as np

def canyEdgeDetector(image):
    edged = cv2.Canny(image, 50, 150)
    return edged


def getROI(image):
    height = image.shape[0]
    width = image.shape[1]
    print(height, width)  # 720 1280
    # Defining Triangular ROI: The values will change as per your camera mounts
    triangle=np.array([[(200, height), (1100, height), (550, 250)]])
    # creating black image same as that of input image
    black_image = np.zeros_like(image)
    # Put the Triangular shape on top of our Black image to create a mask
    mask = cv2.fillPoly(black_image, triangle, 255)
    # applying mask on original image
    masked_image = cv2.bitwise_and(image, mask)
    return masked_image



def getLines(image):
    # lines=cv2.HoughLinesP(image,bin_size,precision,threshold,dummy 2d array--no use,minLineLength,maxLineGap)
    # lets take bin size to be 2 pixels
    # lets take precision to be 1 degree= pi/180 radians
    # threshold is the votes that a bin should have to be accepted to draw a line
    # minLineLength --the minimum length in pixels a line should have to be accepted.
    # maxLineGap --the max gap between 2 broken line which we allow for 2 lines to be connected together.
    lines = cv2.HoughLinesP(image, 2, np.pi / 180, 100, np.array([]), minLineLength=40, maxLineGap=5)
    return lines


#display lines over a image
def displayLines(image, lines):
    if lines is not None:
        for line in lines:
            # print(line) --output like [[704 418 927 641]] this is 2d array representing [[x1,y1,x2,y2]] for each line
            x1, y1, x2, y2 = line.reshape(4)  # converting to 1d array []

            # draw line over black image --(255,0,0) tells we want to draw blue line (b,g,r) values 10 is line thickness
            cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 10)
    return image



def getLineCoordinatesFromParameters(image, line_parameters):
    slope = line_parameters[0]
    intercept = line_parameters[1]
    y1 = image.shape[0]  # since line will always start from bottom of image
    y2 = int(y1 * (3.4 / 5))  # some random point at 3/5
    x1 = int((y1 - intercept) / slope)
    x2 = int((y2 - intercept) / slope)
    return np.array([x1, y1, x2, y2])



#Avergaes all the left and right lines found for a lane and retuns single left and right line for the the lane
def getSmoothLines(image, lines):
    left_fit = []  # will hold m,c parameters for left side lines
    right_fit = []  # will hold m,c parameters for right side lines

    for line in lines:
        x1, y1, x2, y2 = line.reshape(4)
        # polyfit gives slope(m) and intercept(c) values from input points
        # last parameter 1 is for linear..so it will give linear parameters m,c
        parameters = np.polyfit((x1, x2), (y1, y2), 1)
        slope = parameters[0]
        intercept = parameters[1]

        if slope < 0:
            left_fit.append((slope, intercept))
        else:
            right_fit.append((slope, intercept))

    # take averages of all intercepts and slopes separately and get 1 single value for slope,intercept
    # axis=0 means vertically...see its always (row,column)...so row is always 0 position.
    # so axis 0 means over row(vertically)
    left_fit_average = np.average(left_fit, axis=0)
    right_fit_average = np.average(right_fit, axis=0)

    # now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters
    left_line = getLineCoordinatesFromParameters(image, left_fit_average)
    right_line = getLineCoordinatesFromParameters(image, right_fit_average)
    return np.array([left_line, right_line])






videoFeed = cv2.VideoCapture("test_video.mp4")

try:
  while videoFeed.isOpened() :
    (status, image) = videoFeed.read()

    edged_image = canyEdgeDetector(image)   # Step 1
    roi_image = getROI(edged_image)         # Step 2

    lines = getLines(roi_image)             # Step 3
    #image_with_lines = displayLines(image, lines)

    smooth_lines = getSmoothLines(image, lines)    # Step 5
    image_with_smooth_lines = displayLines(image, smooth_lines) # Step 4

    cv2.imshow("Output", image_with_smooth_lines)
    cv2.waitKey(1)

except:
    pass

在这里插入图片描述

以下是基于OpenCV传统数字图像处理实现车道线检测Python代码示例: ```python import cv2 import numpy as np def lane_detection(image): # 将图像转换为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 对图像进行高斯平滑去噪 blurred = cv2.GaussianBlur(gray, (5, 5), 0) # 使用Canny算法进行边缘提取 edges = cv2.Canny(blurred, 50, 150) # 定义ROI(感兴趣区域)的顶点坐标 height, width = edges.shape roi_vertices = [(0, height), (width/2, height/2), (width, height)] # 创建一个掩膜,将ROI以外的区域屏蔽掉 mask = np.zeros_like(edges) cv2.fillPoly(mask, np.array([roi_vertices], np.int32), 255) masked_edges = cv2.bitwise_and(edges, mask) # 使用霍夫变换检测直线 lines = cv2.HoughLinesP(masked_edges, 1, np.pi/180, threshold=50, minLineLength=100, maxLineGap=50) # 在原始图像上绘制检测到的车道线 line_image = np.zeros_like(image) if lines is not None: for line in lines: x1, y1, x2, y2 = line[0] cv2.line(line_image, (x1, y1), (x2, y2), (0, 0, 255), 3) # 将车道线图像与原始图像进行叠加 result = cv2.addWeighted(image, 0.8, line_image, 1, 0) return result # 读取图像 image = cv2.imread('road.jpg') # 进行车道线检测 result = lane_detection(image) # 显示结果图像 cv2.imshow('Lane Detection', result) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段代码实现了基于OpenCV的传统数字图像处理方法进行车道线检测。首先,将图像转换为灰度图,然后使用高斯平滑对图像进行去噪,接着使用Canny算法进行边缘提取。然后,定义感兴趣区域(ROI)并创建一个掩膜,将ROI以外的区域屏蔽掉。最后,使用霍夫变换检测直线,并在原始图像上绘制检测到的车道线。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值