yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
MicroROS V2 Robot Car📖
01.Introduction
  • 0.Unboxing Video
  • 1. Readme Learning Route
  • 2. Must Read Before Use
  • 3. Introduction to MicroROS V2 Control Board
  • 4. Introduction to LiDAR
  • 5. Introduction to ESP32 Camera Module
  • 6. FAQ
  • 7. About Charging
02.Assembly course
  • Assembly Video
03.Preparation
  • 1. Quickly Start
  • 2. Write Firmware
  • 3. Install VM and Start System
  • 4. Configure VM and Connect Robot
  • 5. Connect to MicroROS Agent
  • 6. Change Ubuntu System Language to English
04.Quick start control course
  • 1. VM Keyboard Remote Control
  • 2. VM Handle Remote Control
  • 3. USB Handle Control
05.Robot control course
  • 1. Robot Information Release
  • 2. Robot Keyboard Control
  • 3. Robot Handle Control
  • 4. Robot State Estimation
  • 5. Linear Speed Calibration
  • 6. Angular Velocity Calibration
  • 7. Robot URDF Model
06.Lidar course
  • 1. Precautions for LiDAR Mapping and Navigation
  • 2. Lidar Avoid
  • 3. Lidar Following
  • 4. Lidar Guard
  • 5. Lidar Patrol
  • 6. Gmapping Mapping
  • 7. Cartographer Mapping
  • 8. Cartographer Quickly Repositioning Navigation
  • 9. Slam Toolx Mapping
  • 10. Navigation2 Single Point Navigation
  • 11. Navigation2 Multi Point Navigation
  • 12. Ros Robot App Mapping And Navigation
07.Road network planning
  • 1. Introduction to Road Network Planning and Quick Start
  • 2. Build a Pose Map
  • 3. Road Network Annotation
  • 4. Planning and Navigation Between Road Networks
  • 5. Road Network Navigation in Any Pose
  • 6. Path Replanning
08.Vision basic course
OpenCV Image Processing
  • 1. Introduction to OpenCV Source CV
  • 2. Open Source CV Geometric Transformation
  • 3. Open Source CV Image Processing and Drawing Text Line Segments
  • 4. Open Source CV Image Beautification
09.Visual General Course (For Standard&Superior version)
1. ESP32 Visual Recognition Module Configuration
  • 1. Serial Port Configuration WiFi Instructions
  • 2. Use ESP32 Camera Module in Robot Car
  • 3. Servo PTZ Calibration
2. OpenCV Visual Recognition
  • 1. Human Pose Estimation
  • 2. Object Detection
  • 3. AR Vision
  • 4. QR Code
  • 5. Color Recognition
  • 6. Facial Recognition
  • 7. AprilTag Machine Code Recognition
3. Mediapipe Visual Recognition
  • 1. Hand Detection
  • 2. Pose Detection
  • 3. Holistic Detection
  • 4. Facial Detection
  • 5. Facial Recognition
  • 6. Facial Special Effects
  • 7. 3D Object Recognition
  • 8. Brush
  • 9. Gesture Recognition
  • 10. Palm Target Localization
  • 11. Fingertip Trajectory Recognition
4. Yolov11&26 Visual Recognition
  • 1. YOLO Environment Setup
  • 2. CLI Usage
  • 3. Object Detection
  • 4. Instance Segmentation
  • 5. Pose Estimation
  • 6. Image Classification
  • 7. Oriented Bounding Boxes Object Detection
  • 8. Model Prediction
10.Visual Advanced Course (Just for Standard version)
1. Visual Control
  • 1. QR Code Recognition Control Action
  • 2. AprilTag Control Car Action Group
  • 3. Gesture Control Car Action Group
  • 4. Visual Line Tracking
2. Visual Tracking
  • 1. Color Tracking
  • 2. Facial Tracking
  • 3. QR Code Tracking
  • 4. Object Recognition And Tracking
  • 5. Mediapipe Palm Tracking
  • 6. Mediapipe Gesture Tracking
  • 7. Mediapipe Human Pose Tracking
  • 8. KCF Object Tracking
  • 9. AprilTag Machine Code Tracking
3. Visual Following
  • 1. Color Follow
  • 2. Face Follow
  • 3. QR Code Follow
  • 4. Mediapipe Palm Follow
  • 5. Mediapipe Gesture Follow
  • 6. Mediapipe Human Posture Follow
  • 7. AprilTag Machine Code Follow
  • 8. Object Follow
11.Visual Advanced Course (Just for Superior version)
1. Visual Control
  • 1. QR Code Recognition Control Action
  • 2. AprilTag Control Car Action Group
  • 3. Gesture Control Car Action Group
  • 4. Visual Line Tracking
2. Visual Tracking
  • 1. Color Tracking
  • 2. Facial Tracking
  • 3. QR Code Tracking
  • 4. YOLO Object Recognition and Tracking
  • 5. Mediapipe Palm Tracking
  • 6. Mediapipe Gesture Tracking
  • 7. Mediapipe Human Pose Tracking
  • 8. KCF Object Tracking
  • 9. AprilTag Machine Code Tracking
3. Visual Follow
  • 1. Color Follow
  • 2. Face Follow
  • 3. QR Code Follow
  • 4. Mediapipe Palm Follow
  • 5. Mediapipe Gesture Follow
  • 6. Mediapipe Human Pose Follow
  • 7. AprilTag Machine Code Follow
  • 8. Object Follow
12.AI Large Model Basic and Applications Course
1. AI Large Model Preparation
  • 1.AI Large Model Preparation
2. AI Large Model Basic Course
  • 1. AI Large Model Types and Principles
  • 2. RAG Retrieval Augmented and Training Samples
  • 3. Embodied Intelligent System Architecture
  • 4. Embodied Intelligence Core Source Code
3. AI Large Model Development
  • 1. Register Model Service Account
  • 2. Configure API KEY
  • 3. Dify Introduction
  • 4. Dify Basic Features
  • 5. RAG Knowledge Base Deployment
  • 6. AI Application Development Chatbot
  • 7. RAG Knowledge Base and Chatbot
  • 8. AI Agent Workflow
4. AI Large Model (Text Version)
  • 1. Semantic Understanding and Instruction Following
  • 2. Multimodal Visual Understanding
  • 3. Multimodal Visual Understanding + Basic Control
  • 4. Multimodal Visual Understanding + Object Following
  • 5. Multimodal Visual Understanding + Visual Line Following
  • 6. Multimodal Visual Understanding + SLAM Navigation
  • 7. Multimodal Visual Understanding + SLAM Navigation + Visual Line Following
  • 8. Multimodal Visual Understanding + SLAM Navigation + Object Following
  • 9. Intent Inference + Multimodal Visual Understanding + SLAM Navigation
13.Openclaw Basics Course
  • 1. Openclaw Introduction
  • 2. Openclaw Core Concepts
  • 3. Openclaw Api-Key Configuration
  • 4. Openclaw Switching Models
  • 5. Openclaw System Prompt
  • 6. Openclaw Common CLI Command
14. Openclaw Interaction Course
  • 1. Openclaw Webchat Interaction
  • 2. Openclaw Tui Interaction
  • 3. Openclaw Whatsapp Interaction
15.Openclaw Development Course
  • 1. Openclaw Robot Mcp Service Integration
  • 2. Robot CLI Command Tools
  • 3. Robot-Control Plugin Tools
  • 4. Openclaw Skills Development
  • 5. Openclaw Scheduled Tasks
  • 6. Openclaw Multi Agent System
  • 7. Openclaw Proactive Interaction
  • 8. Openclaw Vector Memory
16.Openclaw Embodied Intelligence Course
  • 1. OpenClaw Natural Interaction + Basic Control
  • 2. OpenClaw Natural Interaction + Slam Navigation
  • 3. OpenClaw Natural Interaction + Multimodal Visual Understand
  • 4. OpenClaw Natural Interaction + Multimodal Visual Understand + Slam Navigation + Visual Follow
  • 5. OpenClaw Natural Interaction + Multimodal Visual Understand + Slam Navigation + Visual Track
17.Multi-machine Course
  • 1. Multi Machine Handle Control
  • 2. Multi Machine Keyboard Control
  • 3. Multi Machine Navigation
18.MicroROS-V2 Control Board Development Environment
  • 1. Set Up the ESP32-IDF Development Environment
  • 2. ESP32-IDF Configuration Tool
  • 3. ESP Flash Tool Flashing Firmware
  • 4. Install ESP32 Microros Components
  • 5. Install And Start Microros Agent
19.MicroROS-V2 Control Board ESP32 Basic Course
  • 1. Led Light Up
  • 2. Button Function
  • 3. Drive Buzzer
  • 4. Oled
  • 5. Usb Host Function
  • 6. Serial Communication
  • 7. Battery Voltage Detection
  • 8. Drive Pwm Servo
  • 9. Drive Motors
  • 10. Read Motor Encoder Data
  • 11. Pid Motor Speed Control
  • 12. Robot Kinematics Analysis Theory
  • 13. Read Imu Data
  • 14. Read Lidar Data
  • 15. Flash Data Storage
  • 16. Custom Partition Table
  • 17. Bluetooth Communication
  • 18. Wifi Connection
  • 19. ESP32 Visual Recognition Module
20.MicroROS-V2 Control Board Micro_ros Basic Course
  • 1. Publish Topics
  • 2. Subscribe To Topics
  • 3. Multi Topic Subscription And Publishing
  • 4. Subscribe To Buzzer Topic
  • 5. Subscribe To Pwm Servo Topic
  • 6. Subscribe To Speed Control Topic
  • 7. Publish Odometry Topic
  • 8. Publish Imu Data Topic
  • 9. Publish Lidar Data Topic
21. Linux System Course
  • 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
22.Docker Course
  • 1.Docker overview and docker installation
  • 2.Common commands for docker image containers
  • 3.Docker images deeply understand and publish images
23.ROS 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
Download
  • Mapping_APP(iOS_Android)
  • Code
  • Software_Tools
  • VM_System_File
  • 3D_Model_File
  • ESP32_Firmware
  • Dify LLM Base
  • Instruction_Manual
  • VMware
Download ZIP

Welcome to MicroROS V2 Robot Car repository

2. Facial Tracking

Facial Tracking (PTZ)

1. Experiment Objective

The PTZ pan-tilt tracks the face position, keeping the face at the center of the frame.

2. Experiment Principle

1. Key Terms

TermDescription
Visual TrackingDetects and continuously locks onto a target through a vision algorithm; only the pan-tilt follows, the car does not move
PTZ Pan-TiltA two-degree-of-freedom servo pan-tilt; s1 rotates horizontally and s2 tilts, controlled via the /cmd_ptz_angle topic
Haar CascadeAn OpenCV cascade classifier based on Haar features that detects face regions using a pretrained XML model
PD ControlProportional-derivative control; computes the pan-tilt angle step from the target offset (P term) and the offset change rate (D term)
DeadbandWhen the target offset is within the deadband pixel range, the pan-tilt does not move, avoiding continuous jitter caused by tiny errors
Histogram EqualizationApplies equalizeHist to the grayscale image to enhance contrast, improving the Haar detector's face detection rate under varying lighting

2. Technical Architecture

The facial tracking node face_tracker_ptz_node subscribes to the raw image topic /camera/image_raw of the ESP32 camera, detects face regions with the Haar Cascade classifier, manages the tracking lifecycle with a five-state machine (searching → tracking → lost → paused/identify), computes the pan-tilt angle step with a PD controller, and publishes to /cmd_ptz_angle to control the pan-tilt to track the face.

Detection pipeline: image conversion → orientation correction → scaled detection → grayscale conversion → histogram equalization → Haar detectMultiScale → multi-face selection strategy (largest area / nearest center) → target center EMA filter → PD pan-tilt control (fixed 20 Hz).

3. Core Topics Quick Reference

Firmware Uplink (Sensor Data)

TopicMessage TypeQoSDescription
/camera/image_rawsensor_msgs/msg/Imagebest_effortRaw image from the ESP32 camera

Firmware Downlink (Control Commands)

TopicMessage TypeQoSFieldRangeDirection
/cmd_ptz_anglegeometry_msgs/msg/Vector3best_effort + keep_last(1)x[-90, 90]°s1 horizontal servo angle
   y[-90, 20]°s2 tilt servo angle

3. Experiment Steps

1. Hardware Preparation

HardwareRequirement
PTZ version✅ Supported
No-PTZ version❌
Required peripheralsESP32 camera (pan-tilt) + PTZ servo

2. Start Agent + Camera + Joint Model (Terminal 1)

ros2 launch microros_v2_bringup car_base.launch.py

image-20260728161615714

3. Start Facial Tracking (Terminal 2)

xxxxxxxxxx
ros2 launch microros_v2_ptz_visual_control_pkg face_tracker_ptz.launch.py

image-20260728190800318

4. Operation Instructions

Workflow

After startup, the node runs through the main loop spin_once plus a fixed-rate image processing timer (image_processing_rate_hz = 30 Hz) and an independent pan-tilt control timer (control_rate_hz = 20 Hz):

1. Image reception and preprocessing

Subscribes to /camera/image_raw (QoS: BEST_EFFORT, KEEP_LAST); the image callback only converts and caches the raw Image. The main loop takes the latest frame at 30 Hz and applies horizontal/vertical flipping and rotation correction as needed.

2. Face detection (Haar Cascade)

Scales the image down by face_detection_scale (0.75), converts it to grayscale, optionally applies histogram equalization (enable_gray_equalize=true), and detects faces with the OpenCV Haar cascade classifier detectMultiScale. Detection parameters: scaleFactor=1.1, minNeighbors=5, minimum detection size 80×80 px.

3. Multi-face selection

If multiple faces are detected, the main target is chosen by the face_select_strategy:

  • largest (default): selects the face with the largest area
  • nearest_center: selects the face closest to the frame center

4. Target state management (five-state machine)

The node maintains 5 states: searching (searching) → tracking (tracking) → lost (lost) → can pause to paused or switch to identify (recognition only). With auto_start_tracking=true, the first detected face enters tracking automatically; with auto_reacquire_face=true, tracking resumes automatically once a face is re-detected after a loss.

5. Target center low-pass filter

Applies EMA low-pass filtering (α = target_smooth_alpha = 0.55) to the detected face center, reducing the effect of Haar detector box jitter on pan-tilt control.

6. PD pan-tilt control

Fixed-rate 20 Hz PD control: normalizes the pixel error (divided by the image half-width/half-height), computes the P+D step, clamps the step (±max_ptz_step = 1.2°), smooths the step (α = ptz_step_smooth_alpha = 0.35), smooths the angle (α = ptz_smooth_alpha = 0.75), and publishes to /cmd_ptz_angle.

Interaction

KeyFunctionDescription
SpaceTracking/pauseToggles between "tracking" and "paused"; keeps the current pan-tilt angle while paused
i / IRecognition modeOnly detects the face and draws the box, without controlling the pan-tilt
r / RReset targetClears the current face target and searches again
q / Q / ESCExitForce-exits the node process with os._exit(0)

On-screen overlay: The debug window shows the current state (searching/tracking/lost/paused/identify), frame rate (based on the header stamp or reception time), image latency, pan-tilt angle, PD parameters, and key hints in real time. All detected faces are drawn with thin yellow boxes; the primary target face is drawn with a thick green box + red center point, and the filtered target center is a purple hollow circle.

Safety and Edge Cases

  • Classifier load failure: If the Haar Cascade XML file (haarcascade_frontalface_default.xml) fails to load, an error log is recorded and the node does not crash
  • Target lost handling: When no face is detected for more than target_lost_timeout_sec (1.0 s) → switches to the lost state; if lost_target_stop=true, the filtered target state is cleared and the PD control resets
  • Auto re-acquisition: With auto_reacquire_face=true, a face re-detected after a loss resumes tracking automatically
  • Pan-tilt angle limiting: Horizontal [-90°, 90°], tilt [-90°, 20°]; initial homing to (0°, -45°)
  • Deadband protection: The step is forced to zero when the face offset is within the deadband (20 px)
  • Initial publish at startup: With publish_initial_ptz_command=true, the initial pan-tilt angle is published repeatedly 20 times at 0.2 s intervals to ensure the servos receive the homing command
  • Exit strategy: Press q/ESC to exit directly with os._exit(0); cv2.destroyAllWindows() is not called during cleanup to avoid the GUI backend hanging

5. How to Stop

Press Ctrl+C to stop Terminal 2 → Terminal 1 in order.

4. Experiment Observations

  • Searching (no face): The frame streams in real time with the state searching; the Haar classifier keeps scanning and the pan-tilt holds its initial angle (0°, -45°)
  • Face detected + auto tracking: Enters the tracking state automatically; the primary target face is drawn with a thick green box, the face center with a red point, and the filtered tracking point with a purple hollow circle; the pan-tilt follows the face smoothly
  • Multi-face scene: All detected faces are drawn with thin yellow boxes; the primary target selected by the strategy is highlighted with a thick green box
  • Face within the deadband: The step is zeroed and the pan-tilt stays still without jitter
  • Face briefly lost (<1 s): The last valid face target is retained and tracking is not interrupted
  • Face lost by timeout (>1 s): Enters the lost state, the PD state resets, and the pan-tilt stays at its last position; with auto_reacquire_face=true, tracking resumes automatically when a face is re-detected
  • Paused mode: The frame continues detecting and showing face boxes, but pan-tilt control is paused and holds the current angle

5. Program Analysis

Source code paths:

  • Launch: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/launch/face_tracker_ptz.launch.py
  • Node: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/microros_v2_ptz_visual_control_pkg/face_tracker_ptz_node.py
  • Haar classifier: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/config/haarcascade_frontalface_default.xml

1. Launch Parameters

Parameter definition files:

  • Launch: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/launch/face_tracker_ptz.launch.py
  • Node: ~/microros_ws/src/microros_v2_ptz_visual_control_pkg/microros_v2_ptz_visual_control_pkg/face_tracker_ptz_node.py
ParameterTypeDefault ValueDescription
image_topicstring/camera/image_rawRaw image input topic
ptz_command_topicstring/cmd_ptz_anglePan-tilt angle output topic
show_debug_windowbooltrueWhether to show the OpenCV debug window
window_namestringface_tracker_ptzOpenCV debug window name
face_cascade_filestringconfig/haarcascade_frontalface_default.xmlHaar face cascade classifier path
face_detection_scale_factorfloat1.1Haar detectMultiScale scale factor
face_min_neighborsint5Haar detectMultiScale minimum neighbors
face_min_width / face_min_heightint80 / 80 pxMinimum face detection size
face_detection_scalefloat0.75Image scale factor before face detection (0.1~1.0)
face_select_strategystringlargestMulti-face selection strategy: largest / nearest_center
enable_gray_equalizebooltrueWhether to apply histogram equalization to the grayscale image
pd_kp / pd_kdfloat0.7 / 0.25PD proportional/derivative gains
control_rate_hzfloat20.0 HzPan-tilt control publishing rate
image_processing_rate_hzfloat30.0 HzImage processing main-loop rate
deadband_x / deadband_yfloat20.0 / 20.0 pxHorizontal/vertical deadband
target_smooth_alphafloat0.55Face center low-pass filter coefficient
ptz_smooth_alphafloat0.75Pan-tilt angle low-pass filter coefficient
max_ptz_stepfloat1.2°Maximum single angle step
ptz_step_smooth_alphafloat0.35Step smoothing coefficient
target_lost_timeout_secfloat1.0 sTarget lost timeout
auto_start_trackingbooltrueStart tracking automatically after a face is detected
auto_reacquire_facebooltrueResume automatically when a face is re-detected after a loss
lost_target_stopbooltrueWhether to clear the filtered state after the target is lost
initial_horizontal_deg / initial_pitch_degfloat0.0° / -45.0°Initial pan-tilt angles
horizontal_min_deg / horizontal_max_degfloat-90.0° / 90.0°s1 horizontal servo angle range
pitch_min_deg / pitch_max_degfloat-90.0° / 20.0°s2 tilt servo angle range

2. Core Node Analysis

FaceTrackerPtzNode inherits from rclpy.node.Node and is the core implementation of facial tracking. The constructor, the pan-tilt control callback, and the PD computation method are shown below.

Constructor __init__

The constructor declares the ROS2 parameters, loads the Haar classifier, creates the publishers and subscribers, initializes the tracking state, and sets up the control timer:

​x
class FaceTrackerPtzNode(Node):
    """ROS2 face tracking PTZ control node."""
​
    def __init__(self) -> None:
        super().__init__("face_tracker_ptz_node")
​
        self.latest_image_lock = threading.Lock()
        self.target_state_lock = threading.Lock()
​
        self.latest_image_frame = None
        self.tracking_state = "searching"
​
        self._declare_ros_parameters()
        self._load_ros_parameters()
        self._reload_face_cascade_classifier()
​
        # Initial pan-tilt angles
        self.horizontal_angle_deg = self.initial_horizontal_deg
        self.pitch_angle_deg = self.initial_pitch_deg
​
        # Create the image subscriber (raw image)
        self.image_subscription = self.create_subscription(
            Image,
            self.image_topic_name,
            self.image_callback,
            QoSProfile(history=QoSHistoryPolicy.KEEP_LAST, depth=1,
                       reliability=QoSReliabilityPolicy.BEST_EFFORT,
                       durability=QoSDurabilityPolicy.VOLATILE),
        )
​
        # Create the pan-tilt angle publisher
        self.ptz_angle_publisher = self.create_publisher(
            Vector3, self.ptz_command_topic_name, 10
        )
​
        # Create the pan-tilt control timer (fixed rate, 20 Hz by default)
        self._recreate_ptz_control_timer(False)
​
        # Register the runtime dynamic tuning callback
        self.dynamic_parameter_callback_handle = self.add_on_set_parameters_callback(
            self.on_dynamic_parameter_update
        )
​
        # Initialize the OpenCV debug window
        self._initialize_debug_window()
​
        # Start repeated publishing of the initial pan-tilt angle
        if self.publish_initial_ptz_command:
            self._start_initial_ptz_publish_timer()

Pan-tilt control callback ptz_control_timer_callback

Triggered at a fixed rate (20 Hz); reads the target snapshot and runs PD control only in the tracking state:

xxxxxxxxxx
def ptz_control_timer_callback(self) -> None:
    if self.is_shutdown_requested:
        return
​
    current_time_sec = time.monotonic()
    time_delta_sec = current_time_sec - self.last_control_time_sec
    self.last_control_time_sec = current_time_sec
​
    if self.tracking_state != "tracking":
        self._reset_pd_control_state()
        return
​
    target_state = self._get_face_target_state_snapshot()
    if not self._is_target_snapshot_usable(target_state):
        self._handle_unusable_target_snapshot(target_state)
        return
​
    image_cx = float(target_state.image_width) * 0.5
    image_cy = float(target_state.image_height) * 0.5
​
    horizontal_error = float(target_state.filtered_target_center_x) - image_cx
    pitch_error = float(target_state.filtered_target_center_y) - image_cy
​
    self.calculate_ptz_angle_command(
        horizontal_error, pitch_error, time_delta_sec
    )
    self.publish_ptz_angle_command()

