Files
marker_detection/README.md
T
2026-11-02 09:50:57 +00:00

418 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<<<<<<< HEAD
# Marker Detection with YOLO26 on NVIDIA Jetson
End-to-end documentation: dataset creation, training, export and Jetson deployment.
> Items marked **[ ... ]** are still to be filled in. Screenshot notes are marked with 📷.
## 1. Project Overview
This project develops a custom **YOLO26** model to detect markers accurately in images and video streams. A dedicated marker dataset is used to train and evaluate the model. The trained model is deployed on an **NVIDIA Jetson Orin Nano** for efficient inference and real-time marker detection using GPU acceleration (TensorRT).
### 1.1 Objectives
- Build a custom marker dataset with bounding-box annotations.
- Train and evaluate a YOLO26 detection model.
- Export the model to ONNX and then to a TensorRT engine.
- Run real-time detection and tracking on a Jetson using a live camera.
### 1.2 Pipeline at a Glance
| Stage | Input | Output | Where it runs |
|---|---|---|---|
| 1. Dataset creation | Raw images / video frames | Annotated dataset (YOLO format) | PC |
| 2. Training | Dataset + pretrained YOLO26 | `best.pt` (renamed `marker_best.pt`) | Google Colab (GPU) |
| 3. Evaluation | Validation set | mAP, precision, recall, curves | Google Colab |
| 4. Export | `marker_best.pt` | `marker_best.onnx` | Google Colab / Jetson |
| 5. Optimization | ONNX | `marker_best.engine` (TensorRT) | Jetson |
| 6. Inference | Live camera / video | Real-time detections | Jetson |
## 2. Hardware and Software Requirements
### 2.1 Hardware
- NVIDIA Jetson Orin Nano (inference device)
- Logitech BRIO 100 USB camera
- Development PC / laptop with internet access
### 2.2 Software
| Component | Details |
|---|---|
| Model | YOLO26 (Ultralytics) |
| Training platform | Google Colab with GPU runtime |
| Annotation tool | **[ e.g., Roboflow / LabelImg / CVAT ]** |
| Export formats | ONNX, TensorRT (`.engine`) |
| Jetson OS | JetPack **[ version ]** |
| Languages / libraries | Python 3, Ultralytics, OpenCV, PyTorch |
## 3. Project Structure
The project lives on the Jetson at:
```
/home/jetson/projects_2026/Marker/Marker_detection
├── marker_detection.py # detection script
├── marker_tracking.py # tracking script (ByteTrack)
├── marker_detection_training.ipynb # training notebook (Jupyter)
└── models/
├── marker_best.pt # trained weights
├── marker_best.onnx # ONNX model
└── marker_best.engine # TensorRT engine
```
| File | Purpose |
|---|---|
| `marker_detection.py` | Real-time marker detection, also used to export the TensorRT engine |
| `marker_tracking.py` | Marker tracking with persistent IDs (ByteTrack) |
| `marker_detection_training.ipynb` | Notebook used for dataset loading, training, evaluation and ONNX export |
| `models/marker_best.pt` | Best trained YOLO26 weights |
| `models/marker_best.onnx` | Weights exported to ONNX |
| `models/marker_best.engine` | TensorRT engine built on the Jetson, loaded automatically at inference |
## 4. Step 1 – Dataset Creation
### 4.1 Collect Images
1. Capture images and video of the markers using the same type of camera used in deployment (BRIO 100) wherever possible.
2. Vary the conditions so the model generalizes:
- different distances and angles
- different lighting (bright, dim, shadows)
- different backgrounds
- partial occlusion and motion blur
3. If using video, extract frames at a fixed interval:
```python
import cv2, os
video_path = "marker_video.mp4"
out_dir = "raw_images"
os.makedirs(out_dir, exist_ok=True)
cap = cv2.VideoCapture(video_path)
count, saved = 0, 0
while True:
ok, frame = cap.read()
if not ok:
break
if count % 10 == 0: # save every 10th frame
cv2.imwrite(f"{out_dir}/frame_{saved:05d}.jpg", frame)
saved += 1
count += 1
cap.release()
print("Saved frames:", saved)
```
**Total images collected:** [ ... ]
### 4.2 Annotate the Images
1. Upload the images to the annotation tool.
2. Create the class (for example `marker`) **[ confirm class name(s) ]**.
3. Draw a tight bounding box around every marker in each image.
4. Review the labels and fix any inaccurate boxes.
📷 *Screenshot: annotation tool with bounding boxes*
### 4.3 Split the Dataset
The dataset was split into training, validation and test sets in a **70 / 20 / 10** ratio:
| Split | Share | Images |
|---|---|---|
| Train | 70% | [ ... ] |
| Validation | 20% | [ ... ] |
| Test | 10% | [ ... ] |
### 4.4 Export in YOLO Format
Export the dataset in **YOLO (Ultralytics) format**. The folder structure should look like this:
```
dataset/
├── images/
│ ├── train/
│ ├── val/
│ └── test/
├── labels/
│ ├── train/
│ ├── val/
│ └── test/
└── data.yaml
```
Each label file contains one line per object:
```
<class_id> <x_center> <y_center> <width> <height> (all values normalized 0–1)
```
Example `data.yaml`:
```yaml
path: /content/dataset
train: images/train
val: images/val
test: images/test
names:
0: marker
```
## 5. Step 2 – Model Training (Google Colab)
The full training workflow is in the notebook `marker_detection_training.ipynb`.
### 5.1 Set Up the Environment
1. Open Google Colab and select **Runtime → Change runtime type → GPU**.
2. Mount Google Drive (to load the dataset and save the weights):
```python
from google.colab import drive
drive.mount('/content/drive')
```
3. Install Ultralytics and verify the GPU:
```python
!pip install -U ultralytics
!nvidia-smi
```
4. Unzip the dataset:
```python
!unzip -q /content/drive/MyDrive/marker_dataset.zip -d /content/dataset
```
### 5.2 Train the YOLO26 Model
```python
from ultralytics import YOLO
model = YOLO("yolo26n.pt") # pretrained YOLO26 weights [ confirm the size you used: n / s / m ]
results = model.train(
data="/content/dataset/data.yaml",
epochs=100, # [ your value ]
imgsz=416, # [ your value ]
batch=16, # [ your value ]
project="/content/drive/MyDrive/marker_runs",
name="marker_yolo26"
)
```
| Parameter | Value used |
|---|---|
| Base model | [ yolo26n.pt ] |
| Epochs | [ ... ] |
| Image size | [ ... ] |
| Batch size | [ ... ] |
📷 *Screenshot: training progress / epoch logs*
### 5.3 Locate the Trained Weights
After training, Ultralytics saves the weights in `runs/.../weights/`:
- `best.pt` – checkpoint with the best validation performance (**use this one**)
- `last.pt` – checkpoint from the final epoch
Copy `best.pt` to the `marker_yolo_weights` folder in Drive and rename it to **`marker_best.pt`**.
## 6. Step 3 – Evaluation
### 6.1 Validate the Model
```python
from ultralytics import YOLO
model = YOLO("/content/drive/MyDrive/marker_yolo_weights/marker_best.pt")
metrics = model.val(data="/content/dataset/data.yaml")
print("mAP50 :", metrics.box.map50)
print("mAP50-95 :", metrics.box.map)
print("Precision:", metrics.box.mp)
print("Recall :", metrics.box.mr)
```
### 6.2 Results
| Metric | Value |
|---|---|
| Precision | 0.9677 |
| Recall | 0.9458 |
| mAP@50 | 0.9499 |
| mAP@50-95 | 0.6995 |
📷 *Screenshots: `results.png` (loss and metric curves), confusion matrix, PR curve*
### 6.3 Test on Sample Images
```python
results = model.predict(source="/content/dataset/images/test", conf=0.5, save=True)
```
📷 *Screenshot: sample predictions on test images*
## 7. Step 4 – Export to ONNX
ONNX is the intermediate format used before building the TensorRT engine.
### 7.1 Run the Export in Colab
```python
from ultralytics import YOLO
model = YOLO("/content/drive/MyDrive/marker_yolo_weights/marker_best.pt")
model.export(format="onnx", imgsz=416)
```
This generates `marker_best.onnx` next to the `.pt` file.
📷 *Screenshot: successful export output*
> **Note:** the export image size (`imgsz`) should match the size used for inference on the Jetson (here, **416**).
## 8. Step 5 – Jetson Setup
### 8.1 Prepare the Jetson
1. Flash JetPack on the Jetson Orin Nano and boot it up.
2. Connect the Logitech BRIO 100 to a USB port and confirm it is detected:
```bash
ls /dev/video*
```
3. Install the dependencies (use the PyTorch / Ultralytics versions compatible with your JetPack):
```bash
pip3 install ultralytics
```
4. (Optional) Maximize performance:
```bash
sudo nvpmodel -m 0
sudo jetson_clocks
```
### 8.2 Copy the Project Files
Copy the scripts, the notebook and the `models/` folder (with `marker_best.pt`) to the project folder shown in Section 3:
```bash
cd /home/jetson/projects_2026/Marker/Marker_detection
ls
ls models
```
## 9. Step 6 – TensorRT Optimization on Jetson
TensorRT converts the model into an engine optimized for the Jetson GPU, giving much faster inference than the plain `.pt` model.
### 9.1 Export the TensorRT Engine
From the project folder run:
```bash
cd /home/jetson/projects_2026/Marker/Marker_detection
python3 marker_detection.py --export-tensorrt --imgsz 416
```
This produces the following files in `models/`:
- `marker_best.onnx`
- `marker_best.engine`
The `.engine` file is loaded automatically at inference time.
📷 *Screenshot: export finished with `.onnx` and `.engine` files listed*
> **Note:** a TensorRT engine is specific to the device and TensorRT version it was built on. Always build it on the Jetson itself.
## 10. Step 7 – Real-Time Detection on Jetson
### 10.1 Run on the Live Camera
```bash
python3 marker_detection.py --source 0 --imgsz 416
```
- `--source 0` selects the first camera (`/dev/video0`). A video file path can be used instead.
- `--imgsz 416` must match the size used during export.
📷 *Screenshot: live detection window with bounding boxes and confidence scores*
### 10.2 Monitor GPU Usage
In a second terminal, confirm that the GPU is being used:
```bash
sudo tegrastats
```
### 10.3 Performance
| Item | Value |
|---|---|
| Device | Jetson Orin Nano |
| Camera | Logitech BRIO 100 |
| Input size | 416 × 416 |
| Model format | TensorRT (`.engine`) |
| FPS | [ ... ] |
## 11. Step 8 – Marker Tracking
Tracking assigns a persistent ID to each marker across frames using the Ultralytics `.track()` function with the **ByteTrack** tracker.
```bash
python3 marker_tracking.py --source 0 --imgsz 416
```
The same TensorRT engine workflow is used: the engine is built once and loaded automatically at runtime.
📷 *Screenshot: tracking output with IDs on the markers*
## 12. Troubleshooting
| Problem | Possible cause | Fix |
|---|---|---|
| Camera not opening | Wrong index or device busy | Check `ls /dev/video*`, try `--source 1`, close other apps using the camera |
| Engine fails to load | Engine built on a different device / TensorRT version | Rebuild the engine on the Jetson |
| Low FPS | Running `.pt` instead of `.engine`, or low power mode | Export the TensorRT engine, run `nvpmodel` and `jetson_clocks` |
| Detections missing | Image size mismatch or confidence threshold too high | Use the same `--imgsz` for export and inference, lower `conf` |
| Poor accuracy in the field | Dataset lacks real-world variety | Add more images from deployment conditions and retrain |
## 13. Conclusion
The project covers the complete workflow of a custom object detection system: dataset creation and annotation, YOLO26 training and evaluation on Google Colab, export to ONNX, TensorRT optimization, and real-time deployment on an NVIDIA Jetson Orin Nano. The trained model reaches a precision of 0.9677, a recall of 0.9458 and an mAP@50 of 0.9499, and runs on live camera streams with GPU acceleration.
## 14. Quick Command Reference
```bash
# Go to the project folder
cd /home/jetson/projects_2026/Marker/Marker_detection
#create the virtual environment
python3 -m venv --system-site-packages venv
#activate the virtual environment
source venv/bin/activate
# Export TensorRT engine (on Jetson)
python3 marker_detection.py --export-tensorrt --imgsz 416
# Run live detection
python3 marker_detection.py --source 0 --imgsz 416
# Run tracking
python3 marker_tracking.py --source 0 --imgsz 416
# Monitor GPU
sudo tegrastats
```