# YOLOv3 ONNX Conversion ## Prerequisites ### 1. Model files (cfg + weights) The Darknet `.cfg` file is already provided in [opencv_extra/testdata/dnn](https://github.com/opencv/opencv_extra/tree/master/testdata/dnn) (`yolov3.cfg`). Download the `.weights` file using the OpenCV test data download script: ```bash git clone https://github.com/opencv/opencv_extra.git cd opencv_extra/testdata/dnn python download_models.py YOLOv3 ``` ### 2. Python environment for `pytorch-YOLOv4` The conversion uses [`pytorch-YOLOv4`](https://github.com/Tianxiaomo/pytorch-YOLOv4). Create a Python environment with the required dependencies: Supported Python versions: **3.8 – 3.10**. ```bash conda create -n python=<3.8-3.10> -y conda activate pip install "torch<2.4" "torchvision<0.19" "numpy<2" onnx onnxruntime "onnxscript==0.1.0" ``` --- ## Conversion of YOLOv3 to ONNX ### Why it requires a patch The original YOLOv3 `.cfg` does not contain the `scale_x_y` field (introduced in YOLOv4). The `pytorch-YOLOv4` converter requires this field unconditionally, causing a `KeyError` when converting YOLOv3. The fix is to default `scale_x_y` to `1.0` when the field is absent. ### The Fix (modified script provided) A patched version of **`darknet2pytorch.py`** is provided in this repository. It adds a default value for `scale_x_y` when the field is absent: ```python # changed line in tool/darknet2pytorch.py yolo_layer.scale_x_y = float(block.get('scale_x_y', 1.0)) ``` ### Conversion Steps ```bash git clone https://github.com/Tianxiaomo/pytorch-YOLOv4.git cd pytorch-YOLOv4 # [!] Replace tool/darknet2pytorch.py with the patched version from this repository # before running the conversion. # Convert YOLOv3 (dynamic batch, batch_size=0) python -c "from tool.darknet2onnx import transform_to_onnx; transform_to_onnx('yolov3.cfg', 'yolov3.weights', 0)" ``` The output file will be named `yolov4_-1_3_416_416_dynamic.onnx` (the script uses `yolov4` as the default prefix regardless of input model). --- ## Usage A demo script is provided to run inference using OpenCV DNN: ```bash python demo.py --model yolov3.onnx \ --image example_outputs/input.jpg \ --output example_outputs/yolov3_output.jpg ``` The demo prints the detected COCO classes, confidence scores, and bounding boxes, and saves an annotated output image. --- ## License See [LICENSE](./LICENSE) — This conversion tool is based on [pytorch-YOLOv4](https://github.com/Tianxiaomo/pytorch-YOLOv4) (Apache-2.0). Original YOLOv3 model weights and configuration are released by Joseph Redmon ([pjreddie/darknet](https://github.com/pjreddie/darknet)).