yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
ROSMASTER M3📖
00.Configuration and Operation Guide
  • 1.Quick start handle to control the car
  • 2.Log in to the car and view the code
  • 3.Enter the Docker (For RPI5)
  • 4.Camera and Radar Configuration (Must Read)
  • 5.Assembly video
  • 6.Modify Control Board Firmware Parameters
01.Chassis Control Course
  • 01.ROS control
  • 02.Handle control
  • 03.Keyboard control
  • 04.Robot state estimation
  • 05.Data remote visualization
  • 06.Line velocity calibration
  • 07.Angular velocity calibration
  • 08.Robot URDF model
  • 09.Line patrol automatic driving
  • 10.Patrol
02.Lidar Course
  • 01.Lidar introduction and use
  • 02.Lidar point cloud fusion and filtering
  • 03.Lidar obstacle avoidance
  • 04.Lidar tracking
  • 05.Lidar guard
  • 06.Gmapping-SLAM mapping
  • 07.Cartographer-SLAM mapping
  • 08.slam_toolbox mapping
  • 09.Lifelong mapping
  • 10.Navigation2 single-point navigation avoid
  • 11.Navigation2 multi-point navigation avoid
  • 12.Cartographer relocalization navigation
  • 13.slam_toolbox localization and navigation
  • 14.Synchronous mapping and navigation
  • 15.RTAB-Map mapping
  • 16.RTAB-Map navigation
  • 17.APP mapping and navigation
03.AI Model Basics
  • 1.AI large model types and principles
  • 2.RAG retrieval enhancement and model training samples
  • 3.Embodied intelligent robot system architecture
  • 4.Embodied intelligent functions core source code
04.AI Model Development
  • 01.Register a model service provider account
  • 02.Configuring API-KEY
  • 03.Introduction to Dify
  • 04.Basic Dify Features
  • 05.AI Large Model Development - chatbot
  • 06.Deploy the RAG knowledge base
  • 07.RAG knowledge base + chatbot
  • 08.AI agent workflow
  • 09.Custom wake-up response
  • 10.Core module testing tools
05.AI Model - Voice Version
  • 1.Semantic understand and command follow
  • 2.Multimodal visual understanding
  • 3.Multimodal visual understanding+SLAM navigation
  • 4.Intention estimation
06.AI Model - Text Version
  • 1.Semantic understand and command follow
  • 2.Multimodal visual understanding
  • 3.Multimodal visual understanding+SLAM navigation
  • 4.Intention estimation
07.Road Network Planning and Navigation
  • 1.Introduction and Quick Start
  • 2.Constructing a Pose Map
  • 3.Road Network Labelling
  • 4.Inter-Road Network Planning and Navigation
  • 5.Free-Pose Road Network Navigation
  • 6.Path Replanning
08.Autonomous Driving expand(Need purchase track map)
  • 01.Environment Setup & Precautions
  • 02.YOLO Environment Configuration
  • 03.Data Collection
  • 04.Data Annotation
  • 05.YOLOv11 Model Training
  • 06.Model Format Conversion
  • 07.Vehicle Centerline Calibration
  • 08.Lane Detection
  • 09.Lane-Keeping Autonomous Driving
  • 10.Traffic Sign Recognition
  • 11.Comprehensive Autonomous Driving Applications
  • 12.Autonomous Driving Debugging Module
  • 13.Road Network Planning with Track Map
  • 14.Road Network Planning with Traffic Sign Recognition
  • 15.AI Model with Road Network Planning
  • 16.AI Model with Track Map and SLAM Navigation
  • 17.AI Model with Road Network Planning and Autonomous Driving
09.Depth Camera Course
  • 01.Dabai_DCW2 Camera Introduction
  • 02.Nuwa-HP60C Camera Introduction
  • 03.Depth Pseudo-Color Image
  • 04.Depth Camera Distance Measurement
  • 05.Wood Block Volume Measurement
  • 06.Edge Detection
  • 07.YOLOv11 Object Detection
  • 08.YOLOv11 Object Tracking
  • 09.Color Following
  • 10.Face Following
  • 11.QR Code Following
  • 12.Machine Code Following
  • 13.KCF Object Tracking
  • 14.QR Code Motion Control
  • 15.AR Vision
