# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [conda env:carnd-term1]
#     language: python
#     name: conda-env-carnd-term1-py
# ---

import numpy as np
import cv2
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg
# %matplotlib inline
from pprint import pprint
import glob
count=0


# +

def calibrate_camera(images_path,nx=9,ny=6):
    objpoints=[]
    imgpoints=[]
    # x=objp[:,:2]
    objp=np.zeros((ny*nx,3),np.float32)
    objp[:,:2]=np.mgrid[0:nx,0:ny].T.reshape(-1,2)
    for image in images_path:
        img=mpimg.imread(image)
        gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        ret,corners=cv2.findChessboardCorners(gray,(nx,ny),None)
        if ret==True:
            imgpoints.append(corners)
            objpoints.append(objp)
            cr_image=cv2.drawChessboardCorners(img,(nx,ny),corners,ret)
            filename=image.split('\\')[-1]
#             print(filename)
            cv2.imwrite('output_corner/'+filename+'.jpg',img)
    return imgpoints,objpoints

def abs_sobel_thresh(img, orient='x',sobel_kernel=3, thresh=(0,255)):
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # Apply x or y gradient with the OpenCV Sobel() function
    # and take the absolute value
    if orient == 'x':
        abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0,sobel_kernel))
    if orient == 'y':
        abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1,sobel_kernel))
    # Rescale back to 8 bit integer
    scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
    # Create a copy and apply the threshold
    binary_output = np.zeros_like(scaled_sobel)
    # Here I'm using inclusive (>=, <=) thresholds, but exclusive is ok too
    binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1

    # Return the result
    return binary_output

def mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # Take both Sobel x and y gradients
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    # Calculate the gradient magnitude
    gradmag = np.sqrt(sobelx**2 + sobely**2)
    # Rescale to 8 bit
    scale_factor = np.max(gradmag)/255 
    gradmag = (gradmag/scale_factor).astype(np.uint8) 
    # Create a binary image of ones where threshold is met, zeros otherwise
    binary_output = np.zeros_like(gradmag)
    binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1

    # Return the binary image
    return binary_output


def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):
    # Grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # Calculate the x and y gradients
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    # Take the absolute value of the gradient direction, 
    # apply a threshold, and create a binary image result
    absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))
    binary_output =  np.zeros_like(absgraddir)
    binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1

    # Return the binary image
    return binary_output

def binary_saturation(image,thresh=(90,255)):
    hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
    S = hls[:,:,2]
    s_binary = np.zeros_like(S)
    s_binary[(S > thresh[0]) & (S <= thresh[1])] = 1
    return s_binary

def getperspective(img,src,dst):
    img_size=(img.shape[1],img.shape[0])
    M = cv2.getPerspectiveTransform(src, dst)
    warped = cv2.warpPerspective(img, M, img_size)
    return warped

def combined_threshold(test_image):
    ksize=3
    gradx = abs_sobel_thresh(test_image, orient='x', sobel_kernel=ksize, thresh=(20, 100))
    grady = abs_sobel_thresh(test_image, orient='y', sobel_kernel=ksize, thresh=(30, 100))
    mag_binary = mag_thresh(test_image, sobel_kernel=ksize, mag_thresh=(30, 100))
    dir_binary = dir_threshold(test_image, sobel_kernel=ksize, thresh=(0.7, 1.3))
    combined = np.zeros_like(dir_binary)
    combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1
    return combined
def findlines(binary_warped): 
    histogram = np.sum(binary_warped[int(binary_warped.shape[0]/2):,:], axis=0)
    # Create an output image to draw on and  visualize the result
    out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255
    # Find the peak of the left and right halves of the histogram
    # These will be the starting point for the left and right lines
    midpoint = np.int(histogram.shape[0]/2)
    leftx_base = np.argmax(histogram[:midpoint])
    rightx_base = np.argmax(histogram[midpoint:]) + midpoint

    # Choose the number of sliding windows
    nwindows = 15
    # Set height of windows
    window_height = np.int(binary_warped.shape[0]/nwindows)
    # Identify the x and y positions of all nonzero pixels in the image
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])
    nonzerox = np.array(nonzero[1])
    # Current positions to be updated for each window
    leftx_current = leftx_base
    rightx_current = rightx_base
    # Set the width of the windows +/- margin
    margin = 100
    # Set minimum number of pixels found to recenter window
    minpix = 50
    # Create empty lists to receive left and right lane pixel indices
    left_lane_inds = []
    right_lane_inds = []

    # Step through the windows one by one
    for window in range(nwindows):
        # Identify window boundaries in x and y (and right and left)
        win_y_low = binary_warped.shape[0] - (window+1)*window_height
        win_y_high = binary_warped.shape[0] - window*window_height
        win_xleft_low = leftx_current - margin
        win_xleft_high = leftx_current + margin
        win_xright_low = rightx_current - margin
        win_xright_high = rightx_current + margin
        # Draw the windows on the visualization image
        cv2.rectangle(out_img,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),
        (0,255,0), 2) 
        cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),
        (0,255,0), 2) 
        # Identify the nonzero pixels in x and y within the window
        good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & 
        (nonzerox >= win_xleft_low) &  (nonzerox < win_xleft_high)).nonzero()[0]
        good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & 
        (nonzerox >= win_xright_low) &  (nonzerox < win_xright_high)).nonzero()[0]
        # Append these indices to the lists
        left_lane_inds.append(good_left_inds)
        right_lane_inds.append(good_right_inds)
        # If you found > minpix pixels, recenter next window on their mean position
        if len(good_left_inds) > minpix:
            leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
        if len(good_right_inds) > minpix:        
            rightx_current = np.int(np.mean(nonzerox[good_right_inds]))

    # Concatenate the arrays of indices
    left_lane_inds = np.concatenate(left_lane_inds)
    right_lane_inds = np.concatenate(right_lane_inds)

    # Extract left and right line pixel positions
    leftx = nonzerox[left_lane_inds]
    lefty = nonzeroy[left_lane_inds] 
    rightx = nonzerox[right_lane_inds]
    righty = nonzeroy[right_lane_inds] 

    # Fit a second order polynomial to each
    left_fit = np.polyfit(lefty, leftx, 2)
    right_fit = np.polyfit(righty, rightx, 2)
    ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )
    left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
    right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]

    ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )
    left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
    right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
    out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
    out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
    
    return out_img,left_fitx,right_fitx,left_fit,right_fit,ploty

def search_area(binary_warped,left_fitx,right_fitx,left_fit,right_fit):   
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])
    nonzerox = np.array(nonzero[1])

    margin = 100
    left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + 
    left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) + 
    left_fit[1]*nonzeroy + left_fit[2] + margin))) 

    right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + 
    right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) + 
    right_fit[1]*nonzeroy + right_fit[2] + margin)))  

    # Again, extract left and right line pixel positions
    leftx = nonzerox[left_lane_inds]
#     print(leftx.shape)
    lefty = nonzeroy[left_lane_inds] 
    rightx = nonzerox[right_lane_inds]
    righty = nonzeroy[right_lane_inds]
    # Fit a second order polynomial to each
    left_fit = np.polyfit(lefty, leftx, 2)
    right_fit = np.polyfit(righty, rightx, 2)
    # Generate x and y values for plotting
    ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )
    left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
    right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
    
    
    out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255
    window_img = np.zeros_like(out_img)
    # Color in left and right line pixels
    out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
    out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]

    # Generate a polygon to illustrate the search window area
    # And recast the x and y points into usable format for cv2.fillPoly()
    left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])
    left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, 
                                  ploty])))])
    left_line_pts = np.hstack((left_line_window1, left_line_window2))
    right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])
    right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, 
                                  ploty])))])
    right_line_pts = np.hstack((right_line_window1, right_line_window2))

    # Draw the lane onto the warped blank image
    cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))
    cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))
    result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)
#     plt.imshow(result)
#     print(result.shape)
#     plt.plot(left_fitx, ploty, color='yellow')
#     plt.plot(right_fitx, ploty, color='yellow')
#     plt.xlim(0, 1280)
#     plt.ylim(720, 0)
    return result

def curvature_plot(left_fitx,right_fitx,ploty):  
    left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
    # right_fit = np.polyfit(ploty, rightx, 2)
    right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]

    # Plot up the fake data
    mark_size = 3
    # plt.plot(leftx, ploty, 'o', color='red', markersize=mark_size)
    # plt.plot(rightx, ploty, 'o', color='blue', markersize=mark_size)
    plt.xlim(0, 1280)
    plt.ylim(0, 720)
    plt.plot(left_fitx, ploty, color='green', linewidth=3)
    plt.plot(right_fitx, ploty, color='green', linewidth=3)
    plt.gca().invert_yaxis() # to visualize as we do the images

def measure_cur_pix(left_fit,right_fit,ploty,left_fitx,right_fitx): 
    y_eval = np.max(ploty)
    left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0])
    right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0])
#     print(left_curverad, right_curverad)
    ym_per_pix = 30/720 # meters per pixel in y dimension
    xm_per_pix = 3.7/700 # meters per pixel in x dimension

    # Fit new polynomials to x,y in world space
    left_fit_cr = np.polyfit(ploty*ym_per_pix, left_fitx*xm_per_pix, 2)
    right_fit_cr = np.polyfit(ploty*ym_per_pix, right_fitx*xm_per_pix, 2)
    # Calculate the new radii of curvature
    left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])
    right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])
    return left_curverad, right_curverad

def draw_lane(test_image,binary_warped,left_fitx,right_fitx,ploty,Minv):

    warp_zero = np.zeros_like(binary_warped).astype(np.uint8)
    color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
#     print(binary_warped.shape)
    # Recast the x and y points into usable format for cv2.fillPoly()
    pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
    pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
    pts = np.hstack((pts_left, pts_right))

    # Draw the lane onto the warped blank image
    cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))

    # Warp the blank back to original image space using inverse perspective matrix (Minv)
    newwarp = cv2.warpPerspective(color_warp, Minv, (test_image.shape[1], test_image.shape[0])) 
    # Combine the result with the original image
    result1 = cv2.addWeighted(test_image, 1, newwarp, 0.3, 0)
    return result1
# -





# +
images_path=glob.glob('camera_cal/calibration*.jpg')
imgpoints,objpoints=calibrate_camera(images_path)
img121=mpimg.imread(images_path[0])
gray121 = cv2.cvtColor(img121, cv2.COLOR_RGB2GRAY)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray121.shape[::-1], None, None)
right_gl=None
def mypipeline(orig_img,test='n'):
    global count
    global right_gl
    count+=1;
    filepath="frames/frame"+str(count);
    cv2.imwrite(filepath+'.jpg',orig_img)
    test_image = cv2.undistort(orig_img, mtx, dist, None, mtx)
    combined_img=combined_threshold(test_image)
    sat_img=binary_saturation(test_image)
    combined_binary = np.zeros_like(combined_img)
    combined_binary[(combined_img == 1) | (sat_img == 1)] = 1
    src = np.float32([[570,480],[770,480],[1100,690],[290,690]])
    dst = np.float32([[250,0], [1090,0],[1090,700],[250,700]])
    binary_warped=getperspective(combined_binary,src,dst)
    histogram = np.sum(binary_warped[int(binary_warped.shape[0]/2):,:], axis=0)

#     print(binary_warped.shape)
    
    Minv = cv2.getPerspectiveTransform(dst, src)
    out_img,left_fitx,right_fitx,left_fit,right_fit,ploty=findlines(binary_warped)
    if(test=='y'):
        print(left_fitx[-1])
        return 0
#         return (right_fitx[-1],left_fitx[-1])
# src = np.float32([[570,480],[770,480],[1100,690],[290,690]])
    if(right_fitx[-1]<1100 or right_fitx[0]<750 or right_fitx[len(right_fitx)//2]<900 ):
        if(right_gl is not None):
            right_fitx=right_gl
#           right_fitx=right_fitx+300
     
    else:
        if(right_gl is not None):
            right_gl=(right_fitx+right_gl)/2
        else:
            right_gl=right_fitx

    
    result=search_area(binary_warped,left_fitx,right_fitx,left_fit,right_fit)
    # curvature_plot(left_fitx,right_fitx,ploty)
    left_curverad, right_curverad=measure_cur_pix(left_fit,right_fit,ploty,left_fitx,right_fitx)
#     print(left_curverad, right_curverad,left_fitx,right_fitx,left_fit,right_fit,ploty)
    final_img=draw_lane(orig_img,binary_warped,left_fitx,right_fitx,ploty,Minv)
#     print(left_fitx)
#     print("--------")
#     print(right_fitx)
#     print("--------")

#     print(np.min(right_fitx))
#     print(np.min(left_fitx))
#     print(np.min(right_fitx)-np.min(left_fitx))
#     print("-----")
    count=count+1
    filepath="frames/frame"+str(count);
    cv2.imwrite(filepath+'.jpg',final_img)
#     print((orig_img.shape[1]/2))
#     font = cv2.FONT_HERSHEY_SIMPLEX
#     final_img = cv2.putText(final_img,"Bottom="+str(right_fitx[-1])+" Top="+str(right_fitx[0]),(20,40), font, 1, (255,255,255), 2, cv2.LINE_AA)
    x_offset=y_offset=50
    x_offset1=300
    y_offset1=50
    f = plt.figure()
    ax = plt.subplot(111)
    ax.plot(histogram)
#     plt.plot(histogram)
#     small_svc=cv2.resize(histogram, (600, 600)) 
#     small_svc=small_svc.astype(np.float32)
#     bw = cv2.cvtColor(combined_binary.astype(np.uint8), cv2.COLOR_GRAY2RGB)
#     br=255*combined_binary
    bw = np.dstack((binary_warped, binary_warped, binary_warped))*255
#     cv2.imwrite('messigray.jpg',out_img)
#     bw=mpimg.imread("messigray.jpg")
    
    bws=cv2.resize(bw, (200, 200))

    f.savefig('plot1.jpg')
    img_bgr=mpimg.imread("plot1.jpg")
    small_svc=cv2.resize(img_bgr, (200, 200))
    final_img[y_offset:y_offset+small_svc.shape[0], x_offset:x_offset+small_svc.shape[1]] = small_svc
    final_img[y_offset1:y_offset1+bws.shape[0], x_offset1:x_offset1+bws.shape[1]] = bws
    final_img[y_offset1:y_offset1+result.shape[0], x_offset1:x_offset1+result.shape[1]] = result
#     print("aaaaaaaaaaaaaaaaaaaa:",bw.shape)
    return final_img

testing=mpimg.imread("frames/frame1.jpg")
mypipeline(testing)

# +
# testimages_path=glob.glob('test_images/test*.jpg')
# max_total=0
# min_total=0
# for path in testimages_path:
#     testimg=mpimg.imread(path)
#     min_total+=mypipeline(testimg,'y')[0]
#     max_total+=mypipeline(testimg,'y')[1]
# average_max=max_total/len(testimages_path)
# average_min=min_total/len(testimages_path)
# print(average_max,average_min)

# +
import os

from moviepy.video.VideoClip import VideoClip
from moviepy.editor import VideoFileClip
from IPython.display import HTML
white_output = 'project_video_output_1.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
# clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4").subclip(37,42)
clip1 = VideoFileClip("project_video.mp4").subclip(15,17)
white_clip = clip1.fl_image(mypipeline) #NOTE: this function expects color images!!
# %time white_clip.write_videofile(white_output, audio=False)
# -

HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(white_output))





StarcoderdataJupyterScriptsDedupFiltered