> Markdown version of https://www.imranjan.cn/projects/p-eyetouch for AI agents and other programs. It carries the same public information as the web page. Built 2026-11-30.

September 2025 - October 2025

# Eye Touch - Real-time Eye Tracking and Gaze Control System

## Wearable Electronic Technology - Course Project

Tags: Software System Development, MediaPipe, Scikit-learn

![Eye Touch - Real-time Eye Tracking and Gaze Control System](https://www.imranjan.cn/images/projects/eyetouch-2025/cover.webp)

Click to enlarge

#### Project Resources

The complete Python source code, database file, configuration files, and more are available in the GitHub repository. An executable installer is also provided, which includes the full runtime environment and can be used without any extra configuration.

[ View Full Source Code](https://github.com/narmi924/Eye%5FTouch)
[ Download Installer (V2.0)](https://github.com/narmi924/Eye%5FTouch/releases/download/V2.0/EyeTouch%5FSetup%5Fv2.0.exe)

### Team Information

#### Advisor

Prof. Wenbin Chen (School of Optoelectronic Science and Engineering, UESTC)

#### Team Members

- Me - Software System Development, Human-Computer Interaction
- Yanbo Wu (School of Optoelectronic Science and Engineering, UESTC) - Pupil Center Detection Algorithm
- Sunzhi Wen (School of Optoelectronic Science and Engineering, UESTC) - Trajectory Recognition and Calibration

### Project Background

Eye-tracking technology holds immense potential in fields like human-computer interaction, medical diagnostics, and psychological research. However, traditional solutions often rely on expensive, specialized hardware (e.g., Tobii eye trackers costing thousands of dollars), severely limiting their widespread adoption and application.

Our project stemmed from a bold idea: could we build a low-cost, easily implementable eye-tracking system using only a standard laptop camera and advanced software algorithms? This concept emerged during our 'Wearable Electronic Technology' course. We aimed to lower the barrier to entry for eye-tracking technology, providing a viable solution for educational demonstrations, assistive interaction design, and low-budget scientific research.

The core objective is to achieve a 'pixel-to-intent' conversion: capturing eye images via a camera, identifying pupil positions, establishing a coordinate mapping relationship for precise eye-gaze-to-screen-coordinate correspondence, and ultimately building a complete interactive eye-tracking system.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/highlight-1.svg)

##### Low-Cost Solution

Requires only a standard laptop camera, eliminating the need for expensive specialized hardware and significantly lowering the entry barrier.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/highlight-2.svg)

##### Independent Process Architecture

Resolves DLL conflicts through an independent process architecture, enabling high-precision calibration and real-time eye tracking.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/highlight-3.svg)

##### Multi-Domain Applications

Valuable for accessibility aids, HCI research, gaming, entertainment, education, and training.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/highlight-4.svg)

##### Data Caching

Supports local caching of the latest calibration data to avoid repetitive calibration and improve system efficiency.

### System Architecture

Early in the project, we faced a critical issue: a severe DLL conflict between the PyQt6 UI library and the MediaPipe vision processing library. They depended on different versions of the C++ runtime, causing the program to crash instantly upon initializing MediaPipe. This was an architectural roadblock that had to be solved first.

#### Core Challenge: DLL Conflict

Symptom: Program crashes immediately on startup with a "DLL load failed" error.

Root Cause: Both libraries depend on different C++ runtime versions, which cannot be loaded in the same process.

#### Our Solution: Independent Process Architecture

To completely isolate the conflict, I designed an independent process architecture. The main process is dedicated to UI rendering and user interaction, while all computationally intensive and conflicting vision processing tasks are offloaded to a separate child process.