10.Mediapipe Visual Course
  • 01.Hand Detection
  • 02.Posture Detection
  • 03.Overall Detection
  • 04.Facial Landmark Detection
  • 05.3D Object Recognition
  • 06.Face Detection
  • 07.Gesture Recognition
  • 08.Face Special Effects
  • 09.Brush
  • 10.Finger Control
  • 11.Palm Target Positioning
  • 12.Fingertip Trajectory Recognition
  • 13.Gesture Following
  • 14.Posture Following
  • 15.Gesture Motion Control
11.Multi-vehicle Course
  • 1.Multi-vehicle Control
  • 2.Multi-vehicle Navigation
  • 3.Multi-vehicle Platoon
12.AI Large Model Basic Course
Offline large model (Text Interaction)
  • 0. AI Large Model Mirroring Explanation
  • 1. Deployment of large-scale AI models
  • 2. Installation of the large model dialogue platform
  • 3. Meta AI Llama 3.2 model
  • 4. Alibaba Cloud Qwen3 Model
  • 5. DeepSeek DeepSeek-R1 model
  • 6. Microsoft Phi-4 mini model
  • 7. Alibaba Cloud Qwen2.5vl Visual Multimodal Large Model
  • 8. Google Gemma3 Visual Multimodal Large Model
  • 9. Llava Visual Multimodal Large Model
  • 10. Multimodal Visual Understanding Applications
  • 11.MiniCPM-V Visual Multimodal Large Model
  • 12. Multimodal Text-Based Image Application
  • 13. Multimodal Video Analysis Application
  • 14. Multimodal table scanning application
  • 15. Multimodal visual positioning applications
  • 16. Multimodal Autonomous Agent Application
Offline large model (Voice Interaction)
  • 0. Voice Interaction Hardware Connection (Must Read)
  • 1. Offline speech-to-text (ASR)
  • 2. Offline Text-to-Speech (TTS)
  • 3. AI large model voice interaction
  • 4. Multimodal visual understanding and voice interaction
  • 5. Multimodal Text-Based Image Application
  • 6. Multimodal Video Analysis Application
  • 7. Multimodal visual positioning applications
  • 8. Multimodal table scanning application
  • 9. Multimodal Autonomous Agent Applications
  • 10. AI large model offline voice assistant
Online large model (Text Interaction)
  • 1. OpenRouter Large Model API Aggregation Platform
  • 2. Multimodal visual understanding applications
  • 3. Multimodal visual positioning applications
  • 4. Multimodal table scanning application
  • 5. Multimodal Autonomous Agent Applications
Online large model (Voice Interaction)
  • 0. Voice Interaction Hardware Connection (Must Read)
  • 1. Online speech-to-text (ASR)
  • 2. Online Text-to-Speech (TTS)
  • 3. AI large model voice interaction
  • 4. Multimodal visual and voice interaction
  • 5. Multimodal visual positioning applications
  • 6. Multimodal table scanning application
  • 7. Multimodal Autonomous Agent Applications
  • 8. AI large model online voice assistant
13.Control Board Course
1.Development environment setup
  • 1.Introduction to the Control Board
  • 2.Set up the STM32CUBEIDE development environment
  • 3.Burning STM32 firmware using SWD
  • 4.Burning STM32 firmware using serial port
  • 5.Compile the microros driver library
  • 6.Install and start the microros agent
  • 7.Import Project
2.Control board STM32 basic routine
  • 1.Turn on the LED light
  • 2.Button functions
  • 3.Drive the buzzer
  • 4.Serial communication
  • 5.Battery voltage detection
  • 6.Driving PWM Servo
  • 7.Drive motor
  • 8.Read motor encoder data
  • 9.PID control of motor speed
  • 10.Robot kinematics analysis theory
  • 11.Read IMU data
  • 12.Read Lidar data
  • 13.Flash access data
  • 14.Driving OLED Displays
  • 15.Driving RGB light strip
  • 16.SBUS model aircraft remote control
  • 17.USB controller remote control
  • 18.CAN bus communication
