C
C
import numpy as np
def region_of_interest(image):
height = image.shape[0]
width = image.shape[1]
top_y = int(height * 0.7) # Adjust this value to change the depth of ROI (30%
from bottom)
polygon = np.array([[
(0, height),
(width // 2, top_y),
(width, height)
]], np.int32)
mask = np.zeros_like(image)
cv2.fillPoly(mask, polygon, (255, 255, 255))
masked_image = cv2.bitwise_and(image, mask)
return masked_image
def detect_lanes(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
roi_edges = region_of_interest(edges)
left_lines = []
right_lines = []
def process_lines(lines):
if not lines:
return None
points = []
for x1, y1, x2, y2 in lines:
points.append([x1, y1])
points.append([x2, y2])
points = np.array(points)
if len(points) < 2:
return None
m, b = np.polyfit(points[:,1], points[:,0], 1)
x_bottom = m * height + b
x_top = m * top_y + b
x_bottom = int(np.clip(x_bottom, 0, width))
x_top = int(np.clip(x_top, 0, width))
return [(x_bottom, height), (x_top, top_y)]
left_line = process_lines(left_lines)
right_line = process_lines(right_lines)
return image
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
lane_frame = detect_lanes(frame)
output_video.write(lane_frame)
cv2.imshow('Lane Detection', lane_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
output_video.release()
cv2.destroyAllWindows()