Files
Marker_segmentation/README_segmentation.md
T
2026-11-02 15:27:47 +05:30

467 lines
14 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.
# Marker Segmentation and Tracking with YOLO26 on NVIDIA Jetson
End-to-end documentation: polygon 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 segmentation** model to detect markers and outline their exact shape (pixel-level masks) in images and video streams. A dedicated marker dataset annotated with **polygons** is used to train and evaluate the model. The trained model is deployed on an **NVIDIA Jetson Orin Nano**, converted to a **TensorRT** engine, and used for real-time marker segmentation and tracking on the GPU.
Compared with the detection project, segmentation gives the exact marker outline instead of only a bounding box.
### 1.1 Objectives
- Build a marker dataset with polygon annotations.
- Train and evaluate a YOLO26 segmentation model.
- Export the model to ONNX and then to a TensorRT engine (FP16).
- Run real-time segmentation and tracking (persistent IDs) on a Jetson with a live camera.
### 1.2 Pipeline at a Glance
| Stage | Input | Output | Where it runs |
|---|---|---|---|
| 1. Dataset creation | Raw images / video frames | Polygon-annotated dataset (YOLO segmentation format) | PC |
| 2. Training | Dataset + pretrained YOLO26 segmentation weights | `best.pt` (renamed `marker_seg_best.pt`) | Google Colab (GPU) |
| 3. Evaluation | Validation set | Box and mask mAP, precision, recall, curves | Google Colab |
| 4. Export | `marker_seg_best.pt` | `marker_seg_best.onnx` | Google Colab / Jetson |
| 5. Optimization | ONNX | `marker_seg_best.engine` (TensorRT, FP16) | Jetson |
| 6. Inference | Live camera / video | Real-time masks with tracking IDs | Jetson |
## 2. Hardware and Software Requirements
### 2.1 Hardware
- NVIDIA Jetson Orin Nano (inference device)
- Logitech BRIO 100 USB camera (a CSI camera is also supported)
- Development PC / laptop with internet access
### 2.2 Software
| Component | Details |
|---|---|
| Model | YOLO26 segmentation (Ultralytics) |
| Tracker | ByteTrack (default), BoT-SORT optional |
| Training platform | Google Colab with GPU runtime |
| Annotation tool | **[ e.g., Roboflow / CVAT / Labelme ]** |
| Export formats | ONNX, TensorRT (`.engine`, FP16) |
| Jetson OS | JetPack **[ version ]** |
| Languages / libraries | Python 3, Ultralytics, OpenCV, PyTorch |
## 3. Project Structure
The project lives on the Jetson at **[ replace with your path, e.g., /home/jetson/projects_2026/Marker/Marker_segmentation ]**:
```
Marker_segmentation
├── marker_segmentation.py # segmentation + tracking script
├── marker_segmentation_training.ipynb # training notebook (Jupyter)
└── models/
├── marker_seg_best.pt # trained weights
├── marker_seg_best.onnx # ONNX model
└── marker_seg_best.engine # TensorRT engine
```
| File | Purpose |
|---|---|
| `marker_segmentation.py` | Real-time marker segmentation and tracking; also used to export ONNX and the TensorRT engine |
| `marker_segmentation_training.ipynb` | Notebook used for dataset loading, training, evaluation and ONNX export |
| `models/marker_seg_best.pt` | Best trained YOLO26 segmentation weights (class 0 = marker) |
| `models/marker_seg_best.onnx` | Weights exported to ONNX |
| `models/marker_seg_best.engine` | TensorRT engine built on the Jetson; loaded automatically when it sits next to the `.pt` file |
## 4. Step 1 – Dataset Creation (Polygon Annotation)
### 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 with Polygons
1. Upload the images to the annotation tool.
2. Create the class (for example `marker`) **[ confirm class name ]**.
3. For every marker, click points around its outline to draw a **polygon** that follows the marker edge closely.
4. Review the polygons and fix any inaccurate outlines.
📷 *Screenshot: annotation tool with polygon masks*
### 4.3 Split the Dataset
Split into training, validation and test sets **[ confirm the ratio, e.g., 70 / 20 / 10 ]**:
| Split | Images |
|---|---|
| Train | [ ... ] |
| Validation | [ ... ] |
| Test | [ ... ] |
### 4.4 Export in YOLO Segmentation Format
Export the dataset in **YOLO segmentation (Ultralytics) format**. The folder structure is the same as for detection:
```
dataset/
├── images/
│ ├── train/
│ ├── val/
│ └── test/
├── labels/
│ ├── train/
│ ├── val/
│ └── test/
└── data.yaml
```
Each label file contains one line per object, with the polygon points instead of a box:
```
<class_id> <x1> <y1> <x2> <y2> ... <xn> <yn> (all coordinates 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_segmentation_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_seg_dataset.zip -d /content/dataset
```
### 5.2 Train the YOLO26 Segmentation Model
Use a segmentation checkpoint (the `-seg` weights):
```python
from ultralytics import YOLO
model = YOLO("yolo26n-seg.pt") # pretrained YOLO26 segmentation 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_seg_runs",
name="marker_seg_yolo26"
)
```
| Parameter | Value used |
|---|---|
| Base model | [ yolo26n-seg.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 a Drive folder and rename it to **`marker_seg_best.pt`**.
## 6. Step 3 – Evaluation
### 6.1 Validate the Model
A segmentation model is evaluated on both the **box** and the **mask** outputs:
```python
from ultralytics import YOLO
model = YOLO("/content/drive/MyDrive/marker_seg_weights/marker_seg_best.pt")
metrics = model.val(data="/content/dataset/data.yaml")
print("Box mAP50 :", metrics.box.map50)
print("Box mAP50-95 :", metrics.box.map)
print("Mask mAP50 :", metrics.seg.map50)
print("Mask mAP50-95 :", metrics.seg.map)
print("Mask Precision:", metrics.seg.mp)
print("Mask Recall :", metrics.seg.mr)
```
### 6.2 Results
| Metric | Box | Mask |
|---|---|---|
| Precision | [ ... ] | [ ... ] |
| Recall | [ ... ] | [ ... ] |
| mAP@50 | [ ... ] | [ ... ] |
| mAP@50-95 | [ ... ] | [ ... ] |
📷 *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 with segmentation masks 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_seg_weights/marker_seg_best.pt")
model.export(format="onnx", imgsz=416)
```
This generates `marker_seg_best.onnx` next to the `.pt` file.
📷 *Screenshot: successful export output*
> **Note:** a TensorRT engine has a **fixed input size**. Use the same `--imgsz` for export and for inference (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 script, the notebook and the `models/` folder (with `marker_seg_best.pt`) to the project folder shown in Section 3:
```bash
cd <your project folder>
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
The script converts `.pt` → `.onnx` → `.engine` (FP16) in one step. Run it once from the project folder:
```bash
python3 marker_segmentation.py --export-tensorrt --imgsz 416
```
To export only the ONNX file, without the engine:
```bash
python3 marker_segmentation.py --export-onnx --imgsz 416
```
This produces the following files in `models/`:
- `marker_seg_best.onnx`
- `marker_seg_best.engine`
If `marker_seg_best.engine` exists next to `marker_seg_best.pt`, it is loaded automatically at inference. Otherwise the `.pt` file is used.
📷 *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 Segmentation and Tracking on Jetson
The script runs segmentation and tracking together. Each marker is outlined with a mask and keeps a persistent ID across frames (ByteTrack by default).
### 10.1 Run on the Live Camera
USB camera:
```bash
python3 marker_segmentation.py --source 0 --imgsz 416
```
CSI camera:
```bash
python3 marker_segmentation.py --source csi --imgsz 416
```
Video file, with the result saved:
```bash
python3 marker_segmentation.py --source my_video.mp4 --imgsz 416 --save out.mp4
```
- `--source 0` selects the first USB camera (`/dev/video0`).
- `--imgsz 416` must match the size used during export.
📷 *Screenshot: live segmentation window with masks, tracking IDs and confidence scores*
### 10.2 Optional Settings
Use BoT-SORT instead of ByteTrack:
```bash
python3 marker_segmentation.py --source 0 --imgsz 416 --tracker botsort.yaml
```
Run headless (for example over SSH, with no display window):
```bash
python3 marker_segmentation.py --source 0 --imgsz 416 --no-display
```
Debug mode, which prints what the model returned for each frame:
```bash
python3 marker_segmentation.py --source 0 --imgsz 416 --debug
```
### 10.3 Monitor GPU Usage
In a second terminal, confirm that the GPU is being used:
```bash
sudo tegrastats
```
### 10.4 Performance
| Item | Value |
|---|---|
| Device | Jetson Orin Nano |
| Camera | Logitech BRIO 100 |
| Input size | 416 × 416 |
| Model format | TensorRT (`.engine`, FP16) |
| FPS | [ ... ] |
## 11. Command-Line Options
| Option | Purpose |
|---|---|
| `--export-tensorrt` | Export `.pt` → `.onnx` → `.engine` (FP16) |
| `--export-onnx` | Export the ONNX file only |
| `--source` | `0` for a USB camera, `csi` for a CSI camera, or a video file path |
| `--imgsz` | Input size; must be the same for export and inference |
| `--save` | Save the output video to the given file |
| `--tracker` | Tracker configuration (`bytetrack.yaml` by default, or `botsort.yaml`) |
| `--no-display` | Run without a display window |
| `--debug` | Print the model output for each frame |
## 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 |
| Wrong results with the engine | `--imgsz` differs from the export size | Use the same `--imgsz` for export and inference |
| Low FPS | Running `.pt` instead of `.engine`, or low power mode | Export the TensorRT engine, run `nvpmodel` and `jetson_clocks` |
| No window on SSH | No display available | Use `--no-display` (and `--save` to keep the output) |
| No masks or IDs appear | Model returned nothing for the frame | Run with `--debug` and check the output |
| Poor mask quality | Polygons in the dataset are too rough or too few images | Improve the annotations, add more images and retrain |
## 13. Conclusion
The project covers the complete workflow of a custom segmentation system: polygon dataset creation, YOLO26 segmentation training and evaluation on Google Colab, export to ONNX, TensorRT optimization, and real-time segmentation and tracking on an NVIDIA Jetson Orin Nano. The result is an efficient marker segmentation system that gives the exact outline of each marker and runs on live camera streams with GPU acceleration.
## 14. Quick Command Reference
```bash
# Export TensorRT engine (run once, on the Jetson)
python3 marker_segmentation.py --export-tensorrt --imgsz 416
# Live tracking, USB camera
python3 marker_segmentation.py --source 0 --imgsz 416
# Live tracking, CSI camera
python3 marker_segmentation.py --source csi --imgsz 416
# Video file, save the result
python3 marker_segmentation.py --source my_video.mp4 --imgsz 416 --save out.mp4
# BoT-SORT tracker
python3 marker_segmentation.py --source 0 --imgsz 416 --tracker botsort.yaml
# Headless over SSH
python3 marker_segmentation.py --source 0 --imgsz 416 --no-display
# Monitor GPU
sudo tegrastats
```