3.Control board micro_ros basic routine
  • 1.Post a topic
  • 2.Subscribe to a topic
  • 3.Multi-topic subscription and publishing
  • 4.Subscribe to the buzzer topic
  • 5.Subscribe to the bus servo topic
  • 6.Subscribe to the rate control topic
  • 7.Release Speed Topic
  • 8.Publish IMU data topic
  • 9.Publish radar data topic
14.Main Control Course
Jetson Orin Nano_NX
  • 1.Jetson Orin board introduction
  • 2.Restore the factory image system
  • 3.Backup SSD system
  • 4.SSD expansion
  • 5.Network configuration
  • 6.SSH remote login
  • 7.VNC remote control
  • 8.Remote file transfer
  • 9.Jtop tool
  • 10.Exchange space expansion
Raspberry Pi
  • 1. Introduction to Raspberry PI 5
  • 2. Raspberry PI system installation and backup
  • 3. Powering the Raspberry PI 5
  • 4. Startup of Raspberry PI 5
  • 5. Update and upgrade operating system
  • 6. Introduction to raspi-config tool
  • 7. config.txt file description
  • 8. Network Configuration
  • 9. remote access
  • 10. Transfer files remotely
  • 11. Set display resolution and rotation
  • 12. Set screen to sleep
  • 13. Play audio and video
  • 14. Using USB camera
  • 15. Using MIPI camera
  • 16. Get real-time temperature of Raspberry Pi
RDKX5
  • 1.Introduction to RDK X5 board
  • 2.Write system file
  • 3.Hardware interface description
  • 4.Install case and other accessories
  • 5.Network configuration
  • 6.Remote login
  • 7.Update system
  • 8.srpi-config user guide
  • 9.config. txt configuration file
  • 10.Self-startup setting
  • 11.RDK exclusive command usage
  • 12.Linux command usage
  • 13.GPIO readwrite operation
  • 14.Image classification algorithm
  • 15.Use USB camera
  • 16.Use MIPI camera
  • 17.Binocular camera depth algorithm
15.YOLOv11 Development (ORIN)
  • 1.YOLO environment construction
  • 2.CLI use
  • 3.Object detection
  • 4.Instance segmentation
  • 5.Pose estimation
  • 6.Image classification
  • 7.Oriented object detection
  • 8.Model conversion
  • 9.Dataset annotation
  • 10.Model Training_Conversion
  • 11.Model prediction
16.YOLOv11 Development(RDKX5)
  • 1.YOLO environment construction
  • 2.CLI use
  • 3.Object detection
  • 4.Instance segmentation
  • 5.Pose estimation
  • 6.Image classification
  • 7.Oriented object detection
  • 8.Model prediction
  • 9.Model Quantization
17.YOLOv11 Development (RPI)
  • 1.YOLO environment construction
  • 2.CLI use
  • 3.Object detection
  • 4.Instance segmentation
  • 5.Pose estimation
  • 6.Image classification
  • 7.Oriented object detection
  • 8.Model conversion
  • 9.Model prediction
18.Linux Operating System
  • 1.Introduction to Linux system
  • 2.Ubuntu file system
  • 3.Ubuntu common commands
  • 4.Ubuntu common editors
  • 5.Ubuntu software operation commands
  • 6.Virtual machine installation
  • 7.SSH remote control
  • 8.VNC remote control
  • 9.Transfer files remotely
  • 10.Driver library and communication
  • 11.Static IP and hotspot mode
  • 12.Bind device ID
  • 13.Capacity expansion and resource allocation
  • 14.Update system software sources
  • 15.Set root user password
  • 16.sudo free password
  • 17.Connect to WiFi network
  • 18.View system version
  • 19.Customized service management
  • 20.Back up system image
