e012f322143866cc4031ac6f0a5fdb9982005423
==========================================================================
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:
0 Bad Weld red
1 Good Weld green
2 Defect orange
The scripts read the class names from the model itself and match colours
by name, so the order above does not affect them.
==========================================================================
1. WHAT THIS PROJECT DOES
==========================================================================
Training happens once in Google Colab:
two datasets -> merge -> train YOLO11s -> best.pt
Deployment happens on the Jetson:
best_weld.pt --(1_convert.py)--> best_weld.onnx
best_weld.onnx --(1_convert.py)--> best_weld.engine (TensorRT, FP16)
Then the engine is used for detection:
2_infer_image.py : images -> annotated images in results/
3_infer_video.py : video or camera -> annotated video in results/
Why an engine? A TensorRT .engine file runs much faster on the Jetson GPU
than the raw .pt file. This matters for live video.
==========================================================================
2. FOLDER STRUCTURE
==========================================================================
/home/jetson/projects/welding/
weld_common.py shared settings and helper functions
1_convert.py converts .pt -> .onnx -> .engine
2_infer_image.py detection on image(s)
3_infer_video.py detection on a video file or camera
README.txt this document
models/
best_weld.pt trained weights from Colab
best_weld.onnx created by 1_convert.py
best_weld.engine created by 1_convert.py (used for inference)
test_images/ your input images
test_video.mp4 your input video
results/ ALL outputs are saved here
venv/ Python virtual environment (made in section 4)
__pycache__/ made automatically by Python, safe to delete
==========================================================================
3. WHAT EACH FILE IS FOR
==========================================================================
--- weld_common.py (shared configuration) ---
Every other script imports this file, so it must stay in the same folder
as them. It contains:
- All paths: BASE_DIR, MODELS_DIR, TEST_IMAGES_DIR, RESULTS_DIR,
PT_PATH, ONNX_PATH, ENGINE_PATH. This is the only place where paths
are defined. To move the project, change BASE_DIR or set the
environment variable WELD_HOME.
- Settings: IMGSZ (640), CONF (0.25), IOU (0.45), DEVICE ("0" = GPU).
- CLASS_COLORS: the colour for each class.
- find_first(): when you do not pass --source, it picks the first image
or video it finds in test_images/, then the project folder, then
test_videos/.
- load_model(): loads the engine, prints the class names, and runs one
dummy inference as a warm-up so the first real frame is not slow.
- detect(): runs the model on one frame. In debug mode it prints every
candidate box, even low-confidence ones.
- draw_detections(): draws coloured boxes and labels, and returns the
number of detections per class.
--- 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.
Options:
--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.
--- 2_infer_image.py (detection on images) ---
Loads the engine, runs detection, draws boxes, and saves the result to
results/ as <name>_out.<ext>. It also prints the class counts for each
image.
Options:
--source An image file or a folder of images.
Default: first image found.
--weights Use a different engine file.
--save-dir Output folder. Default: results/
--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.
--show Open a preview window (press q to quit).
--debug Print every candidate box, even below --conf.
--- 3_infer_video.py (detection on video or camera) ---
Runs detection frame by frame, draws FPS and class counts on the video,
and saves results/<name>_out.mp4. Press q in the preview window to stop.
When it finishes it prints the total detections.
Options:
--source A video file, 0 (USB camera) or csi (Jetson camera).
Default: first video found.
--save Custom output path. Default: results/<name>_out.mp4
--no-save Do not write an output video.
--no-display Do not open a window (use this over SSH).
--conf, --iou, --imgsz, --device, --weights, --debug
Same meaning as in the image script.
--- Folders and other files ---
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. It is 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:
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
The flag --system-site-packages is important 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.
sudo apt update
sudo apt install -y python3-venv python3-pip
cd /home/jetson/projects/welding
python3 -m venv --system-site-packages venv
source venv/bin/activate
pip install --upgrade pip
pip install ultralytics
Then verify inside the venv:
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.
4.3 Optional extras
pip install onnx onnxslim onnxruntime
You only need these if the ONNX export step complains about a missing
package. Your best_weld.onnx already exists, so this is only needed if
you rebuild it.
4.4 Using the environment later
cd /home/jetson/projects/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.
1. Datasets: two public welding datasets are downloaded from Google
Drive: "The Welding Defect Dataset v2" (archive.zip) and
"welding v1i yolov11".
2. Merge into one 3-class dataset (merge_core.py, written by the
notebook):
- 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.
3. Result: about 4,179 images in, 2,559 out (train 2,044, valid 310,
test 205), about 8,700 boxes, and 0 cross-split near-duplicates.
4. Training: starts from yolo11s.pt with these settings:
epochs 200, patience 40
imgsz 640, batch 16
optimizer AdamW, lr0 0.002, cosine learning rate
mosaic 1.0 (switched off for the last 20 epochs), fliplr 0.5,
hsv_h 0.015, hsv_s 0.5, hsv_v 0.4
5. Output: weld_runs/yolo11s_combined/weights/best.pt on Google Drive.
6. 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.
Copying the weights to the Jetson: download best.pt from Drive, then run
this on your computer:
scp best.pt jetson@<JETSON_IP>:/home/jetson/projects/welding/models/best_weld.pt
==========================================================================
6. HOW TO RUN THE PROJECT, START TO FINISH
==========================================================================
Open a terminal and go to the project:
cd /home/jetson/projects/welding
source venv/bin/activate
STEP 1: build the engine (once, takes several minutes)
python3 1_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
python3 2_infer_image.py
python3 2_infer_image.py --source test_images
python3 2_infer_image.py --source test_images/weld1.jpg --show
The first command uses the first image found. The second does every
image in the folder. Outputs go to results/<name>_out.jpg
STEP 3: detect on video
python3 3_infer_video.py
python3 3_infer_video.py --source test_video.mp4
python3 3_infer_video.py --source 0
python3 3_infer_video.py --source csi
python3 3_infer_video.py --no-display
The first command uses the first video found. Use 0 for a USB camera,
csi for the Jetson camera, and --no-display when working over SSH.
Output goes to results/test_video_out.mp4
CHECK THE OUTPUTS
ls -lh results/
==========================================================================
7. HOW IT WORKS
==========================================================================
1. Conversion. 1_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 weld_common.py, or run
export WELD_HOME=/new/path
Use a different input size:
python 1_convert.py --imgsz 416 --force
then set IMGSZ = 416 in weld_common.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
python 1_convert.py --force
Change box colours:
Edit CLASS_COLORS in weld_common.py
==========================================================================
9. TROUBLESHOOTING
==========================================================================
ModuleNotFoundError: weld_common
weld_common.py is not in the same folder as the script you ran, or
its name is wrong. Run "ls *.py" and check.
Weights not found ... best_weld.engine
The engine is not built yet. Run: python 1_convert.py
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 (image).
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 --imgsz 416.
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 3_infer_video.py.
==========================================================================
10. QUICK COMMAND CHEAT SHEET
==========================================================================
cd /home/jetson/projects/welding && source venv/bin/activate
python3 1_convert.py build the engine
python3 2_infer_image.py --source ./test_images test image folder
python 3_infer_video.py --source 0 live USB camera
Languages
Python
100%