<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sunnat Makhmudov on Medium]]></title>
        <description><![CDATA[Stories by Sunnat Makhmudov on Medium]]></description>
        <link>https://medium.com/@SunEdition?source=rss-27200ba748e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j2JjW4XbWFUjH3al.jpg</url>
            <title>Stories by Sunnat Makhmudov on Medium</title>
            <link>https://medium.com/@SunEdition?source=rss-27200ba748e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:56:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SunEdition/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lane Detection and Turn Prediction Algorithm for Autonomous Vehicles]]></title>
            <link>https://medium.com/@SunEdition/lane-detection-and-turn-prediction-algorithm-for-autonomous-vehicles-6423f77dc841?source=rss-27200ba748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6423f77dc841</guid>
            <category><![CDATA[turn-prediction]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[autonomous-vehicles]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lane-detection]]></category>
            <dc:creator><![CDATA[Sunnat Makhmudov]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 06:06:01 GMT</pubDate>
            <atom:updated>2020-07-06T16:56:24.415Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Today, I will show the way how to detect lane lines and predict turns on videos that can be implemented in real projects like Raspberry Pi cars and other autonomous vehicle projects. Follow this guide and </em><a href="https://github.com/Infinem/Invenimus_Lane_Detection_Project"><em>GitHub</em></a><em> repository link to get familiar with the project.</em></p><p><em>The programming language is used: </em><a href="https://www.python.org/"><em>Python</em></a><em> with </em><a href="https://opencv.org/"><em>OpenCV</em></a><em> library.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FikBwVa_SXuc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DikBwVa_SXuc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FikBwVa_SXuc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0fec51c39e31afe57a428f4cda8e114/href">https://medium.com/media/f0fec51c39e31afe57a428f4cda8e114/href</a></iframe><p><em>Links for the </em><a href="https://drive.google.com/file/d/1mYk9oNOKacxl6x6NOK5gxOdYJuafFPd7/view?usp=sharing"><em>source video</em></a><em>.</em></p><p><strong><em>The main challenge of this video is that center between lanes is floating over the video frame, so to correct prediction we need to handle this issue.</em></strong></p><h3>Steps were taken in the project:</h3><ul><li>Denoising the video frames using <a href="https://en.wikipedia.org/wiki/Kernel_(image_processing)">blurring kernel</a>;</li><li><a href="https://en.wikipedia.org/wiki/Grayscale">Grayscaling</a> and detecting edges on the frames with <a href="https://en.wikipedia.org/wiki/Canny_edge_detector">Canny</a> edge detection;</li><li>Drawing region of interest to embed lanes on the video frame;</li><li>Perspective warping;</li><li>Segmentation of lanes using vertical histogram projection;</li><li>Detecting lines on the video frame using <a href="https://docs.opencv.org/master/d9/db0/tutorial_hough_lines.html">Hough Lines Polar</a> and line optimization;</li><li>Displaying lines on the frame;</li><li>Turn prediction;</li><li>Whole process orchestrator;</li></ul><h3>1. Denoising the video frames using blurring kernel</h3><p>When we start processing any image for computer vision we always have to consider the filters which we use to highlight elements that we need to detect. It is an essential part of any image processing tasks. The first step to modify the frame is using a 3x3 kernel filter to smooth (blur) the image and reduce noises. You may think of using another blurring kernel or even another filter.</p><p>First I initialized 3x3 kernel looking like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*7fwxXY6_LnYfwmlenMeSQw.png" /></figure><pre>kernel = np.ones((3, 3), np.float32) / 9</pre><p>Then applied filter using OpenCV function <a href="https://www.tutorialspoint.com/opencv/opencv_filter2d.htm"><em>filter2d</em></a><em>:</em></p><pre>denoised_frame = cv2.filter2D(frame, -1, kernel)</pre><p><strong>Result of blurring the frame:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oIaAmR8tqCfeFtPtDc8iQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU3OIVUpXlwPGz1CIbnNDA.png" /><figcaption>Original frame (Left) — Denoised or blurred frame (Right)</figcaption></figure><p><strong>Reason:</strong> At first glance, it may seem that the effect is not visible, but later we will see that it helped to remove some artifacts from the image.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2652f4b5268e32c107b703e71c2546a/href">https://medium.com/media/d2652f4b5268e32c107b703e71c2546a/href</a></iframe><h3>2. Grayscaling and detecting edges on the frames with Canny edge detection</h3><p>The second filter which we use in this tutorial is the <strong><em>grayscale</em></strong> filter. All images have their own channels of the color spectrum. We have many types of images like RGB, CMYK and etc. For example, the most common RGB images use three channels for basic colors Red, Green, Blue, and all other colors can be acquired from a mix of these colors.</p><p>The job of the grayscale filter is removing that color channels and making a gray-colored image (mix of white and black colors). The OpenCV provides us a useful function that converts RGB image into a grayscale image.</p><pre>gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)</pre><p><strong>Result of grayscaling the frame:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU3OIVUpXlwPGz1CIbnNDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vF0dP8Foujs4Yxrsq0RCA.png" /><figcaption>Original RGB frame (Left) — Grayscaled frame (Right)</figcaption></figure><p><strong>Reason: </strong>Firstly, to process colored images it takes more computational power and space for storing them. Secondly, we do not need all color spectrum for image processing, as all colors: red, green, and blue are equal in their intensity in RGB space and it’s only necessary to specify single intensity value for each pixel rather than using three intensities for one pixel of a full-colored image.</p><p><strong><em>Edge detection </em></strong>is a powerful technique to find the object boundaries in the image. Edge detection commonly used in object segmentation and data extraction. Basically, this technique detects sharp changes in image brightness. As we want to find lanes lines on the road, we need to segment them. Fortunately, OpenCV provides us the function with a <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_canny/py_canny.html">Canny edge detector</a>:</p><pre>canny_edges = cv2.Canny(gray, 50, 150)</pre><p>Here it takes three parameters: first is a gray image, second and third parameters are the min and max values of gradient intensity of edges. It recommended by the library description to have a ration of 1:2 or 1:3 between these values.</p><p><strong>Result of applying edge detection on grayscale frame:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vF0dP8Foujs4Yxrsq0RCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQVFbsG9k1tzMn_IhBrHvg.png" /><figcaption>Grayscale frame (Left) — Frame with detected object edges (Right)</figcaption></figure><p><strong>Reason:</strong> Edge detection finds object boundaries from which we can determine the object shapes. Also, it simplifies images for further image processing.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d6ec2648cc7045efd3b0cec58b1453f/href">https://medium.com/media/5d6ec2648cc7045efd3b0cec58b1453f/href</a></iframe><h3>3. Drawing region of interest to embed lanes on the video frame</h3><p>Next, for further simplification of the image we can draw a region of interest which will highlight only that part of frame which contains lane lines. Since we want to detect only lane lines we can get rid of other objects from the image.</p><p>The logic is pretty simple, first, we create a mask with a shape of the original frame and draw a special polygon region filled by ones, the rest with zeros.</p><pre>height, width = frame.shape<br>mask = np.zeros_like(edges)</pre><pre>polygon = np.array([[<br>(int(width*0.30), height),              # Bottom-left point<br>(int(width*0.46),  int(height*0.72)),   # Top-left point<br>(int(width*0.58), int(height*0.72)),    # Top-right point<br>(int(width*0.82), height),              # Bottom-right point<br>]], np.int32)</pre><pre>cv2.fillPoly(mask, polygon, 255)</pre><p><strong>The result is a black frame (0s filled) with a white polygon (filled with 255):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05sRxnq4T0e-qcZcWZp8Qw.png" /><figcaption>Polygon mask</figcaption></figure><p>After we use AND operator to get a masked frame. Background logic: as the image consists of an array of numbers we take each number of it and apply AND operator with the mask. Below you can see the simplified version of the actual process behind the masking region of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccQz9YGy0u1iXbGOAGPUeg.png" /></figure><pre>cropped_edges = cv2.bitwise_and(frame, mask)</pre><p><strong>Result of finding region of interest:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAAqGb-9ZqGPncrz46YQ-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzl8-uTQJVtxXmKlQabM6A.png" /></figure><p><strong>Reason:</strong> We simplified image significantly and got only a necessary part of it, so our algorithm will not be distracted by the side objects.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eb8dbb2cf9b4f8df62de60201e4cb77/href">https://medium.com/media/9eb8dbb2cf9b4f8df62de60201e4cb77/href</a></iframe><h3>4. Perspective warping</h3><p>In this section, we look at how to change the perspective of the image, especially a polygon region which we masked previously. The main logic is to look at the road from sky view angle.</p><p>First, we need to get frame sizes to save the ratio between points of the polygon which we will warp.</p><pre>height, width = frame.shape    # Get image size</pre><p>Then we need an offset that helps us to regulate the warped image in later tinkering stage.</p><pre>offset = 50     # Offset for frame ratio saving</pre><p>After we declare two sets of points, first for the original view — the points of polygon (like in region of interest section), second for destination points to which it would be fitted after perspective warping.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*iHx9K9pfppbsMyksD0Ej4A.png" /><figcaption>Source points warped to destination points.</figcaption></figure><pre># Perspective points to be warped<br>source_points = np.float32([<br>    [int(width*0.46), int(height*0.72)],     # Top-left point<br>    [int(width*0.58), int(height*0.72)],     # Top-right point<br>    [int(width*0.30), height],               # Bottom-left point<br>    [int(width*0.82), height]])              # Bottom-right point</pre><pre># Window to be shown<br>destination_points = np.float32([<br>    [offset, 0],                             # Top-left point<br>    [width-2*offset, 0],                     # Top-right point<br>    [offset, height],                        # Bottom-left point<br>    [width-2*offset, height]])               # Bottom-right point</pre><p>As you can see we write all points coordinates with bind to frame width and height, doing that saves the rationality of frame. So, if we will have another dimensionality of the frame, the warping zone would be +- the same. Then we calculate a perspective transform from four pairs of the corresponding points using built-in function from OpenCV — <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html"><em>getPerspectiveTransform</em></a><em>. </em>Finally, we apply the perspective transformation of the frame using another OpenCV function — <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html"><em>warpPerspective</em></a><em>.</em></p><pre># Matrix to warp the image for skyview window<br>matrix = cv2.getPerspectiveTransform(source_points, destination_points)</pre><pre># Final warping perspective<br>skyview = cv2.warpPerspective(frame, matrix, (width, height))</pre><p><strong>Result of perspective warping:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iG-Lva0Vzc_w6arUgaAwhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdDdrGL5fz9DC3qYuJhPeg.png" /></figure><p><strong>Offset tinkering results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezS00Ej13w_x1h-ZzbiOSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zkulPRw5xmlANOTTQ8y7w.png" /><figcaption>Offset = 50 (Left) — Offset = 100 (Right)</figcaption></figure><p><strong>Reason:</strong> We do perspective warping to handle the problem of the floating center. It helps us to find the actual center between two lane lines which we use later.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d27e2561f1f68a68f36104a88d9c8d3/href">https://medium.com/media/8d27e2561f1f68a68f36104a88d9c8d3/href</a></iframe><h3>5. Segmentation of lanes using vertical histogram projection</h3><p>Object segmentation is a common technique when we talk about computer vision. The logic is to built histogram using an image where we want to segment the objects. First, we need to convert image in binary format that will only contain black and white pixels. Then we add all values in pixels and build histogram, to recall that 0 — black color and 255 — white color.</p><pre>histogram = np.sum(frame, axis=0)   # Build histogram</pre><p><strong>Result histogram on edged and warped frame:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyxJBw0WVH8vbhSZcgRgyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lX0Bawkp2761ZhxaDxztw.png" /></figure><p>You can see the histogram of the warped frame where we clearly distinguish the lines by mountain-like graphs. Next, we can find the left and right lines from histogram projection.</p><pre><br># Find mid point on histogram<br>midpoint = np.int(histogram.shape[0]/2)</pre><pre># Compute the left max pixels<br>leftx_base = np.argmax(histogram[:midpoint])</pre><pre># Compute the right max pixels<br>rightx_base = np.argmax(histogram[midpoint:]) + midpoint<br></pre><p><strong>Result of drawing left_x and right_x bases on the histogram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_f8KwtXqUUnZp7Ig3dHGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeFe_vGX0199PhlVpSX8-w.png" /></figure><p><strong>Reason:</strong> From histogram projection, we can find the left and right bases coordinates on X-axis.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d65556370392fa85c28653df51ffe9b/href">https://medium.com/media/5d65556370392fa85c28653df51ffe9b/href</a></iframe><h3>6. Detecting lines on the video frame using Hough Lines Polar and line optimization</h3><p>This is one of the essential parts of the project. Most of the above processes were done to properly detect lines on the frame. <a href="https://en.wikipedia.org/wiki/Hough_transform">Hough Transform</a> is a function that finds shapes using a specific algorithm between the pixels. As we have to find lane lines on the image we use a built-in OpenCV function called <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html?highlight=houghlinesp#houghlinesp"><em>HoughLinesP</em></a>. This function has several parameters that we have to tinker by ourselves to properly find line coordinates on the frame.</p><pre>cv2.HoughLinesP(frame, 1, np.pi/180 , 20, np.array([]), minLineLength=40, maxLineGap=150)</pre><ul><li><em>1st parameter</em> —<strong> frame</strong> where we want to find lines.</li><li><em>2nd parameter</em> — <strong>rho</strong>. Distance resolution of the accumulator in pixels.</li><li><em>3rd parameter</em> — <strong>theta</strong>.<strong> </strong>Angle resolution of the accumulator in radians.</li><li><em>4th parameter</em> — <strong>threshold</strong>.<strong> </strong>Only those lines are returned that get enough votes ( &gt;threshold ).</li><li><em>5th parameter </em>— <strong>minimum line length</strong>. Line segments shorter than that are rejected.</li><li><em>6th parameter </em>— <strong>maximum allowed gap</strong> between points on the same line to link them.</li></ul><p><strong>Result of detecting lines on the frame:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ipBs8EehX6kYbpsKJqOKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuU8O5WfXLrZwIXf0Nxcew.png" /></figure><p>Now, we have lines detected on the frame but you can see that there are multiple lines drawn even if there is one solid lane line. We have to improve and optimize line detection to draw two solid and pretty lines on the road.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68618e8441a30f9a5a3a82716050b6a6/href">https://medium.com/media/68618e8441a30f9a5a3a82716050b6a6/href</a></iframe><h4>Optimization part</h4><p>Pay close attention to this part, here we will try to optimize line detection and try to handle some problematic parts where lane lines are not visible or visible partially.</p><p>First, we declare lists that will store the left and the right lane lines parameters and two of them as one list.</p><pre>lane_lines = [] # For both lines</pre><pre>left_fit = []   # For left line<br>right_fit = []  # For right line</pre><p>Also, we have to take frame size to make our algorithm scalable to any frame resolution.</p><pre>height, width, _ = frame.shape  # Take frame size</pre><p>Let’s look at For loop closer:</p><pre># Access each line in lines scope<br>for line in lines:</pre><pre>    # Unpack actual line by coordinates<br>    x1, y1, x2, y2 = line.reshape(4)</pre><p>Firstly, we unpack those lines that we detect using Hough Lines function from the previous function. Basically, we get (x1, y1) coordinates of one point and (x2, y2) of another, from which we can build the lines.</p><pre>    # Take parameters from points gained<br>    parameters = np.polyfit((x1, x2), (y1, y2), 1)<br>    <br>    # First parameter in the list parameters is slope<br>    slope = parameters[0]</pre><pre>    # Second is intercept<br>    intercept = parameters[1]</pre><p><em>np.polyfit(x, y, degree) </em>function returns polynomial values from given coordinates to it and degree of the fitting polynomial. In other words, we get slope and intercept of the line by using this function.</p><pre>  if slope &lt; 0:   # Here we check the slope of the lines</pre><pre>    right_fit.append((slope, intercept))</pre><pre>  else:</pre><pre>    left_fit.append((slope, intercept))</pre><p>Next, we check to which lines previously obtained parameters are belonging. The logic is simple, the slope of right lines is always smaller than 0, actually, it is a negative number. The slope of the left lines is always positive numbers, so it will go to <em>else</em> statement.</p><pre>  # Here we ckeck whether fit for the left line is valid<br>  if len(left_fit) &gt; 0:</pre><pre>    # Averaging fits for the left line<br>    left_fit_average = np.average(left_fit, axis=0)</pre><pre>    # Add result of mapped points to the list lane_lines<br>    lane_lines.append(map_coordinates(frame, left_fit_average))</pre><pre>  # Here we ckeck whether fit for the right line is valid<br>  if len(right_fit) &gt; 0:</pre><pre>    # Averaging fits for the right line<br>    right_fit_average = np.average(right_fit, axis=0)</pre><pre>    # Add result of mapped points to the list lane_lines<br>    lane_lines.append(map_coordinates(frame, right_fit_average))</pre><p>After all, we check whether it found any fits of lines and calculate the average of the corresponding fits. Then we convert slopes and intercepts into points using map_coordinates function from that we get (x1, y1) and (x2, y2) of the lines.</p><p><strong>Results of line optimization after displaying:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKPWgX8DygMUodOZ6kalxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKs8b4oHqeMLqxxO2cf4Bw.png" /></figure><p>Code functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00998b7f02ae762596c87c60a8b9b7ee/href">https://medium.com/media/00998b7f02ae762596c87c60a8b9b7ee/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db0462c93e0bb7d3ab1df1b3c4b1269d/href">https://medium.com/media/db0462c93e0bb7d3ab1df1b3c4b1269d/href</a></iframe><h3>7. Displaying lines on the frame</h3><p>One of the final parts, we will display all our “fruits of labor” done before.</p><p>First, we create an empty mask with the original frame size.</p><pre># Create array with zeros using the same dimension as frame<br>mask = np.zeros_like(frame)</pre><p>Next, we access coordinates from line calculations which we have done before and get coordinates. By those coordinates, we draw the lines on the empty mask.</p><pre># Check if there is a existing line<br>if lines is not None:</pre><pre>  # Iterate through lines list<br>  for line in lines:</pre><pre>    # Unpack line by coordinates<br>    for x1, y1, x2, y2 in line:</pre><pre>       # Draw the line on the created mask <br>       cv2.line(mask, (x1, y1), (x2, y2), (0, 255, 0), 5)</pre><p>Finally, we add a mask to the original frame and get pretty drawn lane lines :)</p><pre># Merge mask with original frame<br>mask = cv2.addWeighted(frame, 0.8, mask, 1, 1)</pre><p><strong>Results of display:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCvSBLkhpFJGJ9saLB1g1w.png" /></figure><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e047f50af8f02835f64ce3ee483898c/href">https://medium.com/media/9e047f50af8f02835f64ce3ee483898c/href</a></iframe><h3>8. Turn prediction</h3><p>The main logic of this part is to make turn prediction using the central point between two lines. The real challenge is that we cannot use static point like frame center and make up all turn prediction around it. Because the video center is floats during some period of time. Previously, we discussed histogram projection, this part directly linked with that. Let’s go.</p><pre># Here we check if there is 2 lines detected<br>if len(lane_lines) == 2:</pre><pre>    # Unpacking left line<br>    left_x1, _, left_x2, _ = lane_lines[0][0]</pre><pre>    # Unpacking right line<br>    right_x1, _, right_x2, _ = lane_lines[1][0]</pre><pre>    # Calculate the relative position of the lower middle point<br>    low_mid = (right_x1 + left_x1) / 2  </pre><pre>    # Calculate the relative position of the upper middle point<br>    up_mid = (right_x2 + left_x2) / 2</pre><p>We only consider two cases when two lane lines detected and the default case. When two lines detected we unpack x-coordinates of two lines:</p><ul><li>x1 and x2 of the left line;</li><li>x1 and x2 of the right line;</li></ul><p>From them, we find the relative centers by the midpoint formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*C4x5M0MzxC52gJ7WSGvdng.png" /></figure><pre>else:       # Handling undetected lines</pre><pre>    up_mid = int(width*1.9)</pre><pre>    low_mid = int(width*1.9)</pre><p>Default case when either one or none lines detected. Shows only in a straight direction.</p><p>Further, we pass <em>low_mid</em> to the next function called <strong>add_text()</strong><em>. </em>Also, it takes <em>left_x_base </em>and <em>right_x_base</em> derived previously from histogram projection.</p><pre># Find lane center between two lines<br>lane_center = left_x + (right_x - left_x) / 2</pre><p>We find the center between lane lines using the above formula. This center is acquired from histogram projection x bases.</p><pre># Find the deviation<br>deviation = image_center - lane_center</pre><p>Then we find a deviation between two different centers and using this value we can find exact numbers according to which we predict turn.</p><pre># Prediction turn according to the deviation<br>if deviation &gt; 160:         <br>    text = &quot;Smooth Left&quot;<br>elif deviation &lt; 40 or deviation &gt; 150 and deviation &lt;= 160:<br>    text = &quot;Smooth Right&quot;<br>elif deviation &gt;= 40 and deviation &lt;= 150:<br>    text = &quot;Straight&quot;</pre><p>The above part is used only for this video case. If you want to use it for other videos, it has to be tinkered accordingly.</p><p>Code functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d7cc83e943bc222449aa8586d8c89e/href">https://medium.com/media/c0d7cc83e943bc222449aa8586d8c89e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd7ede480b52565424c15c5835ebb42d/href">https://medium.com/media/bd7ede480b52565424c15c5835ebb42d/href</a></iframe><h3>9. Whole process orchestrator</h3><p>This is the final point of the project, the whole step by step execution of all functions is illustrated in this orchestrator.</p><p>Code function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b541887f16f32097ca1635c835307c86/href">https://medium.com/media/b541887f16f32097ca1635c835307c86/href</a></iframe><p><em>In conclusion, you learned how to use one of the most popular libraries for python OpenCV and several key techniques to deal with any project based on Computer Vision. Furthermore, you able to find lane lines on the road and predict the vehicle turn. Now, you are closer to construct your own autonomous vehicle. Good luck! :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6423f77dc841" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>