19.ROS2 Basic Course
  • 1.Introduction to ROS2
  • 2.ROS2 install Humble
  • 3.ROS2 development environment
  • 4.ROS2 workspace
  • 5.ROS2 function package
  • 6.ROS2 node
  • 7.ROS2 topic communication
  • 8.ROS2 service communication
  • 9.ROS2 action communication
  • 10.ROS2 custom interface message
  • 11.ROS2 parameter service case
  • 12.ROS2 meta-function package
  • 13.ROS2 distributed communication
  • 14.ROS2 DDS
  • 15.ROS2 time related API
  • 16.ROS2 common command tools
  • 17.ROS2 rviz2 use
  • 18.ROS2 rqt toolbox
  • 19.ROS2 Launch startup file configuration
  • 20.ROS2 recording and playback tool
  • 21.ROS2 URDF model
  • 22.ROS2 Gazebo simulation platform
  • 23.ROS2 TF2 coordinate transformation
20.Docker Course
  • 1、Docker overview and docker installation
  • 2、Common commands for docker image containers
  • 3、Docker images deeply understand and publish images
  • 4、Docker hardware interaction and data processing
  • 5、Enter the bot's docker container
  • 6、Robot development environment construction in Docker
21.Image Processing Basics Course
  • 1. Introduction to Open Source CV
  • 2. Image reading and display
  • 3. Image writing
  • 4. Image quality
  • 5. Pixel Operation
  • 6. Image zoom
  • 7. Image cutting
  • 8. Image translation
  • 9. Image Mirroring
  • 10. Affine Transformation
  • 11. Image Rotation
  • 12. Perspective Transformation
  • 13. Grayscale processing
  • 14. Image Binarization
  • 15. Edge Detection
  • 16. Line drawing
  • 17. Rectangle and circle drawing
  • 18. Drawing text and pictures
Download
  • Mapping_APP(iOS_Android)
  • MainBoard_AI_Pure_System
  • Robot_Image_System_File
  • Code-Firmware
  • Instruction_Manual
  • VM_File
  • Software_Tools
  • Firmware_DriverFile
  • 3D_Model_File
  • ROS2_Basic_VM
  • Other_Annex
Download ZIP

Welcome to ROSMASTER M3 repository

09.Lane-Keeping Autonomous Driving

Lane-Keeping Autonomous Driving

Lane-Keeping Autonomous Driving1. Course Content2. Run Example Program3. Principle Analysis3.1 Straight Driving Maintenance3.2 Left and Right Lane Keeping3.3 Curve Turning4. Source Code Analysis

1. Course Content

Basic: Start the autonomous driving program and use lane-keeping autonomous driving functionality in the sandbox map

Advanced: Understand the implementation principles of lane-keeping

2. Run Example Program

  • Use the following command to start microROS agent to connect to the chassis

If the agent has already been started, there is no need to start it repeatedly

start_agent
  • Place the vehicle in the middle position of the lane in the sandbox map

image-20251203100328912

  • Start lane-keeping autonomous driving
xxxxxxxxxx
ros2 launch m3_bringup auto_drive.launch.py unsign:=True

image-20251203182417331

 

[!NOTE]

Display parameters

  • FPS: Real-time frame rate
  • infer: Total inference and computation time per frame
  • angle-dev: The angle between the vehicle body centerline (blue in the figure) and the line connecting the lane line intersection point with the centerline starting point

image-20251203094526191

  • Start dynamic parameter configuration panel
xxxxxxxxxx
ros2 run rqt_reconfigure rqt_reconfigure
  • Click AutoDrive to enter the parameter control panel. If there is no AutoDrive on the left side when you first open it, click Refresh below

image-20251203094713276

  • Click START_AutoDrive to start autonomous driving and lane-keeping functionality

image-20251128151421743

 

  • After that, the vehicle will perform autonomous driving along the outer lane

    • In straight road sections, it will automatically execute straight driving and left/right lane centering
    • In curved road sections, it will automatically turn and return to lane-keeping mode after exiting the curve

image-20251203100952487

 

  • If you need to stop, simply uncheck START_AutoDrive

image-20251203102211787

[!TIP]

If the lane-keeping autonomous driving effect does not meet expectations, refer to this chapter's 12-Autonomous Driving Debugging Special Topic for parameter debugging.

 

3. Principle Analysis

3.1 Straight Driving Maintenance

  • According to perspective principles, in the camera perspective, the extensions of the left lane line, right lane line, and lane center line must intersect at a point (yellow dot in the figure), recorded as point P1. Using P1 can roughly estimate the position of the lane center line.

image-20251203111250973

 

  • Open DEBUG_MODE_4 in the dynamic parameter configuration panel to display the connection between the centerline starting point and the lane line intersection point

    • The center dot is the intersection point P1 of the left and right lane lines (blue dotted line and green dotted line)
    • The green dot in the figure is the starting point of the vehicle body centerline, recorded as P2
    • The vehicle body centerline is recorded as L2, and the connection between the centerline starting point and the lane line intersection point is recorded as L1
  • When the vehicle body tilts to one side, the two line segments L1 and L2 in the image will show a deviation angle

image-20251203111444208

  • At this time, the lane straight maintenance problem can be abstracted to finding the deviation angle problem

image-20251203110129423

  • For example, when the vehicle head tilts to the right and the deviation angle exceeds a certain threshold, PID control is triggered to correct the vehicle head direction.

image-20251203105343965

 

3.2 Left and Right Lane Keeping

  • When the vehicle body deviates left and right from the lane centerline, according to the previously calibrated standard lane line position, the left and right deviation can be calculated. Through PID regulation, the vehicle body can be stabilized near the center position.

[!IMPORTANT]

  • Under ideal conditions, the vehicle body drives along the lane center, and the real-time lane lines will fit the calibrated standard lane lines (left and right dark blue line segments). In actual driving, there will be an angle between the standard lane lines and the real-time lane lines, so the deviation of the vehicle body relative to the lane centerline can be calculated by calculating the distance between the real-time lane line midpoint and the standard lane line, where:

    • d2 is the point-to-line segment distance between the left lane line midpoint and the calibrated lane line
    • d1 is the point-to-line segment distance between the right lane line midpoint and the calibrated lane line
  • Therefore, the deviation distance error of the vehicle body relative to the lane centerline can be equivalent to: (d2-d1)/2

    • d1 and d2 have positive and negative values. When the real-time lane line is on the left side of the calibrated lane line, it is negative.

image-20251203112812979

 

3.3 Curve Turning

image-20251203120831825

 

  • When the vehicle body enters a curve for turning, the vehicle body centerline will intersect with the left lane line in the camera perspective. Therefore, when there is an intersection point between the two, it proves that the vehicle body is close to the left lane line, and angular velocity control is used to turn the vehicle body.
  • Therefore, the length of the vehicle body centerline determines the timing of the vehicle entering the curve for turning.

image-20251203120734260

 

  • Another situation is that due to YOLO not detecting lane lines or camera field of view blind spots, no lane lines can be seen. In this case, the vehicle will maintain the turning state from the previous frame and perform in-place rotation at a slow angular velocity until lane lines appear in the image.

image-20251203121342970

 

 

 

4. Source Code Analysis

The logic source code of the program is located in the auto_drive.py program of the auto_drive package

xxxxxxxxxx
~/yahboomM3_ws/code_ws/src/auto_drive/auto_drive/auto_drive.py

 

  • The overall implementation program for processing lane lines is the handle_lane method in the AutoDrive class

    • Processing flow: Continuously obtain video frames from the image_queue queue, perform YOLO lane line detection to calculate vehicle body angle deviation and left-right deviation, then output speed through PID calculation to control vehicle body posture.
​x
def handle_lane(self)->None:
    '''Processing lane line recognition detection results'''
​
    while True:
        try:
            frame = self.lane_detect.image_queue.get(timeout=0.1)
        except queue.Empty:
            continue
        infer_start = time.time()
        results =self.lane_detect.get_infer_result(frame, stream=True)
        #Initialize default values
        left_box = None
        right_box = None
        left_candidates = []
        right_candidates = []