PD control core calculate_ptz_angle_command

Implements the complete PD control chain from the face offset to the pan-tilt angle step:

xxxxxxxxxx
def calculate_ptz_angle_command(
    self, horizontal_error_pixel, pitch_error_pixel, time_delta_sec
) -> None:
    # Deadband handling
    if abs(horizontal_error_pixel) <= self.deadband_x:
        horizontal_error_pixel = 0.0
    if abs(pitch_error_pixel) <= self.deadband_y:
        pitch_error_pixel = 0.0
​
    # Normalize the pixel error
    image_cx = float(self.latest_tracking_image_width) * 0.5
    image_cy = float(self.latest_tracking_image_height) * 0.5
    norm_x = horizontal_error_pixel / image_cx
    norm_y = pitch_error_pixel / image_cy
    time_delta_sec = max(float(time_delta_sec), 1.0e-3)
​
    # Derivative terms
    dx = (norm_x - self.previous_error_x) / time_delta_sec
    dy = (norm_y - self.previous_error_y) / time_delta_sec
​
    # PD step computation + limiting
    raw_x = (self.pd_kp * norm_x + self.pd_kd * dx) * self.max_ptz_step
    raw_y = (self.pd_kp * norm_y + self.pd_kd * dy) * self.max_ptz_step
    raw_x = clamp_numeric_value(raw_x, -self.max_ptz_step, self.max_ptz_step)
    raw_y = clamp_numeric_value(raw_y, -self.max_ptz_step, self.max_ptz_step)
​
    # Step EMA smoothing
    alpha = self.ptz_step_smooth_alpha
    step_x = (1.0 - alpha) * self.last_step_x + alpha * raw_x
    step_y = (1.0 - alpha) * self.last_step_y + alpha * raw_y
​
    # Save the control history
    self.previous_error_x = norm_x
    self.previous_error_y = norm_y
    self.last_step_x = step_x
    self.last_step_y = step_y
​
    # Direction reversal
    if self.reverse_horizontal_direction:
        step_x = -step_x
    if self.reverse_pitch_direction:
        step_y = -step_y
​
    # Compute the desired angle and clamp it
    desired_h = self.horizontal_angle_deg + step_x
    desired_p = self.pitch_angle_deg + step_y
    desired_h = clamp_numeric_value(desired_h, self.horizontal_min_deg,
                                    self.horizontal_max_deg)
    desired_p = clamp_numeric_value(desired_p, self.pitch_min_deg,
                                    self.pitch_max_deg)
​
    # Angle EMA smoothing
    ptz_alpha = self.ptz_smooth_alpha
    self.horizontal_angle_deg = (
        (1.0 - ptz_alpha) * self.horizontal_angle_deg + ptz_alpha * desired_h
    )
    self.pitch_angle_deg = (
        (1.0 - ptz_alpha) * self.pitch_angle_deg + ptz_alpha * desired_p
    )
​
    # Final limiting
    self.horizontal_angle_deg = clamp_numeric_value(
        self.horizontal_angle_deg, self.horizontal_min_deg,
        self.horizontal_max_deg)
    self.pitch_angle_deg = clamp_numeric_value(
        self.pitch_angle_deg, self.pitch_min_deg, self.pitch_max_deg)

6. Frequently Asked Questions

ProblemCauseSolution
Profile tracking unstableHaar Cascade is sensitive to frontal faces; profiles lack enough featuresFace the camera squarely, or reduce strictness by adjusting face_detection_scale_factor
Face not detectedInsufficient lighting or too far awayImprove the lighting, move closer to the camera, and make sure enable_gray_equalize=true
Wrong face tracked with multiple facesThe largest face is selected by default; the nearest-center strategy may suit betterros2 param set /face_follow_node face_select_strategy nearest_center
Pan-tilt responds slowlyptz_smooth_alpha too large causes over-smoothingReduce ptz_smooth_alpha (e.g., 0.5) to improve responsiveness
Color Tracking
QR Code Tracking

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

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文