![System Architecture Diagram](https://www.imranjan.cn/images/projects/eyetouch-2025/system architecture diagram.png)Eye Touch System Architecture Diagram

#### Communication Flow Design

The main process launches the child process, which initializes MediaPipe. Status is communicated via JSON, and the main process updates the UI accordingly.

#### Communication Flow Design

python

code.python

```python
# 主进程启动子进程
process = subprocess.Popen(
    ["gaze_tracking_worker.exe", "--command", "track"],
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE,
    text=True
)

# 主进程读取状态（在循环中）
while process.poll() is None:
    line = process.stdout.readline()
    if line.startswith("STATUS:"):
        status = json.loads(line[7:])  # 去掉"STATUS:"前缀
        handle_status(status)  # 更新UI

# 状态消息格式示例
status = {
    "type": "calibration_progress",
    "message": "校准进度：5/25 - 请注视红点",
    "data": {
        "current": 5,
        "total": 25
    }
}

# 主进程发送控制命令
process.stdin.write(json.dumps({"command": "stop"}) + "\n")
process.stdin.flush()
```

#### Architectural Advantages

Stability: The main UI process remains stable even if the child process crashes due to an algorithm error. It can provide a user-friendly error message and attempt a restart. Performance: Separates UI rendering from computation, preventing blocking. Extensibility: Easy to add new algorithm modules or features.

### Algorithm Principles

The core problem in eye tracking is converting the pupil's coordinates from the camera's view into the user's gaze point on the screen. This involves a complex non-linear mapping, complicated by factors like camera angle, lens distortion, and eyeball curvature.

#### **Step 1: Pupil Detection Algorithm**

We designed a robust, dual-safeguard detection process:

#### Step 1: Pupil Detection Algorithm

python

code.python

```python
def detect_pupil_centroid(self, eye_roi):
    """
    稳健的瞳孔中心检测
    方法1：阈值分割 + 轮廓质心法（优先）
    方法2：强度加权质心法（备用）
    """
    if eye_roi is None or eye_roi.size == 0:
        return None

    # 第一步：预处理
    gray = cv2.cvtColor(eye_roi, cv2.COLOR_BGR2GRAY)
    k = max(3, int(min(eye_roi.shape[:2]) / 8) | 1)
    gray = cv2.GaussianBlur(gray, (k, k), 0)

    # 第二步：自适应阈值分割（Otsu方法）
    try:
        _, thresh = cv2.threshold(gray, 0, 255,
                                cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    except:
        _, thresh = cv2.threshold(gray, 40, 255, cv2.THRESH_BINARY_INV)

    # 第三步：形态学操作（去除噪点）
    mk = max(3, int(min(eye_roi.shape[:2]) / 20) | 1)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (mk, mk))
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)

    # 第四步：寻找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 第五步：选择最大轮廓（假设是瞳孔）
    if contours:
        c = max(contours, key=cv2.contourArea)
        if cv2.contourArea(c) >= 10:
            M = cv2.moments(c)
            if M["m00"] != 0:
                cx = int(M["m10"]/M["m00"])
                cy = int(M["m01"]/M["m00"])
                return (cx, cy)

    # 备用方案：强度加权质心法
    inv = 255 - gray
    sum_inv = float(np.sum(inv)) + 1e-6
    coords = np.indices(gray.shape)
    cx = int(np.sum(coords[1] * inv) / sum_inv)
    cy = int(np.sum(coords[0] * inv) / sum_inv)
    h, w = gray.shape
    if 0 <= cx < w and 0 <= cy < h:
        return (cx, cy)
    return None
```

Key techniques include: Otsu's adaptive thresholding to automatically find the best segmentation threshold for varying light conditions; morphological operations to remove noise from eyelashes and reflections; contour moments to precisely locate the pupil boundary and calculate its geometric center; and a fallback intensity-weighted centroid method to ensure output even in complex conditions.

#### **Step 2: 5×5 Grid Calibration System**

We used a machine learning approach to establish the coordinate mapping. A 5×5 grid of 25 points guides the user to gaze at each red dot, where we collect 55 frames of image data to calculate the average pupil coordinates.

![5×5 Grid Calibration System - 25 calibration points](https://www.imranjan.cn/images/projects/eyetouch-2025/standardize page.png)5×5 Grid Calibration System - 25 calibration points

#### **Step 3: Polynomial Regression Modeling**

Using the calibration data, we fit this non-linear mapping with a 2nd-degree polynomial regression:

#### Step 3: Polynomial Regression Modeling

python

code.python

```python
# 步骤1：归一化摄像头坐标（防止数值过大影响回归）
X = np.array(calib_cam, dtype=np.float32)
X_norm = np.stack([X[:,0] / float(self.CAM_W),
                   X[:,1] / float(self.CAM_H)], axis=1)

# 步骤2：多项式特征扩展（2次多项式）
# 原始特征：[x, y]
# 扩展特征：[1, x, y, x^2, xy, y^2]
poly = PolynomialFeatures(degree=2, include_bias=True)
X_poly = poly.fit_transform(X_norm)

# 步骤3：分别对x和y建立回归模型
reg_x = LinearRegression().fit(X_poly, Y[:,0])  # 预测屏幕x坐标
reg_y = LinearRegression().fit(X_poly, Y[:,1])  # 预测屏幕y坐标

# 步骤4：保存模型以备复用
self.save_calibration(poly, reg_x, reg_y)

# 数学原理：
# screen_x = w0 + w1*x + w2*y + w3*x² + w4*xy + w5*y²
# screen_y = v0 + v1*x + v2*y + v3*x² + v4*xy + v5*y²
```

Core features: Normalization of camera coordinates to the 0-1 range for numerical stability; feature expansion from \[x, y\] to 6 features \[1, x, y, x², xy, y²\]; independent modeling for x and y coordinates; and model persistence to save calibration data and avoid repetition.

#### **Step 4: Kalman Filter Smoothing**

The raw tracking results can be jittery, so we introduced a Kalman filter for smoothing:

#### Step 4: Kalman Filter Smoothing

python

code.python

```python
# 初始化卡尔曼滤波器
# 4个状态变量: [x, y, vx, vy] (位置x, 位置y, 速度x, 速度y)
# 2个观测变量: [x, y] (只能观测到位置)
kf = cv2.KalmanFilter(4, 2)

# 状态转移矩阵: 匀速运动模型
# x_new = x_old + vx, y_new = y_old + vy
kf.transitionMatrix = np.array([[1,0,1,0], [0,1,0,1],
                                [0,0,1,0], [0,0,0,1]], np.float32)

# 观测矩阵：只能观测位置，不能直接观测速度
kf.measurementMatrix = np.array([[1,0,0,0], [0,1,0,0]], np.float32)

# 噪声协方差
kf.processNoiseCov = np.eye(4, dtype=np.float32) * 1e-4     # 过程噪声（很小）
kf.measurementNoiseCov = np.eye(2, dtype=np.float32) * 1e-2 # 观测噪声（中等）

# 在追踪循环中：
# 1. 预测
prediction = kf.predict()

# 2. 获取当前观测值
measurement = np.array([[screen_x], [screen_y]], np.float32)

# 3. 校正
kf.correct(measurement)

# 4. 输出平滑后的结果
smoothed_point = (prediction[0], prediction[1])
```

Optimization effects: State variables \[x, y, vx, vy\] include position and velocity; a constant velocity motion model predicts the next frame's position; observation fusion combines predicted and actual values; real-time jitter was reduced from ±50 pixels to ±10 pixels.

### Core Features Showcase

#### Modern Main Interface

I adopted the Fluent Design style to create a modern and clear main interface. Users can intuitively see the camera and algorithm status and launch core functions with one click. The design emphasizes user experience with a welcome window, status monitoring, and helpful tips.

UI StyleFluent Design

Status MonitoringReal-time camera & algorithm status

Quick AccessOne-click start for tracking & control

![Modern Main Interface Design](https://www.imranjan.cn/images/projects/eyetouch-2025/home-page.png)Modern Main Interface Design

![Camera Check and Test Interface](https://www.imranjan.cn/images/projects/eyetouch-2025/camera test page.png)Camera Check and Test Interface

#### Camera Check System

Before starting eye tracking, the system performs a camera check to ensure it's functioning correctly. This is a prerequisite for all subsequent features, including live preview and pupil detection monitoring. If the camera fails, detailed error messages and suggestions are provided.

Live PreviewReal-time camera feed display

Status MonitoringLive feedback on pupil detection status

Error HandlingDetailed diagnostics and suggestions

#### Intelligent Calibration System

This is the first and most critical step. Our 5×5 grid calibration system guides users to quickly complete data collection, laying a solid foundation for accurate tracking. Each point collects 55 frames of data for averaging, ensuring stability and accuracy.

Calibration Points25 points (5×5 grid)

Sample Count55 samples per point

Regression Algorithm2nd-degree polynomial

![5×5 Grid Calibration System](https://www.imranjan.cn/images/projects/eyetouch-2025/standardize page.png)5×5 Grid Calibration System

![Real-time Eye Trajectory Display](https://www.imranjan.cn/images/projects/eyetouch-2025/tracking page after standardize.png)Real-time Eye Trajectory Display

#### Real-time Trajectory Display

After calibration, the system tracks the user's gaze in real time. I designed a fading trail effect where new points are clear and old ones fade, creating a smooth and uncluttered visual. A Kalman filter is used to smooth the trajectory and eliminate high-frequency jitter.

Render Frame Rate100 FPS

Trajectory Length128 points

Filtering AlgorithmKalman Filter

#### Gaze Control System

This is key to turning tracking into interaction. We designed a 9-grid layout where users can launch applications by gazing at a tile for 3 seconds, enabling true "eye operation." A progress bar provides feedback to prevent accidental triggers.

Control Area9-grid layout

Trigger Time3-second dwell

Supported AppsQQ, WeChat, Camera, etc.

![9-Grid Gaze Control System](https://www.imranjan.cn/images/projects/eyetouch-2025/gaze control page.png)9-Grid Gaze Control System

![Eye-Controlled Tic-Tac-Toe Game](https://www.imranjan.cn/images/projects/eyetouch-2025/Tic-Tac-toe game page.png)Eye-Controlled Tic-Tac-Toe Game

#### Eye-Controlled Tic-Tac-Toe

To demonstrate the fun and utility of eye interaction, I developed a Tic-Tac-Toe game. Players make moves by gazing at the board squares to play against a simple AI. It's a great proof-of-concept for accessible entertainment and a foundation for more complex eye-gaze games.

Game TypeTic-Tac-Toe

Control MethodGaze Dwell

Opponent TypeSimple AI

#### System Settings

Provides comprehensive system configuration, including window modes, interface styles, and application paths. Users can personalize settings to their needs, with support for fullscreen and adaptive modes, offering excellent customizability.

Window ModeFullscreen / Adaptive

App ConfigurationCustom paths

Save SettingsAuto-apply on next launch

![System Settings and Configuration](https://www.imranjan.cn/images/projects/eyetouch-2025/setting page.png)System Settings and Configuration

### Quantitative Metrics

We conducted comprehensive performance tests and user experience evaluations to validate the system's technical level and practicality through multi-dimensional metrics.

#### Technical Indicator Comparison

After multiple rounds of testing and optimization, our system met and, in some aspects, exceeded key technical targets.

Metric

Target

Actual

Notes

Calibration Speed

≤ 15s

\~20s

Sacrificed some speed for higher data collection accuracy.

Response Speed

≤ 5s

\~3s

Average time to achieve excellent recognition accuracy.

Recognition Accuracy

≤ 50px

≤ 20px

Average pixel error within 60 frames, better than expected.

Stability

±20° head rotation, accuracy drop ≤5%

Minimal impact

Achieved head movement-assisted eye tracking.

#### Performance Test Metrics

Tracking Frame Rate30 FPS

Trajectory Rendering100 FPS

Average Error< 50px

Processing Latency< 30ms

#### Accuracy Analysis

By testing accuracy with fixed points in different screen areas, we found the following error distribution:

Center Area

≤ 20px

Edge Areas

≤ 50px

Corner Areas

≤ 80px

#### Stability Testing

Long-duration runs and environmental adaptability tests verified the system's stability and reliability:

Continuous Runtime

\> 1 hour without crashing

Head Movement Adaptability

±20° rotation, accuracy drop < 5%

Lighting Adaptability

Success rate > 95% in normal indoor lighting

False Trigger Rate

< 1% (Gaze Control System)

### Problem Solving

During development, we encountered several technical challenges. Through in-depth analysis and creative thinking, we found effective solutions, providing valuable insights for similar projects.

##### Low Pupil Recognition Accuracy

**Problem:** Initial algorithms using circle and ellipse fitting were sensitive to reflections and noise, leading to unstable accuracy.

**Solution:** Switched to an image moment-based centroid method with a dual-safeguard of adaptive thresholding and morphological filtering, significantly improving accuracy.

**Highlight:** Achieved adaptive adjustment to lighting changes, enhancing system robustness.

##### DLL Conflict Causing Crashes

**Problem:** Conflicts between MediaPipe and PyQt6's underlying libraries prevented them from coexisting in the same process, causing frequent crashes.

**Solution:** I designed a dual-process isolation architecture with JSON communication, solving the problem at its root and ensuring stability.

**Highlight:** An innovative inter-process communication mechanism that perfectly integrated different tech stacks.

##### Camera Resource Release Failure

**Problem:** The Windows OS doesn't support simultaneous camera access by multiple modules, causing resource conflicts and functional switching failures.

**Solution:** Implemented dynamic resource management that releases and then requests the camera during function switches, with a 10-attempt retry mechanism.

**Technical Highlights:** An intelligent retry mechanism and resource management strategy that ensured system reliability.

### Complete Demonstration

Complete Demonstration of the Eye Touch Interaction System

#### Demo Highlights

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/demo-1.svg)

##### System Startup & Main Interface Intro

User-friendly main interface design, functions at a glance.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/demo-2.svg)

##### 5×5 Grid Calibration Process

Intelligent calibration system for rapid data collection.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/demo-3.svg)

##### Real-time Eye-Tracking Effect

Ultra-smooth 100 FPS trajectory rendering display.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/demo-4.svg)

##### Gaze Control Operation Demo

9-grid layout enabling gaze-based operations.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/demo-5.svg)

##### Eye-Tracking Game Experience

Tic-Tac-Toe game demonstrates interaction potential.

![](https://www.imranjan.cn/images/projects/eyetouch-2025/icons/demo-6.svg)

##### System Settings & Configuration

Complete personalized configuration options.

### Project Summary

Through this project, we successfully demonstrated that a viable eye-tracking system can be built using only a standard laptop camera and software algorithms. From the initial course idea to the final system, we not only solved technical challenges but also explored new possibilities in human-computer interaction.

Completion DateOctober 16, 2025

Project Grade92

Course Grade93

![$t('eyetouch.sections.summary.result3Label')](https://www.imranjan.cn/images/projects/eyetouch-2025/grade-certificate.webp)Course Grade

#### Takeaways and Insights

##### Technical Innovation Breakthrough

**Highlights:** An independent process architecture to solve DLL conflicts, high-precision calibration, and ultra-smooth 100 FPS rendering, showcasing a complete 'pixel-to-intent' technical chain.

**Innovative Value:** The dual-process design provides an effective solution for integrating similar conflicting tech stacks.

##### User Experience Optimization

**Design Philosophy:** A Fluent Design interface, an intelligent calibration system, and intuitive gaze control operations open new possibilities for accessibility technology.

**User Value:** Lowers the barrier to entry for eye-tracking, allowing more users to experience its convenience.

##### Demonstrated Application Value

**Application Fields:** Accessibility aids, HCI research, gaming, and education, laying the groundwork for low-cost eye-tracking applications.

**Social Impact:** Provides a new interaction method for individuals with disabilities, advancing accessibility technology.

Thanks to my teammates' efforts, I will be continuing research on real-time eye-tracking technology for my graduation project under the guidance of Professor Chen Wenbin.

## Other pages

- [Home](https://www.imranjan.cn/index.md)
- [About me](https://www.imranjan.cn/about.md)
- [Projects](https://www.imranjan.cn/projects.md)
- [Photography](https://www.imranjan.cn/gallery.md)
- [LCIMS Cloud](https://www.imranjan.cn/projects/p-lcims.md)
- [imranjan.cn](https://www.imranjan.cn/projects/p-portfolio.md)
- [Open-source tools](https://www.imranjan.cn/projects/p-open-source.md)
- [Gatehouse](https://www.imranjan.cn/projects/p-gatehouse.md)
- [PlusOne](https://www.imranjan.cn/projects/p-plusone.md)
- [Gantry](https://www.imranjan.cn/projects/p-gantry.md)
- [BYOF Agent](https://www.imranjan.cn/projects/p-byof-agent.md)
- [Shopping Copilot by KI](https://www.imranjan.cn/projects/p-shopping-copilot.md)
- [Look2Act](https://www.imranjan.cn/projects/p-look2act.md)
- [AccessAudit - On-Chain Access Approval & Audit System](https://www.imranjan.cn/projects/p-accessaudit.md)
- [China Collegiate Computer Competition—Mobile Application Innovation Contest](https://www.imranjan.cn/projects/p-yigui.md)
- [Nilufar Restaurant Expense Management System](https://www.imranjan.cn/projects/p-nilufar.md)
- [Voice-Interactive LED Light Panel](https://www.imranjan.cn/projects/p-led.md)
- ["Mengsheng Cup" Electronic Design Competition](https://www.imranjan.cn/projects/p-msb.md)
- [NUS SOC SWS 2024](https://www.imranjan.cn/projects/p-nus.md)

中文版本：https://www.imranjan.cn/zh/projects/p-eyetouch.md
