In [1]:
import cv2
import math
import numpy as np

def grayscale(img):
    """Applies the Grayscale transform
    This will return an image with only one color channel
    but NOTE: to see the returned image as grayscale
    you should call plt.imshow(gray, cmap='gray')"""
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
def canny(img, low_threshold, high_threshold):
    """Applies the Canny transform"""
    return cv2.Canny(img, low_threshold, high_threshold)

def gaussian_blur(img, kernel_size):
    """Applies a Gaussian Noise kernel"""
    return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)

def region_of_interest(img, vertices):
    """
    Applies an image mask.
    
    Only keeps the region of the image defined by the polygon
    formed from `vertices`. The rest of the image is set to black.
    """
    #defining a blank mask to start with
    mask = np.zeros_like(img)   
    
    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255
        
    #filling pixels inside the polygon defined by "vertices" with the fill color    
    cv2.fillPoly(mask, vertices, ignore_mask_color)
    
    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image


def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
    """
    NOTE: this is the function you might want to use as a starting point once you want to 
    average/extrapolate the line segments you detect to map out the full
    extent of the lane (going from the result shown in raw-lines-example.mp4
    to that shown in P1_example.mp4).  
    
    Think about things like separating line segments by their 
    slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
    line vs. the right line.  Then, you can average the position of each of 
    the lines and extrapolate to the top and bottom of the lane.
    
    This function draws `lines` with `color` and `thickness`.    
    Lines are drawn on the image inplace (mutates the image).
    If you want to make the lines semi-transparent, think about combining
    this function with the weighted_img() function below
    """
    for line in lines:
        for x1,y1,x2,y2 in line:
            cv2.line(img, (x1, y1), (x2, y2), color, thickness)

def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
    """
    `img` should be the output of a Canny transform.
        
    Returns an image with hough lines drawn.
    """
    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
    #line_img = np.zeros(img.shape, dtype=np.uint8)
    line_img = np.zeros((*img.shape, 3), dtype=np.uint8)
    if lines is not None:
        draw_lines(line_img, lines)
    return line_img

# Python 3 has support for cool math symbols.

def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):
    """
    `img` is the output of the hough_lines(), An image with lines drawn on it.
    Should be a blank image (all black) with lines drawn on it.
    
    `initial_img` should be the image before any processing.
    
    The result image is computed as follows:
    
    initial_img * α + img * β + λ
    NOTE: initial_img and img must be the same shape!
    """
    return cv2.addWeighted(initial_img, α, img, β, λ)

In [2]:
import matplotlib.image as mpimg

In [103]:
import matplotlib.pyplot as plt
%matplotlib inline


#image = mpimg.imread('/Users/safdar/Documents/self-driving-car/behavioral-cloning/IMG/center_2016_12_04_19_08_20_203.jpg')
image = mpimg.imread('/Users/safdar/Documents/self-driving-car/behavioral-cloning/IMG/center_2016_12_04_19_09_17_571.jpg')

# Copy the image first
result = image.copy()

# Convert to grayscale
result = grayscale(result)
gray = result.copy()

# Blur the gradient:
result = gaussian_blur(result, 3)

# Canny
#result = canny(result, 75, 215)
result = canny(result, 50, 0)

# Carve out the polygonal field of view:
x_dim = np.shape(image)[1]
y_dim = np.shape(image)[0]
y_max = y_dim/3.5
y_min = y_dim - 30
#print(y_min, y_max)
bottom_left = (10,y_min)
bottom_right = (x_dim-10,y_min)
top_right = (x_dim/2+100,y_max)
top_left = (x_dim/2-100,y_max)
vertices = np.array([[bottom_left, \
                      bottom_right, \
                      top_right, \
                      top_left]], \
                    dtype = np.int32)
result = region_of_interest(result, vertices)
plt.imshow(result, 'gray')

# Extract hough lines
rho = 1
theta = np.pi/180
threshold = 10 #20
min_line_length = 10 #100 #20
max_line_gap = 50 #175
lines = cv2.HoughLinesP(result, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
empty = np.zeros((*result.shape, 3), dtype=np.uint8)

# Additional processing:
if lines is not None:
    # Buckets
    leftlanelines = []
    rightlanelines = []
    badlines = []
    leftlanerange = [-0.95, -0.35] # [-0.95, -0.50] #[-0.90, -0.55]
    rightlanerange = [0.35, 0.95] # [0.50, 0.95] #[0.55, 0.90]

    leftmetrics = [0, 0, 0]    # cumulative [slope, intercept]
    rightmetrics = [0, 0, 0]   # cumulative [slope, intercept]
    for line in lines:
        #print (line)
        # Calculate metrics and bucket:
        slope = 0
        line_rad = 0
        x_1 = line[0][0]
        x_2 = line[0][2]
        y_1 = line[0][1]
        y_2 = line[0][3]
        delta_x = float(x_2 - x_1)
        delta_y = float(y_2 - y_1)
        if not delta_x == 0:
            slope = delta_y / delta_x
            line_rad = math.tan(slope)

            # Determine quadrant
            if leftlanerange[0] <= line_rad <= leftlanerange[1]:
                leftlanelines.append(line)
            elif rightlanerange[0] <= line_rad <= rightlanerange[1]:
                rightlanelines.append(line)
            else:
                badlines.append(line)

    print ('Left lanes:', len(leftlanelines))
    print ('Right lanes:', len(rightlanelines))
    print ('Bad lanes: ', len(badlines))
    # draw
    #draw_lines(empty, lanes, [255, 0, 0], 15)
    draw_lines(empty, rightlanelines, [255, 0, 0], 2)
    draw_lines(empty, leftlanelines, [255, 0, 0], 2)

# Superimpose the processed image with the original
result = weighted_img(image, empty)

plt.imshow(empty, 'gray')
plt.figure()
plt.imshow(gray, 'gray')


Left lanes: 1
Right lanes: 3
Bad lanes:  84
Out[103]:
<matplotlib.image.AxesImage at 0x11f540908>

In [ ]: