PageRenderTime 70ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

/Project-1 Lane Finding/Project-1-Lane-Line-Finding/main.py

https://bitbucket.org/anujdutt9/self-driving-car-nano-degree
Python | 169 lines | 96 code | 42 blank | 31 comment | 11 complexity | 8b3649b60cc84fce9d08c64b98408942 MD5 | raw file
  1. # Project-1: Finding Lane Lines in Images and Videos
  2. # Import Dependencies
  3. import os
  4. from sys import argv
  5. import time
  6. import cv2
  7. import glob
  8. import numpy as np
  9. from utils import *
  10. from moviepy.editor import VideoFileClip
  11. import matplotlib.pyplot as plt
  12. from matplotlib.image import imread
  13. from matplotlib import style
  14. style.use('ggplot')
  15. # Create Directory for Output Images and Videos
  16. imageOutDir = './OutputImages/'
  17. videoOutDir = './OutputVideos/'
  18. if not os.path.exists(imageOutDir):
  19. os.makedirs(imageOutDir)
  20. if not os.path.exists(videoOutDir):
  21. os.makedirs(videoOutDir)
  22. # Process Image function for Videos
  23. def process_image(image):
  24. # NOTE: The output you return should be a color image (3 channel) for processing video below
  25. # TODO: put your pipeline here,
  26. # you should return the final output (image with lines are drawn on lanes)
  27. result = LaneLinesPipeline(image,name=None,arg='videos')
  28. return result
  29. # Check all Files in the Directory
  30. print('List of all Test Images in Folder',os.listdir('test_images/'))
  31. # Build the Pipeline
  32. # 1. Read in the Image
  33. # 2. Convert to Grayscale
  34. # 3. Apply Gaussian Blur
  35. # 4. Use Canny Edge to find Edges
  36. # 5. Find Polynomial Region of Interest (ROI) and select Lane Lines.
  37. # 6. Apply Hough Transform and Filter it for Lane Lines
  38. # 7. Plot the Lane Lines on Actual Image
  39. # Pipeline to draw Lane Lines
  40. def LaneLinesPipeline(img,name=None,arg=None):
  41. start = time.time()
  42. x = img.shape[1]
  43. y = img.shape[0]
  44. # print('\nThe image is of type: {0} and shape: {1}'.format(type(read_image),read_image.shape))
  45. # Step-2: Convert to Grayscale
  46. gray_image = grayscale(img)
  47. # Step-3: Apply Gaussian Blur
  48. kernel_size = 5
  49. gaussian_image = gaussian_blur(gray_image,kernel_size)
  50. # Step-4: Apply Canny Edge Detection
  51. low_threshold = 50
  52. high_threshold = 150
  53. canny_edge = cannyEdge(gaussian_image,low_threshold,high_threshold)
  54. canny_edge = cv2.bitwise_or(canny_edge, yellow_mask(img))
  55. # Step-5: Find Polynomial Region of Interest (ROI) and select Lane Lines.
  56. border = 0
  57. imshape = img.shape
  58. # Here, "x" and "y" are the dimensions of the Input Image
  59. vertices = np.array([[(int(0.11*x), y), (int(0.44*x),int(0.6*y)), (int(0.56*x),int(0.6*y)), (int(0.95*x),y)]], dtype=np.int32)
  60. image_roi = region_of_interest(canny_edge, vertices)
  61. # Step-6: Apply Hough Transform and Filter Image
  62. rho = 1
  63. theta = np.pi / 180
  64. threshold = 15
  65. min_line_len = 60
  66. max_line_gap = 30
  67. hough_transformed_image = hough_lines(image_roi, rho, theta, threshold, min_line_len, max_line_gap)
  68. # Step-7: Plot Lane Lines on Actual Image
  69. filtered_image = weighted_img(hough_transformed_image,img,α=0.6, β=1., λ=0.)
  70. end = time.time()
  71. print('Time Taken for whole Process is {} ms'.format((end - start) * 100))
  72. if arg == 'images':
  73. fig, ax = plt.subplots(nrows=2, ncols=2)
  74. arr = [['Greyscale & Gaussian Blurring','Edge Detection'],
  75. ['Region of Interest', 'Hough Transform']]
  76. arr1 = [[gaussian_image,canny_edge],
  77. [image_roi, hough_transformed_image]]
  78. # Plot the Final Output with Outputs of Process Followed
  79. for i in range(0,2):
  80. for j in range(0,2):
  81. ax[i,j].imshow(arr1[i][j],cmap='gray')
  82. ax[i,j].set_axis_off()
  83. ax[i,j].set_title(arr[i][j])
  84. ax[i,j].set_aspect('equal')
  85. figName = imageOutDir+name+'_Process.jpg'
  86. fig.savefig(figName)
  87. fig1,ax1 = plt.subplots()
  88. ax1.imshow(filtered_image)
  89. ax1.set_axis_off()
  90. ax1.set_title('Final Image')
  91. path = imageOutDir+name+'_Final.jpg'
  92. fig1.savefig(path)
  93. plt.show()
  94. return filtered_image
  95. # Main Function
  96. if __name__ == '__main__':
  97. if argv[1] == 'images':
  98. for image in glob.glob('test_images/*.jpg'):
  99. img = imread(image)
  100. name = os.path.splitext(image)[0][12:]
  101. LaneLinesPipeline(img,name,arg='images')
  102. elif argv[1] == 'videos':
  103. # Process White Lane Lines Video
  104. print('Processing Video: solidWhiteRight.mp4')
  105. whiteLanesOut = 'OutputVideos/solidWhiteRightOut.mp4'
  106. clip1 = VideoFileClip('test_videos/solidWhiteRight.mp4')
  107. whiteLanesOutClip = clip1.fl_image(process_image)
  108. whiteLanesOutClip.write_videofile(whiteLanesOut, audio=False)
  109. # Process Yellow Lane Lines Video
  110. print('\nProcessing Video: solidYellowLeft.mp4')
  111. yellowLanesOut = 'OutputVideos/solidYellowLeftOut.mp4'
  112. clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')
  113. yellowLanes_clip = clip2.fl_image(process_image)
  114. yellowLanes_clip.write_videofile(yellowLanesOut, audio=False)
  115. # Process Challenge Video
  116. print('\nProcessing Video: challenge.mp4')
  117. challengeOut = 'OutputVideos/challengeOutput.mp4'
  118. clip3 = VideoFileClip('test_videos/challenge.mp4')
  119. challenge_clip = clip3.fl_image(process_image)
  120. challenge_clip.write_videofile(challengeOut, audio=False)
  121. elif argv[1] == 'help':
  122. print('1. To Process Images, Use: python main.py images')
  123. print('2. To Process Videos, Use: python main.py videos')
  124. else:
  125. print('\nPlease Enter Correct Argument !!!')
  126. print('\nUse:\npython main.py help \nfor help ')
  127. # --------------------------- EOC ---------------------------