diff --git a/2_infer_image.py b/2_infer_image.py deleted file mode 100644 index fbbc90d..0000000 --- a/2_infer_image.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python3 -""" -Step 2: weld detection on image(s) using best_weld.engine - -USAGE ------ -Auto-pick the first image in the welding folder: - python3 2_infer_image.py - -Specific image: - python3 2_infer_image.py --source weld.jpg - -Folder of images: - python3 2_infer_image.py --source ./test_images - -Extras: - --show open a preview window - --debug print every candidate box, even below --conf - --conf 0.15 lower the threshold if welds/defects are being missed -""" - -import argparse -import sys -from pathlib import Path - -import cv2 - -from weld_common import (CONF, DEVICE, IMAGE_EXTS, IMGSZ, IOU, RESULTS_DIR, - counts_to_str, detect, draw_detections, find_first, load_model) - - -def parse_args(): - p = argparse.ArgumentParser(description="Weld detection on images (TensorRT engine)") - p.add_argument("--source", type=str, default=None, - help="Image file or folder. Default: first image in the welding folder.") - p.add_argument("--weights", type=str, default=None, help="Override engine path.") - p.add_argument("--save-dir", type=str, default=str(RESULTS_DIR)) - p.add_argument("--imgsz", type=int, default=IMGSZ, help="Must match the engine's imgsz.") - p.add_argument("--conf", type=float, default=CONF) - p.add_argument("--iou", type=float, default=IOU) - p.add_argument("--device", type=str, default=DEVICE) - p.add_argument("--show", action="store_true", help="Show a preview window.") - p.add_argument("--debug", action="store_true") - return p.parse_args() - - -def collect_images(source): - if source is None: - first = find_first(IMAGE_EXTS) - if first is None: - sys.exit("No image found in the welding folder. Use --source path/to/image.jpg") - print(f"No --source given, using: {first.name}") - return [first] - - path = Path(source) - if path.is_dir(): - imgs = sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_EXTS) - if not imgs: - sys.exit(f"No images found in {path}") - return imgs - if not path.exists(): - sys.exit(f"File not found: {path}") - return [path] - - -def main(): - args = parse_args() - images = collect_images(args.source) - model = load_model(args.weights, args.imgsz, args.device) - - out_dir = Path(args.save_dir) - out_dir.mkdir(parents=True, exist_ok=True) - - for img_path in images: - frame = cv2.imread(str(img_path)) - if frame is None: - print(f"Skipping unreadable file: {img_path}") - continue - - print(f"\n{img_path.name}") - result = detect(model, frame, args.conf, args.iou, args.imgsz, args.device, args.debug) - counts = draw_detections(frame, result, model.names) - print(f" -> {counts_to_str(counts)}") - - out_path = out_dir / f"{img_path.stem}_out{img_path.suffix}" - cv2.imwrite(str(out_path), frame) - print(f" Saved: {out_path}") - - if args.show: - cv2.imshow("Weld Detection", frame) - if cv2.waitKey(0) & 0xFF == ord("q"): - break - - cv2.destroyAllWindows() - print(f"\nDone. {len(images)} image(s) -> {out_dir}") - - -if __name__ == "__main__": - main() diff --git a/3_infer_video.py b/3_infer_video.py deleted file mode 100644 index 255d1f4..0000000 --- a/3_infer_video.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python3 -""" -Step 3: weld detection on video / camera using best_weld.engine - -USAGE ------ -Auto-pick the first video in the welding folder (output saved to results/): - python3 3_infer_video.py - -Specific video: - python3 3_infer_video.py --source weld.mp4 - -USB camera / Jetson CSI camera: - python3 3_infer_video.py --source 0 - python3 3_infer_video.py --source csi - -Headless over SSH (no window): - python3 3_infer_video.py --no-display - -Extras: - --no-save don't write an output video - --debug print every candidate box each frame - --conf 0.15 lower the threshold if welds/defects are being missed - -Press 'q' in the preview window to quit. -""" - -import argparse -import sys -import time -from pathlib import Path - -import cv2 - -from weld_common import (CONF, DEVICE, IMGSZ, IOU, RESULTS_DIR, VIDEO_EXTS, - counts_to_str, detect, draw_detections, find_first, load_model) - - -def build_csi_pipeline(width=1280, height=720, fps=30): - return ( - f"nvarguscamerasrc ! video/x-raw(memory:NVMM), width={width}, height={height}, " - f"format=NV12, framerate={fps}/1 ! nvvidconv flip-method=0 ! " - f"video/x-raw, width={width}, height={height}, format=BGRx ! " - f"videoconvert ! video/x-raw, format=BGR ! appsink drop=1" - ) - - -def open_capture(source: str): - if source == "csi": - return cv2.VideoCapture(build_csi_pipeline(), cv2.CAP_GSTREAMER) - if source.isdigit(): - return cv2.VideoCapture(int(source), cv2.CAP_V4L2) - return cv2.VideoCapture(source) - - -def parse_args(): - p = argparse.ArgumentParser(description="Weld detection on video (TensorRT engine)") - p.add_argument("--source", type=str, default=None, - help="Video file, '0'/'1' for USB camera, or 'csi'. " - "Default: first video in the welding folder.") - p.add_argument("--weights", type=str, default=None, help="Override engine path.") - p.add_argument("--save", type=str, default=None, - help="Output video path. Default: results/_out.mp4") - p.add_argument("--no-save", action="store_true", help="Don't write an output video.") - p.add_argument("--imgsz", type=int, default=IMGSZ, help="Must match the engine's imgsz.") - p.add_argument("--conf", type=float, default=CONF) - p.add_argument("--iou", type=float, default=IOU) - p.add_argument("--device", type=str, default=DEVICE) - p.add_argument("--no-display", action="store_true") - p.add_argument("--debug", action="store_true") - return p.parse_args() - - -def main(): - args = parse_args() - - source = args.source - if source is None: - first = find_first(VIDEO_EXTS) - if first is None: - sys.exit("No video found in the welding folder. Use --source path/to/video.mp4") - print(f"No --source given, using: {first.name}") - source = str(first) - - model = load_model(args.weights, args.imgsz, args.device) - - cap = open_capture(source) - if not cap.isOpened(): - sys.exit(f"Could not open source: {source}") - - writer = None - if not args.no_save: - if args.save: - out_path = Path(args.save) - else: - name = "camera" if (source == "csi" or source.isdigit()) else Path(source).stem - out_path = RESULTS_DIR / f"{name}_out.mp4" - out_path.parent.mkdir(parents=True, exist_ok=True) - w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280 - h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720 - fps_out = cap.get(cv2.CAP_PROP_FPS) or 20 - writer = cv2.VideoWriter(str(out_path), cv2.VideoWriter_fourcc(*"mp4v"), - fps_out, (w, h)) - print(f"Saving output to: {out_path}") - - total_counts = {} - frames = 0 - prev_t = time.time() - print("Running... press 'q' to quit.") - - while True: - ok, frame = cap.read() - if not ok: - print("End of stream / camera read failed.") - break - - result = detect(model, frame, args.conf, args.iou, args.imgsz, args.device, args.debug) - counts = draw_detections(frame, result, model.names) - for k, v in counts.items(): - total_counts[k] = total_counts.get(k, 0) + v - - now = time.time() - fps = 1.0 / max(now - prev_t, 1e-6) - prev_t = now - cv2.putText(frame, f"FPS: {fps:.1f}", (10, 25), - cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) - cv2.putText(frame, counts_to_str(counts), (10, 50), - cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) - - if writer is not None: - writer.write(frame) - if not args.no_display: - cv2.imshow("Weld Detection", frame) - if cv2.waitKey(1) & 0xFF == ord("q"): - break - frames += 1 - - cap.release() - if writer is not None: - writer.release() - cv2.destroyAllWindows() - print(f"\nProcessed {frames} frame(s). Total detections: {counts_to_str(total_counts)}") - - -if __name__ == "__main__": - main() diff --git a/README.txt b/README.txt index d7f83c6..12af21c 100644 --- a/README.txt +++ b/README.txt @@ -2,109 +2,65 @@ 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. - - +The script reads the class names from the model itself and matches colours +by name, so the order above does not affect it. ========================================================================== 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/ - +Deployment happens on the Jetson, using only two scripts: + 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/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 +/home/jetson/projects_2026/welding/ + convert.py converts .pt -> .onnx -> .engine + infer.py detection on images, video, or live 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) + 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 + 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 ========================================================================== - ---- 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) --- - +--- 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. @@ -118,47 +74,45 @@ Options: --force Rebuild even if the outputs already exist. ---- 2_infer_image.py (detection on images) --- +--- 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/. -Loads the engine, runs detection, draws boxes, and saves the result to -results/ as _out.. It also prints the class counts for each -image. +The mode is chosen automatically from --source: + 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/_out. for every image. +Video mode draws FPS and class counts on every frame and saves +results/_out.mp4 (camera output is results/camera_out.mp4). 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. + --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. ---- 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/_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/_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. +Settings (paths, IMGSZ, CONF, IOU, colours) are at the top of each +script in the CONFIG block. --- 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. @@ -166,104 +120,78 @@ Options: 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. - - + __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: - 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 + 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: - 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. - +package. 4.4 Using the environment later - - cd /home/jetson/projects/welding + 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. - 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 @@ -274,11 +202,9 @@ Jetson. 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 @@ -286,230 +212,187 @@ Jetson. 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@:/home/jetson/projects/welding/models/best_weld.pt - - + scp best.pt jetson@:/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: - - cd /home/jetson/projects/welding + cd /home/jetson/projects_2026/welding source venv/bin/activate - STEP 1: build the engine (once, takes several minutes) - - python3 1_convert.py - + 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 + python3 infer.py --source test_images + python3 infer.py --source test_images/weld1.jpg --show - 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 does every image in the folder. Outputs go to +results/_out.jpg +STEP 3: detect on a video file -The first command uses the first image found. The second does every -image in the folder. Outputs go to results/_out.jpg + python3 infer.py --source test_video.mp4 + python3 infer.py --source test_video.mp4 --no-display - -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 +STEP 4: detect on a live camera + + 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 - ls -lh results/ - - ========================================================================== 7. HOW IT WORKS ========================================================================== - -1. Conversion. 1_convert.py exports the PyTorch weights to ONNX, a +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 weld_common.py, or run + Change BASE_DIR in convert.py and infer.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 + 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 - python 1_convert.py --force - + python3 convert.py --force Change box colours: - Edit CLASS_COLORS in weld_common.py - - + Edit CLASS_COLORS in infer.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 + 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 (image). + --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 --imgsz 416. - + "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 3_infer_video.py. - - + Try VLC, or change the codec "mp4v" in infer.py. ========================================================================== 10. QUICK COMMAND CHEAT SHEET ========================================================================== + cd /home/jetson/projects_2026/welding && source venv/bin/activate - 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 - + 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 diff --git a/convert.py b/convert.py index 208a3d6..fb08dee 100644 --- a/convert.py +++ b/convert.py @@ -1,26 +1,32 @@ #!/usr/bin/env python3 """ -Step 1: convert best_weld.pt -> best_weld.onnx -> best_weld.engine +convert.py - convert best_weld.pt -> best_weld.onnx -> best_weld.engine RUN THIS ON THE JETSON. A TensorRT engine only works on the GPU / TensorRT version it was built on, so an engine built in Colab will NOT run on the Orin Nano. +Project root : /home/jetson/projects_2026/welding + models/best_weld.pt (input) + models/best_weld.onnx (created) + models/best_weld.engine (created) + USAGE ----- Default (FP16, Ultralytics builds the engine): - python3 1_convert.py + python3 convert.py -Explicit ONNX -> engine with trtexec (engine gets Ultralytics metadata added -so inference scripts still know the class names): - python3 1_convert.py --method trtexec +Explicit ONNX -> engine with trtexec (class-name metadata is added so the +inference script still knows the class names): + python3 convert.py --method trtexec Other options: - python3 1_convert.py --imgsz 640 --precision fp32 --force - python3 1_convert.py --precision int8 --data weld_data.yaml # needs calibration data + python3 convert.py --imgsz 640 --precision fp32 --force + python3 convert.py --precision int8 --data weld_data.yaml # needs calibration data """ import argparse import json +import os import shutil import subprocess import sys @@ -29,7 +35,19 @@ from pathlib import Path from ultralytics import YOLO -from weld_common import ENGINE_PATH, IMGSZ, ONNX_PATH, PT_PATH +# --------------------------------------------------------------------------- +# CONFIG +# --------------------------------------------------------------------------- +# Override without editing the file: export WELD_HOME=/other/path +BASE_DIR = Path(os.environ.get("WELD_HOME", "/home/jetson/projects_2026/welding")) +MODELS_DIR = BASE_DIR / "models" + +PT_PATH = MODELS_DIR / "best_weld.pt" +ONNX_PATH = MODELS_DIR / "best_weld.onnx" +ENGINE_PATH = MODELS_DIR / "best_weld.engine" + +# The engine is locked to this size. Training used 640. +IMGSZ = 640 # --------------------------------------------------------------------------- @@ -51,7 +69,7 @@ def pt_to_onnx(pt_path: Path, imgsz: int, force: bool) -> Path: # --------------------------------------------------------------------------- -# Step 2a: .onnx/.pt -> .engine via Ultralytics (recommended) +# Step 2a: engine via Ultralytics (recommended) # --------------------------------------------------------------------------- def build_engine_ultralytics(pt_path: Path, imgsz: int, precision: str, data: str, workspace: int) -> None: @@ -69,7 +87,7 @@ def build_engine_ultralytics(pt_path: Path, imgsz: int, precision: str, # --------------------------------------------------------------------------- -# Step 2b: .onnx -> .engine via trtexec (explicit route) +# Step 2b: engine via trtexec (explicit route) # --------------------------------------------------------------------------- def find_trtexec() -> str: found = shutil.which("trtexec") @@ -102,7 +120,7 @@ def build_engine_trtexec(pt_path: Path, onnx_path: Path, imgsz: int, # trtexec engines have no such header, so class names would be lost. model = YOLO(str(pt_path)) meta = { - "description": "Weld detection (Bad Weld / Defect / Good Weld)", + "description": "Weld detection (Bad Weld / Good Weld / Defect)", "author": "custom", "date": datetime.now().isoformat(), "version": "custom", @@ -128,7 +146,7 @@ def parse_args(): help="Input size baked into the engine (use your training size).") p.add_argument("--precision", choices=["fp16", "fp32", "int8"], default="fp16") p.add_argument("--method", choices=["ultralytics", "trtexec"], default="ultralytics", - help="How to build the engine from the ONNX/PT.") + help="How to build the engine.") p.add_argument("--data", type=str, default=None, help="Dataset yaml (INT8 calibration only).") p.add_argument("--workspace", type=int, default=4, help="TensorRT workspace in GB.") p.add_argument("--force", action="store_true", help="Rebuild even if outputs exist.") @@ -141,6 +159,7 @@ def main(): if not pt_path.exists(): sys.exit(f"Weights not found: {pt_path}") + MODELS_DIR.mkdir(parents=True, exist_ok=True) onnx_path = pt_to_onnx(pt_path, args.imgsz, args.force) if ENGINE_PATH.exists() and not args.force: @@ -153,7 +172,7 @@ def main(): build_engine_trtexec(pt_path, onnx_path, args.imgsz, args.precision, args.workspace) print(f"\nDone.\n ONNX : {ONNX_PATH}\n Engine: {ENGINE_PATH}") - print("Next: python3 2_infer_image.py or python3 3_infer_video.py") + print("Next: python3 infer.py") if __name__ == "__main__": diff --git a/infer.py b/infer.py new file mode 100644 index 0000000..9224b2f --- /dev/null +++ b/infer.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +""" +infer.py - weld detection with best_weld.engine on images, video, or a live camera. + +The script looks at --source and picks the mode by itself: + image file / folder of images -> image mode + video file / 0 / 1 / csi -> video mode (live camera or file) + +Project root : /home/jetson/projects_2026/welding + models/best_weld.engine + test_images/ input images + test_video.mp4 input video (any .mp4/.avi/.mov/.mkv in the root also works) + results/ ALL outputs (annotated images + videos) are saved here + +USAGE +----- +No --source: first image found, else first video found: + python3 infer.py + +Images: + python3 infer.py --source weld.jpg + python3 infer.py --source ./test_images + python3 infer.py --source ./test_images --show # preview window + +Video file: + python3 infer.py --source test_video.mp4 + +Live camera: + python3 infer.py --source 0 # USB camera + python3 infer.py --source csi # Jetson CSI camera + +Headless over SSH (no window): + python3 infer.py --source 0 --no-display + +Extras (work in every mode): + --conf 0.15 lower the threshold if welds/defects are being missed + --debug print every candidate box, even below --conf + --no-save (video) don't write an output video + +Press 'q' in a preview window to quit. +""" + +import argparse +import os +import sys +import time +from pathlib import Path + +import cv2 +import numpy as np +from ultralytics import YOLO + +# --------------------------------------------------------------------------- +# CONFIG +# --------------------------------------------------------------------------- +# Override without editing the file: export WELD_HOME=/other/path +BASE_DIR = Path(os.environ.get("WELD_HOME", "/home/jetson/projects_2026/welding")) + +MODELS_DIR = BASE_DIR / "models" +TEST_IMAGES_DIR = BASE_DIR / "test_images" +RESULTS_DIR = BASE_DIR / "results" # all outputs are saved here +ENGINE_PATH = MODELS_DIR / "best_weld.engine" + +# The engine is locked to the imgsz it was built with. Training used 640. +IMGSZ = 640 +CONF = 0.25 +IOU = 0.45 +DEVICE = "0" # Jetson GPU + +IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"} +VIDEO_EXTS = {".mp4", ".avi", ".mov", ".mkv"} + +# Where the default source is searched when --source is not given (in order). +DEFAULT_SEARCH_DIRS = [TEST_IMAGES_DIR, BASE_DIR, BASE_DIR / "test_videos"] + +# BGR colours per class name (case-insensitive). Unknown names get a fallback. +CLASS_COLORS = { + "bad weld": (0, 0, 255), # red + "defect": (0, 165, 255), # orange + "good weld": (0, 200, 0), # green +} +FALLBACK_COLOR = (255, 255, 0) + + +# --------------------------------------------------------------------------- +# Model helpers +# --------------------------------------------------------------------------- +def load_model(weights, imgsz, device): + """Load the engine, print class names, and warm it up.""" + path = Path(weights) if weights else ENGINE_PATH + if not path.exists(): + hint = ("Run 'python3 convert.py' first to build the engine." + if path == ENGINE_PATH else "Check the --weights path.") + sys.exit(f"Weights not found: {path}\n{hint}") + + print(f"Loading model: {path}") + model = YOLO(str(path), task="detect") + print(f"Classes: {model.names}") + + print("Warming up (first-inference CUDA/TensorRT init)...") + dummy = np.zeros((imgsz, imgsz, 3), dtype="uint8") + model.predict(source=dummy, imgsz=imgsz, device=device, verbose=False) + print("Ready.") + return model + + +def detect(model, frame, conf, iou, imgsz, device, debug=False): + """Run inference on one BGR frame and return the Ultralytics result.""" + run_conf = 0.05 if debug else conf + result = model.predict(source=frame, conf=run_conf, iou=iou, imgsz=imgsz, + device=device, verbose=False)[0] + if debug: + if len(result.boxes) == 0: + print(" (no candidate boxes)") + for box in result.boxes: + c = float(box.conf[0]) + name = model.names[int(box.cls[0])] + flag = "OK " if c >= conf else "low" + print(f" [{flag}] {name:<12} conf={c:.3f}") + result = result[result.boxes.conf >= conf] + return result + + +def draw_detections(frame, result, names): + """Draw boxes + labels on the frame in place. Returns {class_name: count}.""" + counts = {} + for box in result.boxes: + x1, y1, x2, y2 = map(int, box.xyxy[0]) + cls_id = int(box.cls[0]) + conf = float(box.conf[0]) + name = names.get(cls_id, str(cls_id)) + counts[name] = counts.get(name, 0) + 1 + color = CLASS_COLORS.get(name.lower(), FALLBACK_COLOR) + + label = f"{name} {conf:.2f}" + cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) + (tw, th), base = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 2) + top = max(y1 - th - base - 4, 0) + cv2.rectangle(frame, (x1, top), (x1 + tw + 4, top + th + base + 4), color, -1) + cv2.putText(frame, label, (x1 + 2, top + th + 1), + cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2) + return counts + + +def counts_to_str(counts): + return ", ".join(f"{k}: {v}" for k, v in sorted(counts.items())) or "no detections" + + +# --------------------------------------------------------------------------- +# Source handling +# --------------------------------------------------------------------------- +def find_first(exts): + """First file with a suffix in exts, searched in DEFAULT_SEARCH_DIRS order.""" + for d in DEFAULT_SEARCH_DIRS: + if not d.is_dir(): + continue + for p in sorted(d.iterdir()): + if p.is_file() and p.suffix.lower() in exts: + return p + return None + + +def classify_source(source): + """Return (mode, source) where mode is 'image' or 'video'.""" + if source is None: + img = find_first(IMAGE_EXTS) + if img is not None: + print(f"No --source given, using image: {img.name}") + return "image", str(img) + vid = find_first(VIDEO_EXTS) + if vid is not None: + print(f"No --source given, using video: {vid.name}") + return "video", str(vid) + sys.exit("No image or video found. Use --source path/to/file (or 0 / csi for a camera).") + + if source == "csi" or source.isdigit(): + return "video", source + + path = Path(source) + if not path.exists(): + sys.exit(f"Source not found: {source}") + if path.is_dir(): + return "image", source + if path.suffix.lower() in IMAGE_EXTS: + return "image", source + if path.suffix.lower() in VIDEO_EXTS: + return "video", source + sys.exit(f"Unsupported file type: {path.suffix}") + + +# --------------------------------------------------------------------------- +# Image mode +# --------------------------------------------------------------------------- +def run_images(model, source, args): + path = Path(source) + if path.is_dir(): + images = sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_EXTS) + if not images: + sys.exit(f"No images found in {path}") + else: + images = [path] + + out_dir = Path(args.save_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + for img_path in images: + frame = cv2.imread(str(img_path)) + if frame is None: + print(f"Skipping unreadable file: {img_path}") + continue + + print(f"\n{img_path.name}") + result = detect(model, frame, args.conf, args.iou, args.imgsz, args.device, args.debug) + counts = draw_detections(frame, result, model.names) + print(f" -> {counts_to_str(counts)}") + + out_path = out_dir / f"{img_path.stem}_out{img_path.suffix}" + cv2.imwrite(str(out_path), frame) + print(f" Saved: {out_path}") + + if args.show: + cv2.imshow("Weld Detection", frame) + if cv2.waitKey(0) & 0xFF == ord("q"): + break + + cv2.destroyAllWindows() + print(f"\nDone. {len(images)} image(s) -> {out_dir}") + + +# --------------------------------------------------------------------------- +# Video / camera mode +# --------------------------------------------------------------------------- +def build_csi_pipeline(width=1280, height=720, fps=30): + return ( + f"nvarguscamerasrc ! video/x-raw(memory:NVMM), width={width}, height={height}, " + f"format=NV12, framerate={fps}/1 ! nvvidconv flip-method=0 ! " + f"video/x-raw, width={width}, height={height}, format=BGRx ! " + f"videoconvert ! video/x-raw, format=BGR ! appsink drop=1" + ) + + +def open_capture(source): + if source == "csi": + return cv2.VideoCapture(build_csi_pipeline(), cv2.CAP_GSTREAMER) + if source.isdigit(): + return cv2.VideoCapture(int(source), cv2.CAP_V4L2) + return cv2.VideoCapture(source) + + +def run_video(model, source, args): + cap = open_capture(source) + if not cap.isOpened(): + sys.exit(f"Could not open source: {source}") + + is_camera = source == "csi" or source.isdigit() + + writer = None + if not args.no_save: + if args.save: + out_path = Path(args.save) + else: + name = "camera" if is_camera else Path(source).stem + out_path = Path(args.save_dir) / f"{name}_out.mp4" + out_path.parent.mkdir(parents=True, exist_ok=True) + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280 + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720 + fps_out = cap.get(cv2.CAP_PROP_FPS) or 20 + writer = cv2.VideoWriter(str(out_path), cv2.VideoWriter_fourcc(*"mp4v"), + fps_out, (w, h)) + print(f"Saving output to: {out_path}") + + total_counts = {} + frames = 0 + prev_t = time.time() + print("Running... press 'q' to quit.") + + try: + while True: + ok, frame = cap.read() + if not ok: + print("End of stream / camera read failed.") + break + + result = detect(model, frame, args.conf, args.iou, args.imgsz, + args.device, args.debug) + counts = draw_detections(frame, result, model.names) + for k, v in counts.items(): + total_counts[k] = total_counts.get(k, 0) + v + + now = time.time() + fps = 1.0 / max(now - prev_t, 1e-6) + prev_t = now + cv2.putText(frame, f"FPS: {fps:.1f}", (10, 25), + cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + cv2.putText(frame, counts_to_str(counts), (10, 50), + cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) + + if writer is not None: + writer.write(frame) + if not args.no_display: + cv2.imshow("Weld Detection", frame) + if cv2.waitKey(1) & 0xFF == ord("q"): + break + frames += 1 + except KeyboardInterrupt: + print("\nStopped by user (Ctrl+C).") + finally: + cap.release() + if writer is not None: + writer.release() + cv2.destroyAllWindows() + + print(f"\nProcessed {frames} frame(s). Total detections: {counts_to_str(total_counts)}") + + +# --------------------------------------------------------------------------- +def parse_args(): + p = argparse.ArgumentParser( + description="Weld detection (TensorRT engine) on images, video, or live camera") + p.add_argument("--source", type=str, default=None, + help="Image file/folder, video file, '0'/'1' for USB camera, or 'csi'. " + "Default: first image (else first video) in the welding folder.") + p.add_argument("--weights", type=str, default=None, help="Override engine path.") + p.add_argument("--save-dir", type=str, default=str(RESULTS_DIR), + help="Output folder. Default: results/") + p.add_argument("--save", type=str, default=None, + help="(video) exact output video path. Default: results/_out.mp4") + p.add_argument("--no-save", action="store_true", help="(video) don't write an output video.") + p.add_argument("--show", action="store_true", help="(images) show a preview window.") + p.add_argument("--no-display", action="store_true", help="(video) no preview window.") + p.add_argument("--imgsz", type=int, default=IMGSZ, help="Must match the engine's imgsz.") + p.add_argument("--conf", type=float, default=CONF) + p.add_argument("--iou", type=float, default=IOU) + p.add_argument("--device", type=str, default=DEVICE) + p.add_argument("--debug", action="store_true", + help="Print every candidate box, even below --conf.") + return p.parse_args() + + +def main(): + args = parse_args() + mode, source = classify_source(args.source) + model = load_model(args.weights, args.imgsz, args.device) + + if mode == "image": + run_images(model, source, args) + else: + run_video(model, source, args) + + +if __name__ == "__main__": + main() diff --git a/results/test_video_out.mp4 b/results/test_video_out.mp4 index 08b60ec..40f6dd5 100644 Binary files a/results/test_video_out.mp4 and b/results/test_video_out.mp4 differ diff --git a/weld_common.py b/weld_common.py deleted file mode 100644 index 80d295d..0000000 --- a/weld_common.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python3 -""" -Shared config + helpers for the weld detection scripts. - - -Project root : /home/jetson/projects/welding - models/ best_weld.pt, best_weld.onnx, best_weld.engine - test_images/ input images - test_video.mp4 input video (any .mp4/.avi/.mov/.mkv in the root also works) - results/ ALL outputs (annotated images + videos) are saved here - - -Classes (read from the model itself; training order): Bad Weld, Good Weld, Defect - - -Edit the CONFIG block below if your names or training size differ. -""" - - -import os -from pathlib import Path - - -import cv2 -from ultralytics import YOLO - - -# --------------------------------------------------------------------------- -# CONFIG -# --------------------------------------------------------------------------- -# Project root. Override without editing the file: export WELD_HOME=/other/path -BASE_DIR = Path(os.environ.get("WELD_HOME", "/home/jetson/projects/welding")) - - -MODELS_DIR = BASE_DIR / "models" -TEST_IMAGES_DIR = BASE_DIR / "test_images" -RESULTS_DIR = BASE_DIR / "results" # <- all outputs are saved here - - -PT_PATH = MODELS_DIR / "best_weld.pt" -ONNX_PATH = MODELS_DIR / "best_weld.onnx" -ENGINE_PATH = MODELS_DIR / "best_weld.engine" - - -# IMPORTANT: a TensorRT engine is locked to the imgsz it was built with. -# Training used imgsz=640, so keep 640 unless you rebuild the engine. -IMGSZ = 640 -CONF = 0.25 -IOU = 0.45 -DEVICE = "0" # Jetson GPU. Use "cpu" only for .pt/.onnx testing. - - -IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"} -VIDEO_EXTS = {".mp4", ".avi", ".mov", ".mkv"} - - -# Where find_first() looks when --source is not given (in this order). -DEFAULT_SEARCH_DIRS = [TEST_IMAGES_DIR, BASE_DIR, BASE_DIR / "test_videos"] - - -# BGR colours per class name (case-insensitive). Unknown names get a fallback. -CLASS_COLORS = { - "bad weld": (0, 0, 255), # red - "defect": (0, 165, 255), # orange - "good weld": (0, 200, 0), # green -} -FALLBACK_COLOR = (255, 255, 0) - - - - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- -def find_first(exts, folder=None): - """Return the first file whose suffix is in exts. - - - Searches folder if given, otherwise DEFAULT_SEARCH_DIRS in order - (test_images/, then the project root, then test_videos/). Returns None if nothing matches. - """ - folders = [Path(folder)] if folder else DEFAULT_SEARCH_DIRS - for d in folders: - if not d.is_dir(): - continue - for p in sorted(d.iterdir()): - if p.is_file() and p.suffix.lower() in exts: - return p - return None - - - - -def resolve_weights(weights=None): - """Use --weights if given, else models/best_weld.engine. Never silently falls back to .pt.""" - path = Path(weights) if weights else ENGINE_PATH - if not path.exists(): - hint = ("Run 1_convert.py first to build the engine." - if path == ENGINE_PATH else "Check the --weights path.") - raise FileNotFoundError(f"Weights not found: {path}\n{hint}") - return path - - - - -def load_model(weights=None, imgsz=IMGSZ, device=DEVICE): - """Load the model, print class names, and warm it up.""" - import numpy as np - - - path = resolve_weights(weights) - print(f"Loading model: {path}") - model = YOLO(str(path), task="detect") - print(f"Classes: {model.names}") - - - print("Warming up (first-inference CUDA/TensorRT init)...") - dummy = np.zeros((imgsz, imgsz, 3), dtype="uint8") - model.predict(source=dummy, imgsz=imgsz, device=device, verbose=False) - print("Ready.") - return model - - - - -def detect(model, frame, conf=CONF, iou=IOU, imgsz=IMGSZ, device=DEVICE, debug=False): - """Run inference on one BGR frame and return the Ultralytics result.""" - run_conf = 0.05 if debug else conf - result = model.predict(source=frame, conf=run_conf, iou=iou, imgsz=imgsz, - device=device, verbose=False)[0] - if debug: - if len(result.boxes) == 0: - print(" (no candidate boxes)") - for box in result.boxes: - c = float(box.conf[0]) - name = model.names[int(box.cls[0])] - flag = "OK " if c >= conf else "low" - print(f" [{flag}] {name:<12} conf={c:.3f}") - result = result[result.boxes.conf >= conf] - return result - - - - -def draw_detections(frame, result, names): - """Draw boxes + labels on the frame in place. Returns {class_name: count}.""" - counts = {} - for box in result.boxes: - x1, y1, x2, y2 = map(int, box.xyxy[0]) - cls_id = int(box.cls[0]) - conf = float(box.conf[0]) - name = names.get(cls_id, str(cls_id)) - counts[name] = counts.get(name, 0) + 1 - color = CLASS_COLORS.get(name.lower(), FALLBACK_COLOR) - - - label = f"{name} {conf:.2f}" - cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) - (tw, th), base = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 2) - top = max(y1 - th - base - 4, 0) - cv2.rectangle(frame, (x1, top), (x1 + tw + 4, top + th + base + 4), color, -1) - cv2.putText(frame, label, (x1 + 2, top + th + 1), - cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2) - return counts - - - - -def counts_to_str(counts): - return ", ".join(f"{k}: {v}" for k, v in sorted(counts.items())) or "no detections"