给我一份opencv车道线检测代码
时间: 2023-06-03 12:04:07 浏览: 213
好的,请稍等,以下是车道线检测的代码:
```python
import cv2
import numpy as np
def image_processing(img):
# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur to the grayscale image
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Apply Canny edge detection to the blurred image
edges = cv2.Canny(blur, 50, 150)
# Create a masked edges image using cv2.fillPoly()
mask = np.zeros_like(edges)
ignore_mask_color = 255
imshape = img.shape
vertices = np.array([[(0,imshape[0]),(450, 290), (490, 290), (imshape[1],imshape[0])]], dtype=np.int32)
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges, mask)
# Define the Hough transform parameters
rho = 2 # Distance resolution in pixels of the Hough grid
theta = np.pi/180 # Angular resolution in radians of the Hough grid
threshold = 40 # Minimum number of votes (intersections in Hough grid cell)
min_line_length = 50 # Minimum number of pixels making up a line
max_line_gap = 150 # Maximum gap in pixels between connectable line segments
# Apply Hough transform to the masked edges image
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),
min_line_length, max_line_gap)
# Create a blank image with the same dimensions as the original image
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
# Draw detected lines onto the blank image
draw_lines(line_img, lines)
# Combine the original image with the line image
result = cv2.addWeighted(img, 0.8, line_img, 1, 0)
return result
def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
"""
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
"""
# Define variables to store the averaged slopes and intercepts of the left and right lane lines
left_slope = []
left_intercept = []
right_slope = []
right_intercept = []
# Iterate over the detected lines
for line in lines:
for x1,y1,x2,y2 in line:
# Calculate the slope and intercept of the line
slope, intercept = np.polyfit((x1, x2), (y1, y2), 1)
# Skip lines with slopes that are too steep or not steep enough
if abs(slope) < 0.5 or abs(slope) > 2:
continue
# Classify the line as left lane line or right lane line based on the slope and position of the line's midpoint
midpoint_x = (x1 + x2) / 2
img_center_x = img.shape[1] / 2
if slope < 0 and midpoint_x < img_center_x:
left_slope.append(slope)
left_intercept.append(intercept)
elif slope > 0 and midpoint_x > img_center_x:
right_slope.append(slope)
right_intercept.append(intercept)
# Calculate the average slope and intercept for the left lane line and right lane line
if left_slope and left_intercept:
left_slope_avg = sum(left_slope) / len(left_slope)
left_intercept_avg = sum(left_intercept) / len(left_intercept)
else:
left_slope_avg = None
left_intercept_avg = None
if right_slope and right_intercept:
right_slope_avg = sum(right_slope) / len(right_slope)
right_intercept_avg = sum(right_intercept) / len(right_intercept)
else:
right_slope_avg = None
right_intercept_avg = None
# Define the top and bottom y-coordinates of the lane lines
y1 = img.shape[0]
y2 = int(y1 * 0.6)
# Draw the left lane line
if left_slope_avg is not None:
x1 = int((y1 - left_intercept_avg) / left_slope_avg)
x2 = int((y2 - left_intercept_avg) / left_slope_avg)
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
# Draw the right lane line
if right_slope_avg is not None:
x1 = int((y1 - right_intercept_avg) / right_slope_avg)
x2 = int((y2 - right_intercept_avg) / right_slope_avg)
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
if __name__ == '__main__':
# Load the test image
img = cv2.imread('test.jpg')
# Apply the image processing pipeline to the test image
result = image_processing(img)
# Show the result
cv2.imshow('Result', result)
cv2.waitKey()
cv2.destroyAllWindows()
```
注意:此代码仅做演示用途,并不一定适用于所有情况。具体应用时需要根据实际需求进行修改调整。
阅读全文