examples/cpp/LibTorch/README.md
A C++ application that runs every Ultralytics YOLO task and model generation as TorchScript with the LibTorch (PyTorch C++ API) and OpenCV. Point it at any exported .torchscript model; the task, class names, and input size are read from the model metadata, and the right post-processing is selected automatically.
imgsz come from the TorchScript config.txt metadata that Ultralytics embeds on export.Ensure you have the following dependencies installed before proceeding:
| Dependency | Version | Resource |
|---|---|---|
| OpenCV | >=4.0.0 | https://opencv.org/ |
| C++ Standard | >=17 | https://isocpp.org/ |
| CMake | >=3.18 | https://cmake.org/ |
| Libtorch | >=1.12.1 | https://pytorch.org/ |
You can download the required version of LibTorch from the official PyTorch website. Make sure to select the correct version corresponding to your system and CUDA version (if using GPU).
Export any model and task to TorchScript with the Ultralytics export mode:
yolo export model=yolo26n.pt imgsz=640 format=torchscript # detect (also -seg / -pose / -obb / -cls / -sem)
YOLOv8 and YOLO11 grid models work too — the output layout is detected automatically.
See the Export documentation for more options.
git clone https://github.com/ultralytics/ultralytics.git
cd ultralytics/examples/cpp/LibTorch
mkdir build && cd build
# Add -DCMAKE_PREFIX_PATH="/path/to/libtorch;/path/to/opencv" if they are not auto-detected.
cmake .. && cmake --build . --config Release
The shared helpers in ../common are header-only and added to the include path automatically.
# If LibTorch is not installed system-wide, add its libraries to the loader path:
export LD_LIBRARY_PATH=/path/to/libtorch/lib:$LD_LIBRARY_PATH
# Defaults: --model yolo26n.torchscript --source bus.jpg --conf 0.25 --iou 0.45 --out result.jpg
./yolo_libtorch --model yolo26n.torchscript --source bus.jpg
./yolo_libtorch --model yolo26n-seg.torchscript --source bus.jpg --out seg.jpg
./yolo_libtorch --model yolo26n-pose.torchscript --source bus.jpg --show
| Argument | Default | Description |
|---|---|---|
--model | yolo26n.torchscript | Path to the exported TorchScript model (any task). |
--source | bus.jpg | Input image. |
--conf | 0.25 | Confidence threshold. |
--iou | 0.45 | NMS IoU threshold (grid models only). |
--out | result.jpg | Output image path. |
--cuda | off | Use CUDA if the LibTorch build and a device support it. |
--show | off | Also open a display window. |
The annotated result is always written to --out and the detections are printed to the console. The detected task is shown at startup, e.g. Model: yolo26n.torchscript | task: detect | classes: 80.
Contributions are welcome! If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request on the main Ultralytics repository.