-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlane.py
More file actions
71 lines (53 loc) · 2.16 KB
/
lane.py
File metadata and controls
71 lines (53 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import cv2
import numpy as np
def process_frame(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
height, width = edges.shape
region_vertices = [
(0, height),
(width / 2, height / 2),
(width, height)
]
roi = region_of_interest(edges, np.array([region_vertices], np.int32))
lines = cv2.HoughLinesP(roi, 1, np.pi / 180, threshold=50, minLineLength=80, maxLineGap=100)
if lines is None:
print("No lines detected")
else:
print(f"Detected {len(lines)} lines")
line_img = np.zeros_like(frame)
draw_lane_lines(line_img, lines)
final_output = cv2.addWeighted(frame, 0.6, line_img, 1.5, 0)
return final_output
# Define the region of interest
def region_of_interest(img, vertices):
mask = np.zeros_like(img)
cv2.fillPoly(mask, vertices, 255)
return cv2.bitwise_and(img, mask)
# Draw the detected lane lines
def draw_lane_lines(img, lines, color=(0, 0, 255), thickness=10):
left_points = []
right_points = []
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
slope = (y2 - y1) / (x2 - x1) if x2 - x1 != 0 else float('inf')
if slope < -0.5:
left_points.extend([(x1, y1), (x2, y2)])
elif slope > 0.5:
right_points.extend([(x1, y1), (x2, y2)])
draw_long_line(img, left_points, color, thickness)
draw_long_line(img, right_points, color, thickness)
# Fit and draw a long line through points
def draw_long_line(img, points, color, thickness):
if len(points) > 0:
x_coords, y_coords = zip(*points)
poly_fit = np.polyfit(y_coords, x_coords, deg=1)
slope, intercept = poly_fit
height = img.shape[0]
start_y = height
end_y = int(height * 0.6)
start_x = max(0, min(int(slope * start_y + intercept), img.shape[1]))
end_x = max(0, min(int(slope * end_y + intercept), img.shape[1]))
cv2.line(img, (start_x, start_y), (end_x, end_y), color, thickness)