Challenge

Project 4

import cv2
import numpy as np 
import matplotlib.pyplot as plt 

def gray_scale(image):
    gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    return gray_img

def read_img (image_path):
    img = cv2.imread(image_path) #reads in bgr fromat 
    return img

def disp_img (img_window,read_img):
    image = cv2.imshow(img_window,read_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def gaussian_filter(image,filter_size,sd_sigma):
    filtered_image = cv2.GaussianBlur(image,(filter_size,filter_size),sd_sigma)

    return filtered_image


def canny_edge(image, low_thersh, up_thersh):
    canny_img = cv2.Canny(image, low_thersh, up_thersh)

    return canny_img


def roi(image):
    height = image.shape[0]
    width = image.shape[1]
    roi_vert =np.array([[
        (0, height),
        (round(width/2.1), round(height/2.1)),
        (1000, height)
    ]])  
    image = np.array(image, dtype=np.float32)
    mask = np.zeros_like(image)
    masked_image = cv2.fillPoly(mask, roi_vert, 255)
    #masked_image = np.array(masked_image, dtype='uint8')
    masked_image = cv2.bitwise_and(image, masked_image)
    masked_image = cv2.normalize(masked_image, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)

    return masked_image

def houghP(image):
    lines = cv2.HoughLinesP(image,rho=2,theta=np.pi / 
           180,threshold=100,lines=np.array([]),minLineLength=50,maxLineGap=50)    
    return lines

def get_coordinates (image, params):
     
    slope, intercept = params 
    if slope < 0:
        y1 = image.shape[0]     
        y2 = int(y1 * (3/5)) # Setting y2 at 3/5th from y1
        x1 = int((y1 - intercept) / slope) # Deriving from y = mx + c
        x2 = int((y2 - intercept) / slope)
    else:
        y1 = image.shape[0]     
        y2 = int(y1 * (3/5)) # Setting y2 at 3/5th from y1
        x1 = int((y1 - intercept) / slope*0.95) # Deriving from y = mx + c
        x2 = int((y2 - intercept) / slope)
         
    
    return np.array([x1, y1, x2, y2])


def avg_lines(image, lines): 
    
    left = [] 
    right = [] 
    
    for line in lines: 
        x1, y1, x2, y2 = line.reshape(4)
          
        # Fit polynomial, find intercept and slope 
        params = np.polyfit((x1, x2), (y1, y2), 1)  
        slope = params[0] 
        y_intercept = params[1] 
        
        if slope < 0: 
            left.append((slope, y_intercept)) #Negative slope indicates left lane
        else: 
            right.append((slope, y_intercept)) #Positive slope indicates right lane
    
    # Avg over all values for a single slope and y-intercept value for each line
    
    left_avg = np.average(left, axis = 0) 
    right_avg = np.average(right, axis = 0) 
    
    # Find coordinates for left & right lines
    left_line = get_coordinates(image, left_avg) 
    right_line = get_coordinates(image, right_avg)
    
    return np.array([left_line, right_line])

# Draws lines of given thickness over an image
def draw_lines(image, lines, thickness): 
   
    #print(lines)
    line_image = np.zeros_like(image)
    color=[50, 0, 255]
    
    if lines is not None: 
        for x1, y1, x2, y2 in lines:
                    cv2.line(line_image, (x1, y1), (x2, y2), color, thickness)

            
    # Merge the image with drawn lines onto the original.
    combined_image = cv2.addWeighted(image, 0.8, line_image, 1.0, 0.0)
    
    return combined_image

#The below code excutes the lane detection task 
vid = cv2.VideoCapture('Lane_video.mp4')

while True:
    ret, frame = vid.read()
    gray = gray_scale(frame)
    gaussian = gaussian_filter(gray ,3 ,2)
    canny = canny_edge(gaussian, 100, 120)
    #print(canny.shape)
    roi_frame = roi(canny)
    
    #print(roi_frame.dtype)
    hough = houghP(roi_frame)

    averaged_lines = avg_lines (frame, hough)
    
    combined_image = draw_lines(frame, averaged_lines, 5)
    
    if not ret:
        vid = cv2.VideoCapture('Lane_video.mp4')
        continue

    cv2.imshow('frame',frame)
    #cv2.imshow('canny',canny)
    #cv2.imshow('roi',roi_frame)

    cv2.imshow('combined_img',combined_image)
    #print(hough)
    #print(avg_lines)
    if cv2.waitKey(25) & 0xFF == ord('q'):
            break

vid.release()
cv2.destroyAllWindows()
Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.