Files
Project_documents/Welding_detection.md
T
2026-11-23 11:42:41 +05:30

394 lines
14 KiB
Markdown

# Weld Defect Detection on Jetson Orin Nano (YOLO11 + TensorRT)
Real-time detection of three weld classes on a Jetson Orin Nano, using a YOLO11s model trained in Google Colab and deployed as a TensorRT engine.
Classes (training order) and the box colour used when drawing:
| ID | Class | Box colour |
|---|---|---|
| 0 | Bad Weld | Red |
| 1 | Good Weld | Green |
| 2 | Defect | Orange |
The script reads the class names from the model itself and matches colours by name, so the order above does not affect it.
## Table of Contents
1. [What This Project Does](#1-what-this-project-does)
2. [Folder Structure](#2-folder-structure)
3. [What Each File Is For](#3-what-each-file-is-for)
4. [One-Time Setup on the Jetson](#4-one-time-setup-on-the-jetson)
5. [Training Summary](#5-training-summary)
6. [How to Run the Project, Start to Finish](#6-how-to-run-the-project-start-to-finish)
7. [How It Works](#7-how-it-works)
8. [Changing Things](#8-changing-things)
9. [Troubleshooting](#9-troubleshooting)
10. [Quick Command Cheat Sheet](#10-quick-command-cheat-sheet)
---
## 1. What This Project Does
Training happens **once** in Google Colab:
```
two datasets -> merge -> train YOLO11s -> best.pt
```
Deployment happens on the Jetson, using only two scripts:
| Script | Purpose |
|---|---|
| `convert.py` | `best_weld.pt` -> `best_weld.onnx` -> `best_weld.engine` |
| `infer.py` | Detection on images, video files, or a live camera |
**Why an engine?** A TensorRT `.engine` file runs much faster on the Jetson GPU than the raw `.pt` file. This matters for live video.
Each script is fully self-contained. There is no shared helper file any more, so you can copy either script on its own.
---
## 2. Folder Structure
```
/home/jetson/projects_2026/welding/
├── convert.py # converts .pt -> .onnx -> .engine
├── infer.py # detection on images, video, or live camera
├── README.txt # project documentation
├── models/
│ ├── best_weld.pt # trained weights from Colab
│ ├── best_weld.onnx # created by convert.py
│ └── best_weld.engine # created by convert.py (used for inference)
├── test_images/ # your input images
├── test_video.mp4 # your input video
├── results/ # ALL outputs are saved here (created automatically)
├── venv/ # Python virtual environment (made in section 4)
└── __pycache__/ # made automatically by Python, safe to delete
```
---
## 3. What Each File Is For
### 3.1 `convert.py` (run once, on the Jetson)
Converts `models/best_weld.pt` into `models/best_weld.onnx` and then into `models/best_weld.engine`. It skips any output that already exists unless you add `--force`.
| Option | Description |
|---|---|
| `--weights` | Input `.pt` file. Default: `models/best_weld.pt` |
| `--imgsz` | Input size baked into the engine. Default: `640`. It must match the size used at inference. |
| `--precision` | `fp16` (default), `fp32` or `int8`. INT8 also needs `--data`. |
| `--method` | `ultralytics` (default): Ultralytics builds the engine. `trtexec`: NVIDIA's trtexec tool builds it from the ONNX file, then class-name metadata is added. |
| `--data` | Dataset yaml file, only for INT8 calibration. |
| `--workspace` | TensorRT workspace in GB. Default: `4`. |
| `--force` | Rebuild even if the outputs already exist. |
### 3.2 `infer.py` (images, video files and live camera in one script)
Loads the engine, runs detection, draws coloured boxes and labels, prints the class counts, and saves the result to `results/`.
The mode is chosen automatically from `--source`:
| `--source` value | Mode |
|---|---|
| An image file or a folder of images | Image mode |
| A video file, `0`, `1` or `csi` | Video / live camera mode |
| No `--source` at all | First image found; if there is no image, first video found |
- **Image mode** saves `results/<name>_out.<ext>` for every image.
- **Video mode** draws FPS and class counts on every frame and saves `results/<name>_out.mp4` (camera output is `results/camera_out.mp4`).
| Option | Description |
|---|---|
| `--source` | Image file, image folder, video file, `0` (USB camera) or `csi` (Jetson camera). |
| `--weights` | Use a different engine file. |
| `--save-dir` | Output folder. Default: `results/` |
| `--save` | (video) exact output video path. |
| `--no-save` | (video) do not write an output video. |
| `--show` | (images) open a preview window; press `q` to stop. |
| `--no-display` | (video) do not open a window. Use this over SSH. |
| `--imgsz` | Must match the engine. Default: `640`. |
| `--conf` | Minimum confidence to show a box. Default: `0.25`. |
| `--iou` | Overlap threshold for merging boxes. Default: `0.45`. |
| `--device` | Default `"0"` (the Jetson GPU). |
| `--debug` | Print every candidate box, even below `--conf`. |
In a preview window press `q` to quit. In the terminal `Ctrl+C` also stops a video or camera run cleanly, and the output file is still saved.
Settings (paths, `IMGSZ`, `CONF`, `IOU`, colours) are at the top of each script in the `CONFIG` block.
### 3.3 Folders and Other Files
| Item | Purpose |
|---|---|
| `models/` | Holds the three model files. Only `best_weld.engine` is used at inference time. Keep the `.pt` so you can rebuild the engine later. |
| `test_images/` | Your input images. |
| `test_video.mp4` | Your input video. |
| `results/` | Created automatically if it is missing. |
| `venv/` | The isolated Python environment for this project. |
| `__pycache__/` | Python's compiled cache. Regenerated automatically and can be deleted. |
---
## 4. One-Time Setup on the Jetson
### 4.1 Prerequisites
Your Jetson should already have JetPack (CUDA, TensorRT, cuDNN) and NVIDIA's Jetson build of PyTorch. Check with:
```bash
python3 --version
python3 -c "import torch; print(torch.__version__, torch.cuda.is_available())"
python3 -c "import tensorrt; print(tensorrt.__version__)"
```
`torch.cuda.is_available()` must print `True`. If it prints `False` you have a CPU-only torch, and you need NVIDIA's Jetson wheel for your JetPack version before continuing.
### 4.2 Create the Virtual Environment
> **Important:** the flag `--system-site-packages` is needed on Jetson. It lets the venv see the JetPack packages (TensorRT, and the Jetson torch if it was installed system-wide), which cannot be installed with plain pip.
```bash
sudo apt update
sudo apt install -y python3-venv python3-pip
cd /home/jetson/projects_2026/welding
python3 -m venv --system-site-packages venv
source venv/bin/activate
pip install --upgrade pip
pip install ultralytics
```
Then verify inside the venv:
```bash
python -c "import torch; print('torch', torch.__version__, 'cuda', torch.cuda.is_available())"
python -c "import tensorrt; print('tensorrt', tensorrt.__version__)"
python -c "import ultralytics, cv2; print('ultralytics', ultralytics.__version__, 'cv2', cv2.__version__)"
```
If any of these print `False` or fail to import, see [section 9](#9-troubleshooting).
### 4.3 Optional Extras
```bash
pip install onnx onnxslim onnxruntime
```
You only need these if the ONNX export step complains about a missing package.
### 4.4 Using the Environment Later
```bash
cd /home/jetson/projects_2026/welding
source venv/bin/activate # start
deactivate # stop
```
Activate the venv in every new terminal before running the scripts.
---
## 5. Training Summary
*(from `welding_combined_yolo_colab.ipynb`)*
Training was done in Google Colab on a T4 GPU. It is not repeated on the Jetson.
### 5.1 Datasets
Two public welding datasets are downloaded from Google Drive: **"The Welding Defect Dataset v2"** (`archive.zip`) and **"welding v1i yolov11"**.
### 5.2 Merge into One 3-Class Dataset
The notebook writes `merge_core.py`, which does the following:
- Checks that the second dataset's unnamed classes 0/1/2 match Bad Weld / Good Weld / Defect by comparing boxes on images that both datasets contain.
- Removes near-identical images using perceptual hashing.
- Re-splits by groups of similar images so look-alike images never sit in both train and test (this avoids leakage).
- Keeps validation and test free of augmented copies.
### 5.3 Resulting Dataset
| Item | Value |
|---|---|
| Images in | about 4,179 |
| Images out | 2,559 |
| Train | 2,044 |
| Validation | 310 |
| Test | 205 |
| Boxes | about 8,700 |
| Cross-split near-duplicates | 0 |
### 5.4 Training Settings
Training starts from `yolo11s.pt`:
| Setting | Value |
|---|---|
| Epochs / patience | 200 / 40 |
| Image size / batch | 640 / 16 |
| Optimizer | AdamW |
| Initial learning rate (`lr0`) | 0.002, cosine learning rate |
| Mosaic | 1.0 (switched off for the last 20 epochs) |
| `fliplr` | 0.5 |
| `hsv_h` / `hsv_s` / `hsv_v` | 0.015 / 0.5 / 0.4 |
### 5.5 Output and Evaluation
- **Output:** `weld_runs/yolo11s_combined/weights/best.pt` on Google Drive.
- **Evaluation:** the notebook runs validation on the test split and prints mAP50-95, mAP50 and the per-class AP.
Because training used `imgsz 640`, the Jetson engine is also built at 640.
### 5.6 Copying the Weights to the Jetson
Download `best.pt` from Drive, then run this on your computer:
```bash
scp best.pt jetson@<JETSON_IP>:/home/jetson/projects_2026/welding/models/best_weld.pt
```
---
## 6. How to Run the Project, Start to Finish
Open a terminal and go to the project:
```bash
cd /home/jetson/projects_2026/welding
source venv/bin/activate
```
### Step 1: Build the Engine (once, takes several minutes)
```bash
python3 convert.py
```
If `models/best_weld.onnx` and `models/best_weld.engine` already exist, they are skipped. Add `--force` to rebuild.
### Step 2: Detect on Images
```bash
python3 infer.py --source test_images
python3 infer.py --source test_images/weld1.jpg --show
```
The first command does every image in the folder. Outputs go to `results/<name>_out.jpg`.
### Step 3: Detect on a Video File
```bash
python3 infer.py --source test_video.mp4
python3 infer.py --source test_video.mp4 --no-display
```
Output goes to `results/test_video_out.mp4`.
### Step 4: Detect on a Live Camera
```bash
python3 infer.py --source 0
python3 infer.py --source csi
python3 infer.py --source 0 --no-display
```
Use `0` for a USB camera and `csi` for the Jetson camera. Add `--no-display` when working over SSH. Output goes to `results/camera_out.mp4`.
Running `python3 infer.py` with no `--source` uses the first image found (or the first video if there is no image).
### Check the Outputs
```bash
ls -lh results/
```
---
## 7. How It Works
1. **Conversion.** `convert.py` exports the PyTorch weights to ONNX, a portable format. TensorRT then compiles the ONNX graph into an engine optimised for this exact GPU. FP16 precision roughly doubles speed on the Orin Nano with very little loss of accuracy.
2. **Loading.** The engine file carries a small metadata header with the class names and image size, which Ultralytics reads.
3. **Warm-up.** The first inference initialises CUDA and TensorRT and is slow, so one dummy frame is run before real work starts. The FPS counter is therefore not distorted.
4. **Detection.** Each frame is resized to 640x640, the engine produces candidate boxes, boxes below `CONF` are dropped, and overlapping boxes are merged with NMS (`IOU`).
5. **Drawing and saving.** Boxes are drawn in each class colour, the class counts are printed, and the results are written to `results/`.
---
## 8. Changing Things
### Move the project
Change `BASE_DIR` in `convert.py` and `infer.py`, or run:
```bash
export WELD_HOME=/new/path
```
### Use a different input size
```bash
python3 convert.py --imgsz 416 --force
```
Then set `IMGSZ = 416` in `infer.py` (and in `convert.py`). 416 is faster but less accurate; 640 is slower but more accurate.
### Catch more small defects
Use `--conf 0.15` (more false alarms are possible).
### Fewer false alarms
Use `--conf 0.40`.
### Use a new model
Copy it to `models/best_weld.pt`, then run:
```bash
python3 convert.py --force
```
### Change box colours
Edit `CLASS_COLORS` in `infer.py`.
---
## 9. Troubleshooting
| Problem | Cause and fix |
|---|---|
| **Weights not found ... `best_weld.engine`** | The engine is not built yet. Run `python3 convert.py`. |
| **Weights not found ... `best_weld.pt`** | Copy the `.pt` file to `models/best_weld.pt`, or pass `--weights path`. |
| **`torch.cuda.is_available()` is `False`** | The venv is using a CPU-only torch. Recreate the venv with `--system-site-packages`. If pip installed its own torch, run `pip uninstall torch torchvision` so the Jetson wheel is used. |
| **No module named `tensorrt`** | The venv was created without `--system-site-packages`. Recreate it as shown in section 4.2. |
| **Engine fails to load or gives errors** | The engine was built on another machine or a different JetPack or TensorRT version. Rebuild it on this Jetson with `--force`. |
| **Wrong or garbage detections** | `imgsz` mismatch. The engine and `IMGSZ` must be the same (640). |
| **Class names show as 0, 1, 2** | The engine has no metadata. Rebuild with the default `--method ultralytics`. |
| **"cannot connect to X server" or a window error** | You are running over SSH. Add `--no-display` (video) and do not use `--show` (images). |
| **Could not open source: 0** | The USB camera is not at index 0. Try `--source 1`, or check `ls /dev/video*`. |
| **CSI camera fails** | Check `nvarguscamerasrc`. If you installed `opencv-python` with pip, it may hide the JetPack OpenCV that has GStreamer support. Run `pip uninstall opencv-python` and use the system OpenCV. |
| **`trtexec` not found** | Run `export PATH=$PATH:/usr/src/tensorrt/bin`, or use the default `--method ultralytics`. |
| **Low FPS** | Check the power mode with `sudo nvpmodel -q`, run `sudo jetson_clocks`, use FP16, and try a 416 engine (`--imgsz 416 --force` in `convert.py`, and `IMGSZ = 416` in `infer.py`). |
| **Nothing detected** | Run with `--debug --conf 0.15` to see low-confidence boxes in the terminal. |
| **Output video will not play** | Try VLC, or change the codec `"mp4v"` in `infer.py`. |
---
## 10. Quick Command Cheat Sheet
```bash
cd /home/jetson/projects_2026/welding && source venv/bin/activate
python3 convert.py # build the engine
python3 infer.py --source ./test_images # test image folder
python3 infer.py --source test_video.mp4 # video file
python3 infer.py --source 0 # live USB camera
python3 infer.py --source csi # live CSI camera
python3 infer.py --source 0 --no-display # camera over SSH
```