import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def canny(image):
gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY);
blur = cv.GaussianBlur(gray,(5,5),0)
canny= cv.Canny(blur,50,100)
return canny
def roi(image):
height = image.shape[0]
polygons = np.array([[(200,height),(1100,height),(550,250)]])
mask = np.zeros_like(image);
cv.fillPoly(mask,polygons,255)
masked_image = cv.bitwise_and(image,mask)
return masked_image
def display_lines(image,lines):
line_image = np.zeros_like(image);
for line in lines:
x1,y1,x2,y2 = line.reshape(4)
cv.line(line_image,(x1,y1),(x2,y2),(255,255,0),10);
return line_image
def make_coordinates(image,parameters):
slope = parameters[0]
intercept = parameters[1]
y1 = image.shape[0]
y2 = int(y1*0.6)
x1 = int((y1 - intercept)/slope)
x2 = int((y2 - intercept)/slope)
return np.array([x1,y1,x2,y2])
def average_slop_intercept(image,lines):
left_fit = []
right_fit = []
print(lines)
for line in lines:
x1, y1, x2, y2 = line.reshape(4)
print(x1,y1,x2,y2)
parameters = np.polyfit((x1,x2),(y1,y2),1)
print(parameters)
slope = parameters[0]
intercept = parameters[1]
if slope > 0 :
left_fit.append((slope,intercept))
else:
right_fit.append((slope,intercept))
#yong
result_lines = []
if len(left_fit):
left_fit_average = np.average(left_fit, axis=0)
left_line = make_coordinates(image,left_fit_average)
result_lines.append(left_line)
if len(right_fit)>0:
right_fit_average = np.average(right_fit, axis=0)
right_line = make_coordinates(image,right_fit_average)
result_lines.append(right_line)
return result_lines
cv.namedWindow("result",cv.WINDOW_NORMAL)
capture = cv.VideoCapture()
capture.open("test2.mp4")
if capture.isOpened():
flag = True
while flag:
flag,image = capture.read();
if not flag: break
# image = cv.imread("test_image.jpg")
lane_image = image # np.copy(image);
print(lane_image.shape)
canny_image = canny(lane_image)
cropped_image = roi(canny_image)
lines = cv.HoughLinesP(cropped_image,2,np.pi/180,100,minLineLength=40,maxLineGap=5)
average_lines = average_slop_intercept(image,lines)
lines_image = display_lines(lane_image,average_lines)
combo_image = cv.addWeighted(lane_image,0.8,lines_image,1,1)
cv.imshow("result",combo_image)
cv.waitKey(10)
cv.waitKey(0)
cv.destroyAllWindows()