​
        for res in results:
            boxes = res.boxes  # Boxes object for bounding box outputs
            if self.DEBUG_MODE: frame = res.plot()
            if boxes is not None:
                for i in range(len(boxes)):
                    box_coords = boxes.xyxy[i].tolist()        # Get the bounding box coordinates (xyxy format: xmin, ymin, xmax, ymax)
                    lane=self.lane_detect.classify_lane_direction(frame,box_coords,debug=self.DEBUG_MODE)
                    if lane=="left":
                        left_candidates.append(box_coords)
                    elif lane=="right":
                        right_candidates.append(box_coords)
​
        if len(left_candidates)>0 :
            left_box = max(left_candidates, key=lambda box: box[3]) # Select the bounding box closest to the bottom (with the largest ymax).
        if len(right_candidates)>0:
            right_box = max(right_candidates, key=lambda box: ((box[2] - box[0])**2 + (box[3] - box[1])**2)**0.5)
​
        frame=self.__handle_lane_detect_result(left_box,right_box,frame)
        infer_end = time.time()
​
        self.frame_count_1 += 1
        curr_time = time.time()
        time_diff = curr_time - self.prev_time_1
        if time_diff >= 1.0:
            self.fps_1 = self.frame_count_1 / time_diff
            self.frame_count_1 = 0
            self.prev_time_1 = curr_time
        cv2.putText(frame,f"FPS: {self.fps_1:.2f}",(10, 25),cv2.FONT_HERSHEY_SIMPLEX,0.6,(0, 255, 0),1,)
​
        infer_time = (infer_end - infer_start) * 1000
        cv2.putText(frame, f"Infer: {infer_time:.1f} ms", (10, 45),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 1)
        cv2.imshow("Auto-Drive Panel", frame)
        cv2.waitKey(1)

 

  • The __handle_lane_detect_result method in the AutoDrive class is the main logic for implementing lane keeping
xxxxxxxxxx
    def __handle_lane_detect_result(self,left_box,right_box,frame):
        '''Lane centering processing'''
        error_mode = 99  
        angular_z=0.0
        error_angular = [0.0, 0.0]  
​
        if left_box is not None: k_left=self.lane_detect.draw_left_line(frame, left_box)
        if right_box is not None: k_right=self.lane_detect.draw_right_line(frame, right_box)
​
        if left_box is not None and right_box is not None and left_box[0]<right_box[0] :
            error_mode=0  
            frame,x_center,y_center=self.lane_detect.draw_center_point(frame,left_box,right_box,debug=self.DEBUG_MODE_4) #Draw the real-time lane center
            avg_offset=self.lane_detect.cal_point_to_lane_line_distance(left_box,right_box)      #Calculate the deviation of the car in the lane
            if self.DEBUG_MODE_3 : self.__calculate_init_error(avg_offset)                      #Initial error compensation
            error_angular=self.lane_detect.cal_error_angular(x_center,y_center)#Calculate the angular error between the vehicle body and the center point
            
        elif left_box is not None and right_box is None:
            error_mode=1
            self.lane_detect.prev_center=None
        elif right_box is not None and left_box is None :
            error_mode=2
            self.lane_detect.prev_center=None
        elif left_box is None and right_box is None:
            error_mode=3
            self.lane_detect.prev_center=None
​
        if self.lanekeeping_enable:
            '''Lane keeping mode'''
            if error_mode==0 :
                '''Both the left and right lane lines exist'''
                if abs(error_angular[1])> self.min_error_angular:
                    angular_z=self.pid_controller.pid_control(error_angular[1])
                    angular_z=min(angular_z,0.3)
                    angular_z=max(angular_z,-0.3)
                    self.__set_current_speed(linear_x=self.drive_speed,angular_z=angular_z)
                else:
                    linear_y=self.pid_controller_1.pid_control(avg_offset-10.18)
                    linear_y=min(linear_y,0.05)
                    linear_y=max(linear_y,-0.05)
                    self.__set_current_speed(linear_x=self.drive_speed,linear_y=linear_y)
​
            elif error_mode==1:
                '''Only the left lane line'''
                if_infer=self.lane_detect.IF_lane_intersection(left_box)
                if if_infer is not None:
                    # If infer_result is true, it means there is an intersection point, and control is then performed based on the angle deviation.
                    angular_z=self.angular_speed
                else:
                    if left_box[0]>self.lane_detect.start_point[0]:
                        angular_z=self.angular_speed
                    else:
                        angular_z=0.0
​
                self.__set_current_speed(linear_x=self.drive_speed,angular_z=angular_z)
            
            elif error_mode==2:
                '''Only the right lane line'''
                if right_box[0]<self.lane_detect.start_point[0]:
                    self.turn_right_conunt+=1
                    if self.turn_right_conunt>self.tr_threshold:
                        angular_z=-self.angular_speed
                        self.__set_current_speed(linear_x=0.1,angular_z=angular_z)
                        self.turn_right_conunt=0
                else:
                    self.turn_right_conunt=0
            elif error_mode==3:
                '''Neither the left nor the right lane lines exist'''
                if self.last_error_mode==1:
                    '''If you are in a blind spot and cannot see the left lane line in front of you, turn right'''
                    self.__set_current_speed(linear_x=0.0,angular_z=-0.15)
                elif self.last_error_mode==2:
                    '''If you are in a blind spot and cannot see the lane line on the right in front of you, turn left'''
                    self.__set_current_speed(linear_x=0.0,angular_z=0.09)
                elif self.last_error_mode==0:
                    self.__set_current_speed(linear_x=0.1)
            else:
                '''The rest of the situation'''
                self.__set_current_speed(linear_x=self.drive_speed,angular_z=0.0)
            
        self.last_error_mode=error_mode
​
        # Display angular deviation on the image 
        cv2.putText(frame, f"angle-dev: {error_angular[1]:.2f} rad", (10, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 255), 1)
        if self.DEBUG_MODE_4: self.lane_detect.draw_midline(frame)
        return frame

 

  • The program for calculating deviation angle and left-right deviation is as follows:
xxxxxxxxxx
        if left_box is not None and right_box is not None and left_box[0]<right_box[0] :
            error_mode=0  
            frame,x_center,y_center=self.lane_detect.draw_center_point(frame,left_box,right_box,debug=self.DEBUG_MODE_4) #Draw the real-time lane center
            avg_offset=self.lane_detect.cal_point_to_lane_line_distance(left_box,right_box)      #Calculate the deviation of the car in the lane
            if self.DEBUG_MODE_3 : self.__calculate_init_error(avg_offset)                      #Initial error compensation
            error_angular=self.lane_detect.cal_error_angular(x_center,y_center)#Calculate the angular error between the vehicle body and the center point

 

  • The calculation steps draw_center_point, cal_point_to_lane_line_distance, __calculate_init_error, cal_error_angular belong to the Lane_Detect class in yolov11_infer.py

 

  • draw_center_point is used to draw the connection between the real-time lane center point and the vehicle body centerline starting point
xxxxxxxxxx
    def draw_center_point(self,image,left_box,right_box,debug=True):
        '''Draw the center point of the lane and connect it with the starting point of the central axis of the vehicle's perspective'''
        x1l, y1l, x2l, y2l = map(int, left_box)
        x1r, y1r, x2r, y2r = map(int, right_box)
        left_p1 = (x1l, y2l)
        left_p2 = (x2l, y1l)
        right_p1 = (x1r, y1r)
        right_p2 = (x2r, y2r)
​
        k1, b1 = self._line_params(left_p1, left_p2)
        k2, b2 = self._line_params(right_p1, right_p2)
​
        # Calculate the intersection point 
        if abs(k1 - k2) < 1e-6:
            x_center, y_center = image.shape[1] // 2, image.shape[0] // 2
        else:
            x_center = int((b2 - b1) / (k1 - k2))
            y_center = int(k1 * x_center + b1)
            x_center_smooth, y_center_smooth=self.center_point_filter(x_center,y_center)
            if debug: cv2.line(image, (x_center_smooth,y_center_smooth), self.start_point, (100, 0, 0), 3)     #The line connecting the center point of the road estimation and the starting point of the central axis of the vehicle's viewing Angle
​
        if debug:
            cv2.circle(image, (x_center_smooth, y_center_smooth), 6, (0, 0, 255), -1)
            cv2.putText(image, f"center ({x_center_smooth},{y_center_smooth})",
                        (x_center_smooth + 10, y_center_smooth - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
​
        return image,x_center_smooth, y_center_smooth

 

  • cal_point_to_lane_line_distance method is used to calculate the left and right deviation of the vehicle body in the lane
xxxxxxxxxx
    def cal_point_to_lane_line_distance(self, left_box, right_box):
        '''
        Calculate the left and right deviations of the vehicle body in the lane
        '''
        x1l, y1l, x2l, y2l = map(int, left_box)
        x1r, y1r, x2r, y2r = map(int, right_box)
        
        left_p1 = (x1l, y2l)
        left_p2 = (x2l, y1l)
        
        right_p1 = (x1r, y1r)
        right_p2 = (x2r, y2r)
        
        left_point = np.array(self.left_lane_center_point)
        right_point = np.array(self.right_lane_center_point)
        
        left_distance = self._point_to_infinite_line_distance_with_direction(left_point, left_p1, left_p2)
        right_distance = self._point_to_infinite_line_distance_with_direction(right_point, right_p1, right_p2)
        avg_offset = (left_distance - right_distance) / 2
        return avg_offset

 

  • Curve turning program implementation

In the previous __handle_lane_detect_result method, the corresponding program segment is as follows. If the vehicle body centerline intersects with the left lane line, the vehicle body turns at self.angular_speed angular velocity.

xxxxxxxxxx
            elif error_mode==1:
                '''Only the left lane line'''
                if_infer=self.lane_detect.IF_lane_intersection(left_box)
                if if_infer is not None:
                    # If infer_result is true, it means there is an intersection point, and control is then performed based on the angle deviation.
                    angular_z=self.angular_speed
                else:
                    if left_box[0]>self.lane_detect.start_point[0]:
                        angular_z=self.angular_speed
                    else:
                        angular_z=0.0
​
                self.__set_current_speed(linear_x=self.drive_speed,angular_z=angular_z)
xxxxxxxxxx
    def IF_lane_intersection(self, left_box):
        """
        Determine whether the left lane line intersects the vehicle's central axis and return to the intersection point
        """
        x1l, y1l, x2l, y2l = map(int, left_box)
​
        left_p1 = (x1l, y2l)
        left_p2 = (x2l, y1l)
        x1, y1 = self.start_point
        x2, y2 = self.end_point
        x3, y3 = left_p1
        x4, y4 = left_p2
​
        denom = (x1 - x2)*(y3 - y4) - (y1 - y2)*(x3 - x4)
        if denom == 0:
            return None  
​
        t = ((x1 - x3)*(y3 - y4) - (y1 - y3)*(x3 - x4)) / denom
        u = ((x1 - x3)*(y1 - y2) - (y1 - y3)*(x1 - x2)) / denom
​
        if 0 <= t <= 1 and 0 <= u <= 1:
            inter_x = x1 + t * (x2 - x1)
            inter_y = y1 + t * (y2 - y1)
            return (inter_x, inter_y)
        else:
            return None

 

  • When lane lines cannot be detected, trigger self-rescue mechanism and slowly rotate to find lane lines based on the previous turning state
xxxxxxxxxx
            elif error_mode==3:
                '''Neither the left nor the right lane lines exist'''
                if self.last_error_mode==1:
                    '''If you are in a blind spot and cannot see the left lane line in front of you, turn right'''
                    self.__set_current_speed(linear_x=0.0,angular_z=-0.15)
                # elif self.last_error_mode==2:
                #     '''If you are in a blind spot and cannot see the lane line on the right in front of you, turn left'''
                #     self.__set_current_speed(linear_x=0.0,angular_z=0.09)
                elif self.last_error_mode==0:
                    self.__set_current_speed(linear_x=0.1)
            else:
                '''The rest of the situation'''
                self.__set_current_speed(linear_x=self.drive_speed,angular_z=0.0)

 

Lane Detection
Traffic Sign Recognition

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文