Showing preview only (1,251K chars total). Download the full file or copy to clipboard to get everything.
Repository: ultralytics/yolov3
Branch: master
Commit: 5de397bef75c
Files: 136
Total size: 1.2 MB
Directory structure:
gitextract_9q02duc2/
├── .dockerignore
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug-report.yml
│ │ ├── config.yml
│ │ ├── feature-request.yml
│ │ └── question.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── ci-testing.yml
│ ├── cla.yml
│ ├── docker.yml
│ ├── format.yml
│ ├── links.yml
│ ├── merge-main-into-prs.yml
│ └── stale.yml
├── .gitignore
├── CITATION.cff
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── README.zh-CN.md
├── benchmarks.py
├── classify/
│ ├── predict.py
│ ├── train.py
│ ├── tutorial.ipynb
│ └── val.py
├── data/
│ ├── Argoverse.yaml
│ ├── GlobalWheat2020.yaml
│ ├── ImageNet.yaml
│ ├── SKU-110K.yaml
│ ├── VisDrone.yaml
│ ├── coco.yaml
│ ├── coco128-seg.yaml
│ ├── coco128.yaml
│ ├── hyps/
│ │ ├── hyp.Objects365.yaml
│ │ ├── hyp.VOC.yaml
│ │ ├── hyp.no-augmentation.yaml
│ │ ├── hyp.scratch-high.yaml
│ │ ├── hyp.scratch-low.yaml
│ │ └── hyp.scratch-med.yaml
│ ├── objects365.yaml
│ ├── scripts/
│ │ ├── download_weights.sh
│ │ ├── get_coco.sh
│ │ ├── get_coco128.sh
│ │ └── get_imagenet.sh
│ ├── voc.yaml
│ └── xView.yaml
├── detect.py
├── export.py
├── hubconf.py
├── models/
│ ├── __init__.py
│ ├── common.py
│ ├── experimental.py
│ ├── hub/
│ │ ├── anchors.yaml
│ │ ├── yolov5-bifpn.yaml
│ │ ├── yolov5-fpn.yaml
│ │ ├── yolov5-p2.yaml
│ │ ├── yolov5-p34.yaml
│ │ ├── yolov5-p6.yaml
│ │ ├── yolov5-p7.yaml
│ │ ├── yolov5-panet.yaml
│ │ ├── yolov5l6.yaml
│ │ ├── yolov5m6.yaml
│ │ ├── yolov5n6.yaml
│ │ ├── yolov5s-LeakyReLU.yaml
│ │ ├── yolov5s-ghost.yaml
│ │ ├── yolov5s-transformer.yaml
│ │ ├── yolov5s6.yaml
│ │ └── yolov5x6.yaml
│ ├── segment/
│ │ ├── yolov5l-seg.yaml
│ │ ├── yolov5m-seg.yaml
│ │ ├── yolov5n-seg.yaml
│ │ ├── yolov5s-seg.yaml
│ │ └── yolov5x-seg.yaml
│ ├── tf.py
│ ├── yolo.py
│ ├── yolov3-spp.yaml
│ ├── yolov3-tiny.yaml
│ ├── yolov3.yaml
│ ├── yolov5l.yaml
│ ├── yolov5m.yaml
│ ├── yolov5n.yaml
│ ├── yolov5s.yaml
│ └── yolov5x.yaml
├── pyproject.toml
├── requirements.txt
├── segment/
│ ├── predict.py
│ ├── train.py
│ ├── tutorial.ipynb
│ └── val.py
├── train.py
├── tutorial.ipynb
├── utils/
│ ├── __init__.py
│ ├── activations.py
│ ├── augmentations.py
│ ├── autoanchor.py
│ ├── autobatch.py
│ ├── aws/
│ │ ├── __init__.py
│ │ ├── mime.sh
│ │ ├── resume.py
│ │ └── userdata.sh
│ ├── callbacks.py
│ ├── dataloaders.py
│ ├── docker/
│ │ ├── Dockerfile
│ │ ├── Dockerfile-arm64
│ │ └── Dockerfile-cpu
│ ├── downloads.py
│ ├── flask_rest_api/
│ │ ├── README.md
│ │ ├── example_request.py
│ │ └── restapi.py
│ ├── general.py
│ ├── google_app_engine/
│ │ ├── Dockerfile
│ │ ├── additional_requirements.txt
│ │ └── app.yaml
│ ├── loggers/
│ │ ├── __init__.py
│ │ ├── clearml/
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ ├── clearml_utils.py
│ │ │ └── hpo.py
│ │ ├── comet/
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ ├── comet_utils.py
│ │ │ └── hpo.py
│ │ └── wandb/
│ │ ├── __init__.py
│ │ └── wandb_utils.py
│ ├── loss.py
│ ├── metrics.py
│ ├── plots.py
│ ├── segment/
│ │ ├── __init__.py
│ │ ├── augmentations.py
│ │ ├── dataloaders.py
│ │ ├── general.py
│ │ ├── loss.py
│ │ ├── metrics.py
│ │ └── plots.py
│ ├── torch_utils.py
│ └── triton.py
└── val.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
# Repo-specific DockerIgnore -------------------------------------------------------------------------------------------
.git
.cache
.idea
runs
output
coco
storage.googleapis.com
data/samples/*
**/results*.csv
*.jpg
# Neural Network weights -----------------------------------------------------------------------------------------------
**/*.pt
**/*.pth
**/*.onnx
**/*.engine
**/*.mlmodel
**/*.torchscript
**/*.torchscript.pt
**/*.tflite
**/*.h5
**/*.pb
*_saved_model/
*_web_model/
*_openvino_model/
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
wandb/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv*
venv*/
ENV*/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
Icon?
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/*
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.html # Bokeh Plots
.pg # TensorFlow Frozen Graphs
.avi # videos
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
================================================
FILE: .github/ISSUE_TEMPLATE/bug-report.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
name: 🐛 Bug Report
description: "Problems with Ultralytics YOLOv3"
labels: [bug, triage]
type: "bug"
body:
- type: markdown
attributes:
value: |
Thank you for submitting an Ultralytics YOLOv3 🐛 Bug Report!
- type: checkboxes
attributes:
label: Search before asking
description: >
Please search the Ultralytics YOLOv3 [README](https://github.com/ultralytics/yolov3#readme) and [issues](https://github.com/ultralytics/yolov3/issues) to see if a similar bug report already exists.
options:
- label: >
I have searched the [issues](https://github.com/ultralytics/yolov3/issues) and did not find a similar report.
required: true
- type: dropdown
attributes:
label: Project area
description: |
Help us route the report to the right maintainers.
multiple: true
options:
- "Training"
- "Inference"
- "Export/deployment"
- "Documentation"
- "Other"
validations:
required: false
- type: textarea
attributes:
label: Bug
description: Please describe the issue in detail so we can reproduce it in Ultralytics YOLOv3. Include logs, screenshots, console output, and any context that helps explain the problem.
placeholder: |
💡 ProTip! Include as much information as possible (logs, tracebacks, screenshots, etc.) to receive the most helpful response.
validations:
required: true
- type: textarea
attributes:
label: Environment
description: Share the platform and version information relevant to your report.
placeholder: |
Please include:
- OS (e.g., Ubuntu 20.04, macOS 13.5, Windows 11)
- Language or framework version (Python, Swift, Flutter, etc.)
- Package or app version
- Hardware (e.g., CPU, GPU model, device model)
- Any other environment details
validations:
required: true
- type: textarea
attributes:
label: Minimal Reproducible Example
description: >
Provide the smallest possible snippet, command, or steps required to reproduce the issue. This helps us pinpoint problems faster.
placeholder: |
```python
# Code or commands to reproduce your issue here
```
validations:
required: true
- type: textarea
attributes:
label: Additional
description: Anything else you would like to share?
- type: checkboxes
attributes:
label: Are you willing to submit a PR?
description: >
(Optional) We encourage you to submit a [Pull Request](https://github.com/ultralytics/yolov3/pulls) to help improve Ultralytics YOLOv3, especially if you know how to fix the issue.
See the Ultralytics [Contributing Guide](https://docs.ultralytics.com/help/contributing/) to get started.
options:
- label: Yes I'd like to help by submitting a PR!
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
blank_issues_enabled: true
contact_links:
- name: 📘 YOLOv3 README
url: https://github.com/ultralytics/yolov3#readme
about: Usage guide and background for YOLOv3
- name: 💬 Forum
url: https://community.ultralytics.com/
about: Ask the Ultralytics community for workflow help
- name: 🎧 Discord
url: https://ultralytics.com/discord
about: Chat with the Ultralytics team and other builders
- name: ⌨️ Reddit
url: https://reddit.com/r/ultralytics
about: Discuss Ultralytics projects on Reddit
================================================
FILE: .github/ISSUE_TEMPLATE/feature-request.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
name: 🚀 Feature Request
description: "Suggest an Ultralytics YOLOv3 improvement"
labels: [enhancement]
type: "feature"
body:
- type: markdown
attributes:
value: |
Thank you for submitting an Ultralytics YOLOv3 🚀 Feature Request!
- type: checkboxes
attributes:
label: Search before asking
description: >
Please search the Ultralytics YOLOv3 [README](https://github.com/ultralytics/yolov3#readme) and [issues](https://github.com/ultralytics/yolov3/issues) to see if a similar feature request already exists.
options:
- label: >
I have searched https://github.com/ultralytics/yolov3/issues and did not find a similar request.
required: true
- type: textarea
attributes:
label: Description
description: Briefly describe the feature you would like to see added to Ultralytics YOLOv3.
placeholder: |
What new capability or improvement are you proposing?
validations:
required: true
- type: textarea
attributes:
label: Use case
description: Explain how this feature would be used and who benefits from it. Screenshots or mockups are welcome.
placeholder: |
How would this feature improve your workflow?
- type: textarea
attributes:
label: Additional
description: Anything else you would like to share?
- type: checkboxes
attributes:
label: Are you willing to submit a PR?
description: >
(Optional) We encourage you to submit a [Pull Request](https://github.com/ultralytics/yolov3/pulls) to help improve Ultralytics YOLOv3.
See the Ultralytics [Contributing Guide](https://docs.ultralytics.com/help/contributing/) to get started.
options:
- label: Yes I'd like to help by submitting a PR!
================================================
FILE: .github/ISSUE_TEMPLATE/question.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
name: ❓ Question
description: "Ask an Ultralytics YOLOv3 question"
labels: [question]
body:
- type: markdown
attributes:
value: |
Thank you for asking an Ultralytics YOLOv3 ❓ Question!
- type: checkboxes
attributes:
label: Search before asking
description: >
Please search the Ultralytics YOLOv3 [README](https://github.com/ultralytics/yolov3#readme), [issues](https://github.com/ultralytics/yolov3/issues), and [Ultralytics discussions](https://github.com/orgs/ultralytics/discussions) to see if a similar question already exists.
options:
- label: >
I checked the docs, issues, and discussions and could not find an answer.
required: true
- type: textarea
attributes:
label: Question
description: What is your question? Provide as much detail as possible so we can assist with Ultralytics YOLOv3. Include code snippets, screenshots, logs, or links to notebooks/demos.
placeholder: |
💡 ProTip! Include as much information as possible (logs, tracebacks, screenshots, etc.) to receive the most helpful response.
validations:
required: true
- type: textarea
attributes:
label: Additional
description: Anything else you would like to share?
================================================
FILE: .github/dependabot.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# Dependabot for package version updates
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: pip
directory: "/"
schedule:
interval: weekly
time: "04:00"
open-pull-requests-limit: 10
labels:
- dependencies
- package-ecosystem: github-actions
directory: "/.github/workflows"
schedule:
interval: weekly
time: "04:00"
open-pull-requests-limit: 5
labels:
- dependencies
================================================
FILE: .github/workflows/ci-testing.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# YOLOv3 Continuous Integration (CI) GitHub Actions tests
name: YOLOv3 CI
permissions:
contents: read
on:
push:
branches: [master]
pull_request:
branches: [master]
schedule:
- cron: "0 0 * * *" # runs at 00:00 UTC every day
workflow_dispatch:
jobs:
Tests:
timeout-minutes: 60
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest] # macos-latest bug https://github.com/ultralytics/yolov5/pull/9049
python-version: ["3.11"]
model: [yolov5n]
include:
# - os: ubuntu-latest
# python-version: "3.8" # '3.6.8' min (warning, this test is failing)
# model: yolov5n
- os: ubuntu-latest
python-version: "3.9"
model: yolov5n
- os: ubuntu-latest
python-version: "3.8" # torch 1.8.0 requires python >=3.6, <=3.8
model: yolov5n
torch: "1.8.0" # min torch version CI https://pypi.org/project/torchvision/
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
cache: "pip" # caching pip dependencies
- name: Install requirements
run: |
python -m pip install --upgrade pip wheel
torch=""
if [ "${{ matrix.torch }}" == "1.8.0" ]; then
torch="torch==1.8.0 torchvision==0.9.0"
fi
pip install -r requirements.txt $torch --extra-index-url https://download.pytorch.org/whl/cpu
shell: bash # for Windows compatibility
- name: Check environment
run: |
yolo checks
pip list
- name: Test detection
shell: bash # for Windows compatibility
run: |
# export PYTHONPATH="$PWD" # to run '$ python *.py' files in subdirectories
m=${{ matrix.model }} # official weights
b=runs/train/exp/weights/best # best.pt checkpoint
python train.py --imgsz 64 --batch 32 --weights $m.pt --cfg $m.yaml --epochs 1 --device cpu # train
for d in cpu; do # devices
for w in $m $b; do # weights
python val.py --imgsz 64 --batch 32 --weights $w.pt --device $d # val
python detect.py --imgsz 64 --weights $w.pt --device $d # detect
done
done
python hubconf.py --model $m # hub
# python models/tf.py --weights $m.pt # build TF model
python models/yolo.py --cfg $m.yaml # build PyTorch model
python export.py --weights $m.pt --img 64 --include torchscript # export
python - <<EOF
import torch
im = torch.zeros([1, 3, 64, 64])
for path in '$m', '$b':
model = torch.hub.load('.', 'custom', path=path, source='local')
print(model('data/images/bus.jpg'))
model(im) # warmup, build grids for trace
torch.jit.trace(model, [im])
EOF
- name: Test segmentation
shell: bash # for Windows compatibility
run: |
m=${{ matrix.model }}-seg # official weights
b=runs/train-seg/exp/weights/best # best.pt checkpoint
python segment/train.py --imgsz 64 --batch 32 --weights $m.pt --cfg $m.yaml --epochs 1 --device cpu # train
python segment/train.py --imgsz 64 --batch 32 --weights '' --cfg $m.yaml --epochs 1 --device cpu # train
for d in cpu; do # devices
for w in $m $b; do # weights
python segment/val.py --imgsz 64 --batch 32 --weights $w.pt --device $d # val
python segment/predict.py --imgsz 64 --weights $w.pt --device $d # predict
python export.py --weights $w.pt --img 64 --include torchscript --device $d # export
done
done
- name: Test classification
shell: bash # for Windows compatibility
run: |
m=${{ matrix.model }}-cls.pt # official weights
b=runs/train-cls/exp/weights/best.pt # best.pt checkpoint
python classify/train.py --imgsz 32 --model $m --data mnist160 --epochs 1 # train
python classify/val.py --imgsz 32 --weights $b --data ../datasets/mnist160 # val
python classify/predict.py --imgsz 32 --weights $b --source ../datasets/mnist160/test/7/60.png # predict
python classify/predict.py --imgsz 32 --weights $m --source data/images/bus.jpg # predict
python export.py --weights $b --img 64 --include torchscript # export
python - <<EOF
import torch
for path in '$m', '$b':
model = torch.hub.load('.', 'custom', path=path, source='local')
EOF
Summary:
runs-on: ubuntu-latest
needs: [Tests]
if: always()
steps:
- name: Check for failure and notify
if: (needs.Tests.result == 'failure' || needs.Tests.result == 'cancelled') && github.repository == 'ultralytics/yolov3' && (github.event_name == 'schedule' || github.event_name == 'push')
uses: slackapi/slack-github-action@v3.0.1
with:
webhook-type: incoming-webhook
webhook: ${{ secrets.SLACK_WEBHOOK_URL_YOLO }}
payload: |
text: "<!channel> GitHub Actions error for ${{ github.workflow }} ❌\n\n\n*Repository:* https://github.com/${{ github.repository }}\n*Action:* https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}\n*Author:* ${{ github.actor }}\n*Event:* ${{ github.event_name }}\n"
================================================
FILE: .github/workflows/cla.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# Ultralytics Contributor License Agreement (CLA) action https://docs.ultralytics.com/help/CLA
# This workflow automatically requests Pull Requests (PR) authors to sign the Ultralytics CLA before PRs can be merged
name: CLA Assistant
on:
issue_comment:
types:
- created
pull_request_target:
types:
- reopened
- opened
- synchronize
permissions:
actions: write
contents: write
pull-requests: write
statuses: write
jobs:
CLA:
if: github.repository == 'ultralytics/yolov3'
runs-on: ubuntu-latest
steps:
- name: CLA Assistant
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I sign the CLA') || github.event_name == 'pull_request_target'
uses: contributor-assistant/github-action@v2.6.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Must be repository secret PAT
PERSONAL_ACCESS_TOKEN: ${{ secrets._GITHUB_TOKEN }}
with:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://docs.ultralytics.com/help/CLA" # CLA document
# Branch must not be protected
branch: cla-signatures
allowlist: dependabot[bot],github-actions,[pre-commit*,pre-commit*,bot*
remote-organization-name: ultralytics
remote-repository-name: cla
custom-pr-sign-comment: "I have read the CLA Document and I sign the CLA"
custom-allsigned-prcomment: All Contributors have signed the CLA. ✅
================================================
FILE: .github/workflows/docker.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# Builds ultralytics/yolov3:latest images on DockerHub https://hub.docker.com/r/ultralytics/yolov3
name: Publish Docker Images
permissions:
contents: read
on:
push:
branches: [master]
workflow_dispatch:
jobs:
docker:
if: github.repository == 'ultralytics/yolov3'
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v6
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push arm64 image
uses: docker/build-push-action@v7
continue-on-error: true
with:
context: .
platforms: linux/arm64
file: utils/docker/Dockerfile-arm64
push: true
tags: ultralytics/yolov3:latest-arm64
- name: Build and push CPU image
uses: docker/build-push-action@v7
continue-on-error: true
with:
context: .
file: utils/docker/Dockerfile-cpu
push: true
tags: ultralytics/yolov3:latest-cpu
- name: Build and push GPU image
uses: docker/build-push-action@v7
continue-on-error: true
with:
context: .
file: utils/docker/Dockerfile
push: true
tags: ultralytics/yolov3:latest
================================================
FILE: .github/workflows/format.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# Ultralytics Actions https://github.com/ultralytics/actions
# This workflow formats code and documentation in PRs to Ultralytics standards
name: Ultralytics Actions
on:
issues:
types: [opened]
pull_request:
branches: [main, master]
types: [opened, closed, synchronize, review_requested]
permissions:
contents: write # Modify code in PRs
pull-requests: write # Add comments and labels to PRs
issues: write # Add comments and labels to issues
jobs:
actions:
runs-on: ubuntu-latest
steps:
- name: Run Ultralytics Actions
uses: ultralytics/actions@main
with:
token: ${{ secrets._GITHUB_TOKEN || secrets.GITHUB_TOKEN }} # Auto-generated token
labels: true # Auto-label issues/PRs using AI
python: true # Format Python with Ruff and docformatter
prettier: true # Format YAML, JSON, Markdown, CSS
spelling: true # Check spelling with codespell
links: false # Check broken links with Lychee
summary: true # Generate AI-powered PR summaries
openai_api_key: ${{ secrets.OPENAI_API_KEY }} # Powers PR summaries, labels and comments
brave_api_key: ${{ secrets.BRAVE_API_KEY }} # Used for broken link resolution
================================================
FILE: .github/workflows/links.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# Continuous Integration (CI) GitHub Actions tests broken link checker using https://github.com/lycheeverse/lychee
# Ignores the following status codes to reduce false positives:
# - 403(OpenVINO, 'forbidden')
# - 429(Instagram, 'too many requests')
# - 500(Zenodo, 'cached')
# - 502(Zenodo, 'bad gateway')
# - 999(LinkedIn, 'unknown status code')
name: Check Broken links
permissions:
contents: read
on:
workflow_dispatch:
schedule:
- cron: "0 0 * * *" # runs at 00:00 UTC every day
jobs:
Links:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Install lychee
run: curl -sSfL "https://github.com/lycheeverse/lychee/releases/latest/download/lychee-x86_64-unknown-linux-gnu.tar.gz" | sudo tar xz -C /usr/local/bin
- name: Test Markdown and HTML links with retry
uses: ultralytics/actions/retry@main
with:
timeout_minutes: 5
retry_delay_seconds: 60
retries: 2
run: |
lychee \
--scheme 'https' \
--timeout 60 \
--insecure \
--accept 100..=103,200..=299,401,403,429,500,502,999 \
--exclude-all-private \
--exclude 'https?://(www\.)?(linkedin\.com|twitter\.com|x\.com|instagram\.com|kaggle\.com|fonts\.gstatic\.com|url\.com)' \
--exclude-path './**/ci.yml' \
--github-token ${{ secrets.GITHUB_TOKEN }} \
--header "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.6478.183 Safari/537.36" \
'./**/*.md' \
'./**/*.html' | tee -a $GITHUB_STEP_SUMMARY
# Raise error if broken links found
if ! grep -q "0 Errors" $GITHUB_STEP_SUMMARY; then
exit 1
fi
- name: Test Markdown, HTML, YAML, Python and Notebook links with retry
if: github.event_name == 'workflow_dispatch'
uses: ultralytics/actions/retry@main
with:
timeout_minutes: 5
retry_delay_seconds: 60
retries: 2
run: |
lychee \
--scheme 'https' \
--timeout 60 \
--insecure \
--accept 100..=103,200..=299,429,999 \
--exclude-all-private \
--exclude 'https?://(www\.)?(linkedin\.com|twitter\.com|x\.com|instagram\.com|kaggle\.com|fonts\.gstatic\.com|url\.com)' \
--exclude-path './**/ci.yml' \
--github-token ${{ secrets.GITHUB_TOKEN }} \
--header "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.6478.183 Safari/537.36" \
'./**/*.md' \
'./**/*.html' \
'./**/*.yml' \
'./**/*.yaml' \
'./**/*.py' \
'./**/*.ipynb' | tee -a $GITHUB_STEP_SUMMARY
# Raise error if broken links found
if ! grep -q "0 Errors" $GITHUB_STEP_SUMMARY; then
exit 1
fi
================================================
FILE: .github/workflows/merge-main-into-prs.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# Automatically merges repository 'main' branch into all open PRs to keep them up-to-date
# Action runs on updates to main branch so when one PR merges to main all others update
name: Merge main into PRs
on:
workflow_dispatch:
# push:
# branches:
# - ${{ github.event.repository.default_branch }}
jobs:
Merge:
if: github.repository == 'ultralytics/yolov3'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions/setup-python@v6
with:
python-version: "3.x"
cache: "pip"
- name: Install requirements
run: |
pip install pygithub
- name: Merge default branch into PRs
shell: python
run: |
from github import Github
import os
g = Github(os.getenv('GITHUB_TOKEN'))
repo = g.get_repo(os.getenv('GITHUB_REPOSITORY'))
# Fetch the default branch name
default_branch_name = repo.default_branch
default_branch = repo.get_branch(default_branch_name)
for pr in repo.get_pulls(state='open', sort='created'):
try:
# Get full names for repositories and branches
base_repo_name = repo.full_name
head_repo_name = pr.head.repo.full_name
base_branch_name = pr.base.ref
head_branch_name = pr.head.ref
# Check if PR is behind the default branch
comparison = repo.compare(default_branch.commit.sha, pr.head.sha)
if comparison.behind_by > 0:
print(f"⚠️ PR #{pr.number} ({head_repo_name}:{head_branch_name} -> {base_repo_name}:{base_branch_name}) is behind {default_branch_name} by {comparison.behind_by} commit(s).")
# Attempt to update the branch
try:
success = pr.update_branch()
assert success, "Branch update failed"
print(f"✅ Successfully merged '{default_branch_name}' into PR #{pr.number} ({head_repo_name}:{head_branch_name} -> {base_repo_name}:{base_branch_name}).")
except Exception as update_error:
print(f"❌ Could not update PR #{pr.number} ({head_repo_name}:{head_branch_name} -> {base_repo_name}:{base_branch_name}): {update_error}")
print(" This might be due to branch protection rules or insufficient permissions.")
else:
print(f"✅ PR #{pr.number} ({head_repo_name}:{head_branch_name} -> {base_repo_name}:{base_branch_name}) is up to date with {default_branch_name}.")
except Exception as e:
print(f"❌ Could not process PR #{pr.number}: {e}")
env:
GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }}
GITHUB_REPOSITORY: ${{ github.repository }}
================================================
FILE: .github/workflows/stale.yml
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
name: Close stale issues
permissions:
contents: read
issues: write
pull-requests: write
on:
schedule:
- cron: "0 0 * * *" # Runs at 00:00 UTC every day
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v10
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: |
👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.
For additional resources and information, please see the links below:
- **Docs**: https://docs.ultralytics.com
- **Platform**: https://platform.ultralytics.com
- **Community**: https://community.ultralytics.com
Feel free to inform us of any other **issues** you discover or **feature requests** that come to mind in the future. Pull Requests (PRs) are also always welcomed!
Thank you for your contributions to YOLO 🚀 and Vision AI ⭐
stale-pr-message: |
👋 Hello there! We wanted to let you know that we've decided to close this pull request due to inactivity. We appreciate the effort you put into contributing to our project, but unfortunately, not all contributions are suitable or aligned with our product roadmap.
We hope you understand our decision, and please don't let it discourage you from contributing to open source projects in the future. We value all of our community members and their contributions, and we encourage you to keep exploring new projects and ways to get involved.
For additional resources and information, please see the links below:
- **Docs**: https://docs.ultralytics.com
- **Platform**: https://platform.ultralytics.com
- **Community**: https://community.ultralytics.com
Thank you for your contributions to YOLO 🚀 and Vision AI ⭐
days-before-issue-stale: 30
days-before-issue-close: 10
days-before-pr-stale: 90
days-before-pr-close: 30
exempt-issue-labels: "documentation,tutorial,TODO"
operations-per-run: 300 # The maximum number of operations per run, used to control rate limiting.
================================================
FILE: .gitignore
================================================
# Repo-specific GitIgnore ----------------------------------------------------------------------------------------------
*.jpg
*.jpeg
*.png
*.bmp
*.tif
*.tiff
*.heic
*.JPG
*.JPEG
*.PNG
*.BMP
*.TIF
*.TIFF
*.HEIC
*.mp4
*.mov
*.MOV
*.avi
*.data
*.json
*.cfg
!setup.cfg
!cfg/yolov3*.cfg
storage.googleapis.com
runs/*
data/*
data/images/*
!data/*.yaml
!data/hyps
!data/scripts
!data/images
!data/images/zidane.jpg
!data/images/bus.jpg
!data/*.sh
results*.csv
# Datasets -------------------------------------------------------------------------------------------------------------
coco/
coco128/
VOC/
# MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
*.m~
*.mat
!targets*.mat
# Neural Network weights -----------------------------------------------------------------------------------------------
*.weights
*.pt
*.pb
*.onnx
*.engine
*.mlmodel
*.torchscript
*.tflite
*.h5
*_saved_model/
*_web_model/
*_openvino_model/
*_paddle_model/
darknet53.conv.74
yolov3-tiny.conv.15
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
/wandb/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv*
venv*/
ENV*/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
Icon?
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/*
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.html # Bokeh Plots
.pg # TensorFlow Frozen Graphs
.avi # videos
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
================================================
FILE: CITATION.cff
================================================
cff-version: 1.2.0
preferred-citation:
type: software
message: If you use YOLOv5, please cite it as below.
authors:
- family-names: Jocher
given-names: Glenn
orcid: "https://orcid.org/0000-0001-5950-6979"
title: "YOLOv5 by Ultralytics"
version: 7.0
doi: 10.5281/zenodo.3908559
date-released: 2020-5-29
license: AGPL-3.0
url: "https://github.com/ultralytics/yolov5"
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing To YOLOv3 🚀
We value your input and welcome your contributions to Ultralytics YOLOv3! Whether you're interested in:
- Reporting a bug
- Discussing the current state of the codebase
- Submitting a fix
- Proposing a new feature
- Becoming a maintainer
Ultralytics YOLO models are successful thanks to the collective efforts of our community. Every improvement you contribute helps advance the possibilities of AI and computer vision! 😃
## Submitting A Pull Request (PR) 🛠️
Contributing a PR is straightforward! Here’s a step-by-step example for updating `requirements.txt`:
### 1. Select The File To Update
Click on `requirements.txt` in the GitHub repository to open it.
<p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
### 2. Click 'Edit This File'
Use the pencil icon in the top-right corner to begin editing.
<p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
### 3. Make Your Changes
For example, update the `matplotlib` version from `3.2.2` to `3.3`.
<p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
### 4. Preview And Submit Your PR
Switch to the **Preview changes** tab to review your edits. At the bottom, select 'Create a new branch for this commit', give your branch a descriptive name like `fix/matplotlib_version`, and click the green **Propose changes** button. Your PR is now submitted for review! 😃
<p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
### PR Best Practices
To ensure your contribution is integrated smoothly, please:
- ✅ Ensure your PR is **up-to-date** with the `ultralytics/yolov3` `master` branch. If your PR is behind, update your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
<p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 15" src="https://user-images.githubusercontent.com/26833433/187295893-50ed9f44-b2c9-4138-a614-de69bd1753d7.png"></p>
- ✅ Confirm that all Continuous Integration (CI) **checks are passing**.
<p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 03" src="https://user-images.githubusercontent.com/26833433/187296922-545c5498-f64a-4d8c-8300-5fa764360da6.png"></p>
- ✅ Limit your changes to the **minimum required** for your bug fix or feature.
_"It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
## Submitting A Bug Report 🐛
If you encounter an issue with Ultralytics YOLOv3, please submit a bug report!
To help us investigate, please provide a [minimum reproducible example](https://docs.ultralytics.com/help/minimum-reproducible-example/). Your code should be:
- ✅ **Minimal** – Use as little code as possible that still produces the issue.
- ✅ **Complete** – Include all parts needed for someone else to reproduce the problem.
- ✅ **Reproducible** – Test your code to ensure it reliably triggers the issue.
Additionally, for [Ultralytics](https://www.ultralytics.com/) to assist, your code should be:
- ✅ **Current** – Ensure your code is up-to-date with the latest [master branch](https://github.com/ultralytics/yolov3/tree/master). Use `git pull` or `git clone` to get the latest version.
- ✅ **Unmodified** – The problem must be reproducible without custom modifications to the repository. [Ultralytics](https://www.ultralytics.com/) does not provide support for custom code.
If your issue meets these criteria, please close your current issue and open a new one using the 🐛 **Bug Report** [template](https://github.com/ultralytics/yolov3/issues/new/choose), including your [minimum reproducible example](https://docs.ultralytics.com/help/minimum-reproducible-example/) to help us diagnose and resolve your problem.
## License
By contributing, you agree that your submissions will be licensed under the [AGPL-3.0 license](https://choosealicense.com/licenses/agpl-3.0/).
---
Thank you for helping improve Ultralytics YOLOv3! Your contributions make a difference. For more on open-source best practices, check out the [Ultralytics open-source community](https://www.ultralytics.com/blog/tips-to-start-contributing-to-ultralytics-open-source-projects) and [GitHub's open source guides](https://opensource.guide/how-to-contribute/).
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: README.md
================================================
<div align="center">
<p>
<a href="https://platform.ultralytics.com/?utm_source=github&utm_medium=referral&utm_campaign=platform_launch&utm_content=banner&utm_term=ultralytics_github" target="_blank">
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov3/banner-yolov3.png" alt="Ultralytics YOLOv3 banner"></a>
</p>
[中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es) | [Português](https://docs.ultralytics.com/pt/) | [Türkçe](https://docs.ultralytics.com/tr/) | [Tiếng Việt](https://docs.ultralytics.com/vi/) | [العربية](https://docs.ultralytics.com/ar/)
<div>
<a href="https://github.com/ultralytics/yolov3/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov3/actions/workflows/ci-testing.yml/badge.svg" alt="YOLOv3 CI"></a>
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv3 Citation"></a>
<a href="https://hub.docker.com/r/ultralytics/yolov3"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov3?logo=docker" alt="Docker Pulls"></a>
<a href="https://discord.com/invite/ultralytics"><img alt="Discord" src="https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue"></a>
<a href="https://community.ultralytics.com/"><img alt="Ultralytics Forums" src="https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue"></a>
<a href="https://www.reddit.com/r/ultralytics/"><img alt="Ultralytics Reddit" src="https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue"></a>
<br>
<a href="https://bit.ly/yolov5-paperspace-notebook"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"></a>
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
<a href="https://www.kaggle.com/models/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
</div>
<br>
Ultralytics YOLOv3 is a robust and efficient [computer vision](https://www.ultralytics.com/glossary/computer-vision-cv) model developed by [Ultralytics](https://www.ultralytics.com/). Built on the [PyTorch](https://pytorch.org/) framework, this implementation extends the original YOLOv3 architecture, renowned for its improvements in [object detection](https://www.ultralytics.com/glossary/object-detection) speed and accuracy over earlier versions. It incorporates best practices and insights from extensive research, making it a reliable choice for a wide range of vision AI applications.
Explore the [Ultralytics Docs](https://docs.ultralytics.com/) for in-depth guidance (YOLOv3-specific docs may be limited, but general YOLO principles apply), open an issue on [GitHub](https://github.com/ultralytics/yolov5/issues/new/choose) for support, and join our [Discord community](https://discord.com/invite/ultralytics) for questions and discussions!
For Enterprise License requests, please complete the form at [Ultralytics Licensing](https://www.ultralytics.com/license).
<div align="center">
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="2%" alt="Ultralytics GitHub"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="2%" alt="Ultralytics LinkedIn"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="2%" alt="Ultralytics Twitter"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="2%" alt="Ultralytics YouTube"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="2%" alt="Ultralytics TikTok"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="2%" alt="Ultralytics BiliBili"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://discord.com/invite/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="2%" alt="Ultralytics Discord"></a>
</div>
</div>
<br>
## 🚀 YOLO11: The Next Evolution
We are thrilled to introduce **Ultralytics YOLO11** 🚀, the latest advancement in our state-of-the-art vision models! Available now at the [Ultralytics YOLO GitHub repository](https://github.com/ultralytics/ultralytics), YOLO11 continues our legacy of speed, precision, and user-friendly design. Whether you're working on [object detection](https://docs.ultralytics.com/tasks/detect/), [instance segmentation](https://docs.ultralytics.com/tasks/segment/), [pose estimation](https://docs.ultralytics.com/tasks/pose/), [image classification](https://docs.ultralytics.com/tasks/classify/), or [oriented object detection (OBB)](https://docs.ultralytics.com/tasks/obb/), YOLO11 delivers the performance and flexibility needed for modern computer vision tasks.
Get started today and unlock the full potential of YOLO11! Visit the [Ultralytics Docs](https://docs.ultralytics.com/) for comprehensive guides and resources:
[](https://badge.fury.io/py/ultralytics) [](https://pepy.tech/projects/ultralytics)
```bash
# Install the ultralytics package
pip install ultralytics
```
<div align="center">
<a href="https://www.ultralytics.com/yolo" target="_blank">
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/refs/heads/main/yolo/performance-comparison.png" alt="Ultralytics YOLO Performance Comparison"></a>
</div>
## 📚 Documentation
See the [Ultralytics Docs for YOLOv3](https://docs.ultralytics.com/models/yolov3/) for full documentation on training, testing, and deployment using the Ultralytics framework. While YOLOv3-specific documentation may be limited, the general YOLO principles apply. Below are quickstart examples adapted for YOLOv3 concepts.
<details open>
<summary>Install</summary>
Clone the repository and install dependencies from `requirements.txt` in a [**Python>=3.8.0**](https://www.python.org/) environment. Ensure you have [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/) installed. (Note: This repo is originally YOLOv5, dependencies should be compatible but tailored testing for YOLOv3 is recommended).
```bash
# Clone the YOLOv3 repository
git clone https://github.com/ultralytics/yolov3
# Navigate to the cloned directory
cd yolov3
# Install required packages
pip install -r requirements.txt
```
</details>
<details open>
<summary>Inference with PyTorch Hub</summary>
Use YOLOv3 via [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading/) for inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) like `yolov3.pt`, `yolov3-spp.pt`, `yolov3-tiny.pt` can be loaded.
```python
import torch
# Load a YOLOv3 model (e.g., yolov3, yolov3-spp)
model = torch.hub.load("ultralytics/yolov3", "yolov3", pretrained=True) # specify 'yolov3' or other variants
# Define the input image source (URL, local file, PIL image, OpenCV frame, numpy array, or list)
img = "https://ultralytics.com/images/zidane.jpg" # Example image
# Perform inference
results = model(img)
# Process the results (options: .print(), .show(), .save(), .crop(), .pandas())
results.print() # Print results to console
results.show() # Display results in a window
results.save() # Save results to runs/detect/exp
```
</details>
<details>
<summary>Inference with detect.py</summary>
The `detect.py` script runs inference on various sources. Use `--weights yolov3.pt` or other YOLOv3 variants. It automatically downloads models and saves results to `runs/detect`.
```bash
# Run inference using a webcam with yolov3-tiny
python detect.py --weights yolov3-tiny.pt --source 0
# Run inference on a local image file with yolov3
python detect.py --weights yolov3.pt --source img.jpg
# Run inference on a local video file with yolov3-spp
python detect.py --weights yolov3-spp.pt --source vid.mp4
# Run inference on a screen capture
python detect.py --weights yolov3.pt --source screen
# Run inference on a directory of images
python detect.py --weights yolov3.pt --source path/to/images/
# Run inference on a text file listing image paths
python detect.py --weights yolov3.pt --source list.txt
# Run inference on a text file listing stream URLs
python detect.py --weights yolov3.pt --source list.streams
# Run inference using a glob pattern for images
python detect.py --weights yolov3.pt --source 'path/to/*.jpg'
# Run inference on a YouTube video URL
python detect.py --weights yolov3.pt --source 'https://youtu.be/LNwODJXcvt4'
# Run inference on an RTSP, RTMP, or HTTP stream
python detect.py --weights yolov3.pt --source 'rtsp://example.com/media.mp4'
```
</details>
<details>
<summary>Training</summary>
The commands below show how to train YOLOv3 models on the [COCO dataset](https://docs.ultralytics.com/datasets/detect/coco/). Models and datasets are downloaded automatically. Use the largest `--batch-size` your hardware allows.
```bash
# Train YOLOv3-tiny on COCO for 300 epochs (example settings)
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov3-tiny.yaml --batch-size 64
# Train YOLOv3 on COCO for 300 epochs (example settings)
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov3.yaml --batch-size 32
# Train YOLOv3-SPP on COCO for 300 epochs (example settings)
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov3-spp.yaml --batch-size 16
```
</details>
<details open>
<summary>Tutorials</summary>
Note: These tutorials primarily use YOLOv5 examples but the principles often apply to YOLOv3 within the Ultralytics framework.
- **[Train Custom Data](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data/)** 🚀 **RECOMMENDED**: Learn how to train models on your own datasets.
- **[Tips for Best Training Results](https://docs.ultralytics.com/guides/model-training-tips/)** ☘️: Improve your model's performance with expert tips.
- **[Multi-GPU Training](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training/)**: Speed up training using multiple GPUs.
- **[PyTorch Hub Integration](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading/)** 🌟 **NEW**: Easily load models using PyTorch Hub.
- **[Model Export (TFLite, ONNX, CoreML, TensorRT)](https://docs.ultralytics.com/yolov5/tutorials/model_export/)** 🚀: Convert your models to various deployment formats.
- **[NVIDIA Jetson Deployment](https://docs.ultralytics.com/guides/nvidia-jetson/)** 🌟 **NEW**: Deploy models on NVIDIA Jetson devices.
- **[Test-Time Augmentation (TTA)](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation/)**: Enhance prediction accuracy with TTA.
- **[Model Ensembling](https://docs.ultralytics.com/yolov5/tutorials/model_ensembling/)**: Combine multiple models for better performance.
- **[Model Pruning/Sparsity](https://docs.ultralytics.com/yolov5/tutorials/model_pruning_and_sparsity/)**: Optimize models for size and speed.
- **[Hyperparameter Evolution](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution/)**: Automatically find the best training hyperparameters.
- **[Transfer Learning with Frozen Layers](https://docs.ultralytics.com/yolov5/tutorials/transfer_learning_with_frozen_layers/)**: Adapt pretrained models to new tasks efficiently.
- **[Architecture Summary](https://docs.ultralytics.com/yolov5/tutorials/architecture_description/)** 🌟 **NEW**: Understand the model architecture (focus on YOLOv3 principles).
- **[Ultralytics Platform Training](https://platform.ultralytics.com)** 🚀 **RECOMMENDED**: Train and deploy YOLO models using Ultralytics Platform.
- **[ClearML Logging](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration/)**: Integrate with ClearML for experiment tracking.
- **[Neural Magic DeepSparse Integration](https://docs.ultralytics.com/yolov5/tutorials/neural_magic_pruning_quantization/)**: Accelerate inference with DeepSparse.
- **[Comet Logging](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration/)** 🌟 **NEW**: Log experiments using Comet ML.
</details>
## 🧩 Integrations
Ultralytics offers robust integrations with leading AI platforms to enhance your workflow, including dataset labeling, training, visualization, and model management. Discover how Ultralytics, in collaboration with partners like [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases/), [Comet ML](https://docs.ultralytics.com/integrations/comet/), [Roboflow](https://docs.ultralytics.com/integrations/roboflow/), and [Intel OpenVINO](https://docs.ultralytics.com/integrations/openvino/), can optimize your AI projects. Explore more at [Ultralytics Integrations](https://docs.ultralytics.com/integrations/).
<a href="https://docs.ultralytics.com/integrations/" target="_blank">
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics active learning integrations">
</a>
<br>
<br>
<div align="center">
<a href="https://platform.ultralytics.com">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-ultralytics-hub.png" width="10%" alt="Ultralytics Platform logo"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="space">
<a href="https://docs.ultralytics.com/integrations/weights-biases/">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-wb.png" width="10%" alt="Weights & Biases logo"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="space">
<a href="https://docs.ultralytics.com/integrations/comet/">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-comet.png" width="10%" alt="Comet ML logo"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="space">
<a href="https://docs.ultralytics.com/integrations/neural-magic/">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-neuralmagic.png" width="10%" alt="Neural Magic logo"></a>
</div>
| Ultralytics Platform 🌟 | Weights & Biases | Comet | Neural Magic |
| :--------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------: |
| Streamline YOLO workflows: Label, train, and deploy effortlessly with [Ultralytics Platform](https://platform.ultralytics.com). Try now! | Track experiments, hyperparameters, and results with [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases/). | Free forever, [Comet ML](https://docs.ultralytics.com/integrations/comet/) lets you save YOLO models, resume training, and interactively visualize predictions. | Run YOLO inference up to 6x faster with [Neural Magic DeepSparse](https://docs.ultralytics.com/integrations/neural-magic/). |
## ⭐ Ultralytics Platform
Experience seamless AI development with [Ultralytics Platform](https://platform.ultralytics.com) ⭐, the ultimate platform for building, training, and deploying computer vision models. Visualize datasets, train YOLOv3, YOLOv5, and YOLOv8 🚀 models, and deploy them to real-world applications without writing any code. Transform images into actionable insights using our advanced tools and user-friendly [Ultralytics App](https://www.ultralytics.com/app-install). Start your journey for **Free** today!
<a align="center" href="https://platform.ultralytics.com" target="_blank">
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png" alt="Ultralytics Platform Platform Screenshot"></a>
## 🤔 Why YOLOv3?
YOLOv3 marked a major leap forward in real-time object detection at its release. Key advantages include:
- **Improved Accuracy:** Enhanced detection of small objects compared to YOLOv2.
- **Multi-Scale Predictions:** Detects objects at three different scales, boosting performance across varied object sizes.
- **Class Prediction:** Uses logistic classifiers for object classes, enabling multi-label classification.
- **Feature Extractor:** Employs a deeper network (Darknet-53) versus the Darknet-19 used in YOLOv2.
While newer models like YOLOv5 and YOLO11 offer further advancements, YOLOv3 remains a reliable and widely adopted baseline, efficiently implemented in PyTorch by Ultralytics.
## ☁️ Environments
Get started quickly with our pre-configured environments. Click the icons below for setup details.
<div align="center">
<a href="https://docs.ultralytics.com/integrations/paperspace/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gradient.png" width="10%" alt="Run on Gradient"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/google-colab/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-colab-small.png" width="10%" alt="Open In Colab"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/kaggle/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-kaggle-small.png" width="10%" alt="Open In Kaggle"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/guides/docker-quickstart/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-docker-small.png" width="10%" alt="Docker Image"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/amazon-sagemaker/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-aws-small.png" width="10%" alt="AWS Marketplace"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/google-colab/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gcp-small.png" width="10%" alt="GCP Quickstart"/></a>
</div>
## 🤝 Contribute
We welcome your contributions! Making YOLO models accessible and effective is a community effort. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing/) to get started. Share your feedback through the [Ultralytics Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). Thank you to all our contributors for making Ultralytics YOLO better!
[](https://github.com/ultralytics/yolov5/graphs/contributors)
## 📜 License
Ultralytics provides two licensing options to meet different needs:
- **AGPL-3.0 License**: An [OSI-approved](https://opensource.org/license/agpl-v3) open-source license ideal for academic research, personal projects, and testing. It promotes open collaboration and knowledge sharing. See the [LICENSE](https://github.com/ultralytics/yolov5/blob/master/LICENSE) file for details.
- **Enterprise License**: Tailored for commercial applications, this license allows seamless integration of Ultralytics software and AI models into commercial products and services, bypassing the open-source requirements of AGPL-3.0. For commercial use cases, please contact us via [Ultralytics Licensing](https://www.ultralytics.com/license).
## 📧 Contact
For bug reports and feature requests related to Ultralytics YOLO implementations, please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For general questions, discussions, and community support, join our [Discord server](https://discord.com/invite/ultralytics)!
<br>
<div align="center">
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="3%" alt="Ultralytics GitHub"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="3%" alt="Ultralytics LinkedIn"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="3%" alt="Ultralytics Twitter"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="3%" alt="Ultralytics YouTube"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="3%" alt="Ultralytics TikTok"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="3%" alt="Ultralytics BiliBili"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://discord.com/invite/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="3%" alt="Ultralytics Discord"></a>
</div>
================================================
FILE: README.zh-CN.md
================================================
<a href="https://www.ultralytics.com/"><img src="https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg" width="320" alt="Ultralytics logo"></a>
<div align="center">
<p>
<a href="https://platform.ultralytics.com/?utm_source=github&utm_medium=referral&utm_campaign=platform_launch&utm_content=banner&utm_term=ultralytics_github" target="_blank">
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov3/banner-yolov3.png" alt="Ultralytics YOLOv3 banner"></a>
</p>
[English](https://docs.ultralytics.com/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es) | [Português](https://docs.ultralytics.com/pt/) | [Türkçe](https://docs.ultralytics.com/tr/) | [Tiếng Việt](https://docs.ultralytics.com/vi/) | [العربية](https://docs.ultralytics.com/ar/)
<div>
<a href="https://github.com/ultralytics/yolov3/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov3/actions/workflows/ci-testing.yml/badge.svg" alt="YOLOv3 CI"></a>
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv3 Citation"></a>
<a href="https://hub.docker.com/r/ultralytics/yolov3"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov3?logo=docker" alt="Docker Pulls"></a>
<a href="https://discord.com/invite/ultralytics"><img alt="Discord" src="https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue"></a>
<a href="https://community.ultralytics.com/"><img alt="Ultralytics Forums" src="https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue"></a>
<a href="https://www.reddit.com/r/ultralytics/"><img alt="Ultralytics Reddit" src="https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue"></a>
<br>
<a href="https://bit.ly/yolov5-paperspace-notebook"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"></a>
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
<a href="https://www.kaggle.com/models/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
</div>
<br>
Ultralytics YOLOv3 是由 [Ultralytics](https://www.ultralytics.com/) 开发的高效、强大的[计算机视觉](https://www.ultralytics.com/glossary/computer-vision-cv)模型。该实现基于 [PyTorch](https://pytorch.org/) 框架,构建于原始 YOLOv3 架构之上。与早期版本相比,YOLOv3 在[目标检测](https://www.ultralytics.com/glossary/object-detection)速度与准确性方面表现卓越,融合了前沿研究和最佳实践,成为多种视觉 AI 任务的可靠选择。
欢迎您充分利用本项目资源!请访问 [Ultralytics 文档](https://docs.ultralytics.com/)获取详细指南(注意:YOLOv3 专属文档有限,建议参考通用 YOLO 原则),在 [GitHub Issues](https://github.com/ultralytics/yolov5/issues/new/choose) 提问获取支持,并加入 [Discord 社区](https://discord.com/invite/ultralytics)参与讨论!
如需企业许可证,请填写 [Ultralytics 许可申请](https://www.ultralytics.com/license)。
<div align="center">
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="2%" alt="Ultralytics GitHub"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="2%" alt="Ultralytics LinkedIn"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="2%" alt="Ultralytics Twitter"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="2%" alt="Ultralytics YouTube"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="2%" alt="Ultralytics TikTok"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="2%" alt="Ultralytics BiliBili"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="2%" alt="space">
<a href="https://discord.com/invite/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="2%" alt="Ultralytics Discord"></a>
</div>
</div>
<br>
## 🚀 YOLO11:下一代进化
我们隆重推出 **Ultralytics YOLO11** 🚀,这是我们最新的 SOTA 视觉模型!YOLO11 已在 [Ultralytics YOLO GitHub 仓库](https://github.com/ultralytics/ultralytics)发布,延续了速度、精度与易用性的卓越传统。无论您在进行[目标检测](https://docs.ultralytics.com/tasks/detect/)、[实例分割](https://docs.ultralytics.com/tasks/segment/)、[姿态估计](https://docs.ultralytics.com/tasks/pose/)、[图像分类](https://docs.ultralytics.com/tasks/classify/)还是[旋转目标检测 (OBB)](https://docs.ultralytics.com/tasks/obb/),YOLO11 都能为您的应用带来卓越性能和多功能性。
立即体验,释放 YOLO11 的全部潜能!访问 [Ultralytics 文档](https://docs.ultralytics.com/)获取全面指南和资源:
[](https://badge.fury.io/py/ultralytics) [](https://pepy.tech/projects/ultralytics)
```bash
# 安装 ultralytics 包
pip install ultralytics
```
<div align="center">
<a href="https://www.ultralytics.com/yolo" target="_blank">
<img width="100%" src="https://raw.githubusercontent.com/ultralytics/assets/refs/heads/main/yolo/performance-comparison.png" alt="Ultralytics YOLO Performance Comparison"></a>
</div>
## 📚 文档
请参阅 [Ultralytics YOLOv3 文档](https://docs.ultralytics.com/models/yolov3/),了解如何使用 Ultralytics 框架进行训练、测试和部署。虽然 YOLOv3 专属文档有限,但通用 YOLO 原则同样适用。以下为 YOLOv3 快速入门示例。
<details open>
<summary>安装</summary>
克隆仓库并在 [**Python>=3.8.0**](https://www.python.org/) 环境下,从 [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) 安装依赖。确保已安装 [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/)。建议针对 YOLOv3 进行专门测试以确保兼容性。
```bash
# 克隆 YOLOv3 仓库
git clone https://github.com/ultralytics/yolov3
# 进入目录
cd yolov3
# 安装依赖
pip install -r requirements.txt
```
</details>
<details open>
<summary>使用 PyTorch Hub 进行推理</summary>
通过 [PyTorch Hub](https://docs.ultralytics.com/integrations/jupyterlab/) 可便捷加载 YOLOv3 进行推理。[模型权重](https://github.com/ultralytics/yolov5/tree/master/models)如 `yolov3.pt`、`yolov3-spp.pt`、`yolov3-tiny.pt` 均可直接使用。
```python
import torch
# 加载 YOLOv3 模型(如 yolov3, yolov3-spp)
model = torch.hub.load("ultralytics/yolov3", "yolov3", pretrained=True)
# 输入图像(支持 URL、本地文件、PIL、OpenCV、numpy 数组或列表)
img = "https://ultralytics.com/images/zidane.jpg"
# 推理
results = model(img)
# 结果处理(.print(), .show(), .save(), .crop(), .pandas())
results.print()
results.show()
results.save()
```
</details>
<details>
<summary>使用 detect.py 进行推理</summary>
`detect.py` 脚本支持多种输入源推理。使用 `--weights yolov3.pt` 或其他变体,模型会自动下载,结果保存至 `runs/detect`。
```bash
# 使用 yolov3-tiny 和摄像头推理
python detect.py --weights yolov3-tiny.pt --source 0
# 使用 yolov3 推理本地图像
python detect.py --weights yolov3.pt --source img.jpg
# 使用 yolov3-spp 推理本地视频
python detect.py --weights yolov3-spp.pt --source vid.mp4
# 推理屏幕截图
python detect.py --weights yolov3.pt --source screen
# 推理图像目录
python detect.py --weights yolov3.pt --source path/to/images/
# 推理图像路径列表文件
python detect.py --weights yolov3.pt --source list.txt
# 推理流 URL 列表文件
python detect.py --weights yolov3.pt --source list.streams
# 使用 glob 模式推理
python detect.py --weights yolov3.pt --source 'path/to/*.jpg'
# 推理 YouTube 视频
python detect.py --weights yolov3.pt --source 'https://youtu.be/LNwODJXcvt4'
# 推理 RTSP、RTMP 或 HTTP 流
python detect.py --weights yolov3.pt --source 'rtsp://example.com/media.mp4'
```
</details>
<details>
<summary>训练</summary>
以下命令展示如何在 [COCO 数据集](https://docs.ultralytics.com/datasets/detect/coco/)上训练 YOLOv3。模型和数据集会自动下载。请根据硬件选择合适的 `--batch-size`。
```bash
# 在 COCO 上训练 YOLOv3-tiny 300 轮
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov3-tiny.yaml --batch-size 64
# 在 COCO 上训练 YOLOv3 300 轮
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov3.yaml --batch-size 32
# 在 COCO 上训练 YOLOv3-SPP 300 轮
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov3-spp.yaml --batch-size 16
```
</details>
<details open>
<summary>教程</summary>
注意:这些教程多以 YOLOv5 为例,但原理同样适用于 YOLOv3。
- **[训练自定义数据](https://docs.ultralytics.com/guides/data-collection-and-annotation/)** 🚀 **推荐**:学习如何在自有数据集上训练模型。
- **[最佳训练技巧](https://docs.ultralytics.com/guides/model-training-tips/)** ☘️:提升模型性能的专家建议。
- **[多 GPU 训练](https://docs.ultralytics.com/guides/model-training-tips/)**:加速大规模训练。
- **[PyTorch Hub 集成](https://docs.ultralytics.com/integrations/jupyterlab/)** 🌟 **新增**:一键加载模型。
- **[模型导出 (TFLite, ONNX, CoreML, TensorRT)](https://docs.ultralytics.com/modes/export/)** 🚀:多格式部署支持。
- **[NVIDIA Jetson 部署](https://docs.ultralytics.com/guides/nvidia-jetson/)** 🌟 **新增**:边缘设备推理。
- **[测试时增强 (TTA)](https://docs.ultralytics.com/guides/model-evaluation-insights/)**:提升预测准确率。
- **[模型集成](https://docs.ultralytics.com/guides/model-deployment-options/)**:多模型融合提升表现。
- **[模型剪枝/稀疏化](https://docs.ultralytics.com/guides/model-deployment-practices/)**:优化模型体积与速度。
- **[超参数进化](https://docs.ultralytics.com/guides/hyperparameter-tuning/)**:自动优化训练参数。
- **[迁移学习与冻结层](https://docs.ultralytics.com/guides/model-training-tips/)**:高效迁移预训练模型。
- **[架构总结](https://docs.ultralytics.com/models/yolov3/)** 🌟 **新增**:理解 YOLOv3 设计原理。
- **[Ultralytics Platform 训练](https://platform.ultralytics.com)** 🚀 **推荐**:无代码训练与部署。
- **[ClearML 日志集成](https://docs.ultralytics.com/integrations/clearml/)**:实验可追溯。
- **[Neural Magic DeepSparse 集成](https://docs.ultralytics.com/integrations/neural-magic/)**:极致推理加速。
- **[Comet 日志集成](https://docs.ultralytics.com/integrations/comet/)** 🌟 **新增**:实验可视化与管理。
</details>
## 🧩 集成
Ultralytics 与领先 AI 平台深度集成,扩展了数据集标注、训练、可视化和模型管理等能力。了解如何通过 [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases/)、[Comet ML](https://docs.ultralytics.com/integrations/comet/)、[Roboflow](https://docs.ultralytics.com/integrations/roboflow/) 和 [Intel OpenVINO](https://docs.ultralytics.com/integrations/openvino/) 等合作伙伴优化您的 AI 工作流。探索 [Ultralytics 集成](https://docs.ultralytics.com/integrations/) 了解更多。
<a href="https://docs.ultralytics.com/integrations/" target="_blank">
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics active learning integrations">
</a>
<br>
<br>
<div align="center">
<a href="https://platform.ultralytics.com">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-ultralytics-hub.png" width="10%" alt="Ultralytics Platform logo"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="space">
<a href="https://docs.ultralytics.com/integrations/weights-biases/">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-wb.png" width="10%" alt="Weights & Biases logo"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="space">
<a href="https://docs.ultralytics.com/integrations/comet/">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-comet.png" width="10%" alt="Comet ML logo"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="15%" height="0" alt="space">
<a href="https://docs.ultralytics.com/integrations/neural-magic/">
<img src="https://github.com/ultralytics/assets/raw/main/partners/logo-neuralmagic.png" width="10%" alt="Neural Magic logo"></a>
</div>
| Ultralytics Platform 🌟 | Weights & Biases | Comet | Neural Magic |
| :--------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------: |
| 简化 YOLO 工作流:使用 [Ultralytics Platform](https://platform.ultralytics.com) 轻松标注、训练和部署。立即体验! | 使用 [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases/) 跟踪实验与超参数。 | [Comet ML](https://docs.ultralytics.com/integrations/comet/) 永久免费,支持模型保存、训练恢复与预测可视化。 | [Neural Magic DeepSparse](https://docs.ultralytics.com/integrations/neural-magic/) 可将 YOLO 推理速度提升至 6 倍。 |
## ⭐ Ultralytics Platform
通过 [Ultralytics Platform](https://platform.ultralytics.com) ⭐ 体验无缝 AI 开发,轻松构建、训练和部署计算机视觉模型。无需代码,即可可视化数据集、训练 YOLOv3、YOLOv5 和 YOLOv8 🚀,并将模型部署到实际场景。借助 [Ultralytics App](https://www.ultralytics.com/app-install) 和创新工具,将图像转化为可操作见解。立即开启您的**免费** AI 之旅!
<a align="center" href="https://platform.ultralytics.com" target="_blank">
<img width="100%" src="https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png" alt="Ultralytics Platform Platform Screenshot"></a>
## 🤔 为何选择 YOLOv3?
YOLOv3 发布时推动了实时目标检测的进步。其核心优势包括:
- **更高准确率:** 对小目标检测表现优异。
- **多尺度预测:** 支持三种不同尺度,提升多尺寸目标检测能力。
- **多标签分类:** 采用逻辑分类器而非 softmax,支持多标签输出。
- **强大特征提取器:** 使用更深的 Darknet-53 网络替代 YOLOv2 的 Darknet-19。
尽管后续如 YOLOv5 和 YOLO11 等模型带来更多创新,YOLOv3 依然是坚实且广泛理解的基准,Ultralytics 在 PyTorch 中实现高效。
## ☁️ 环境
使用预配置环境快速上手。点击下方图标了解各平台设置详情。
<div align="center">
<a href="https://docs.ultralytics.com/integrations/paperspace/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gradient.png" width="10%" alt="Run on Gradient"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/google-colab/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-colab-small.png" width="10%" alt="Open In Colab"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/kaggle/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-kaggle-small.png" width="10%" alt="Open In Kaggle"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/guides/docker-quickstart/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-docker-small.png" width="10%" alt="Docker Image"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/amazon-sagemaker/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-aws-small.png" width="10%" alt="AWS Marketplace"/></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="5%" alt="" />
<a href="https://docs.ultralytics.com/integrations/google-colab/">
<img src="https://github.com/ultralytics/assets/releases/download/v0.0.0/logo-gcp-small.png" width="10%" alt="GCP Quickstart"/></a>
</div>
## 🤝 贡献
欢迎您的贡献!Ultralytics 致力于让 YOLO 模型更易用、更高效。请参阅[贡献指南](https://docs.ultralytics.com/help/contributing/)开始参与。通过 [Ultralytics 调查](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) 分享您的反馈。感谢所有为 Ultralytics YOLO 发展做出贡献的朋友!
[](https://github.com/ultralytics/yolov5/graphs/contributors)
## 📜 许可证
Ultralytics 提供两种许可选项以满足不同需求:
- **AGPL-3.0 许可证**:经 [OSI 批准](https://opensource.org/license/agpl-v3)的开源协议,适合学术、个人项目和测试,促进开放合作。详情见 [LICENSE](https://github.com/ultralytics/yolov5/blob/master/LICENSE)。
- **企业许可证**:专为商业应用设计,允许将 Ultralytics 软件和模型集成到商业产品和服务,无需遵守 AGPL-3.0 的开源要求。请通过 [Ultralytics 许可](https://www.ultralytics.com/license) 联系我们。
## 📧 联系
如需报告 Ultralytics YOLO 实现的 bug 或功能请求,请访问 [GitHub Issues](https://github.com/ultralytics/yolov5/issues)。如有一般问题、讨论或社区支持,欢迎加入 [Discord 服务器](https://discord.com/invite/ultralytics)!
<br>
<div align="center">
<a href="https://github.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png" width="3%" alt="Ultralytics GitHub"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://www.linkedin.com/company/ultralytics/"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png" width="3%" alt="Ultralytics LinkedIn"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://twitter.com/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png" width="3%" alt="Ultralytics Twitter"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://youtube.com/ultralytics?sub_confirmation=1"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png" width="3%" alt="Ultralytics YouTube"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://www.tiktok.com/@ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png" width="3%" alt="Ultralytics TikTok"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://ultralytics.com/bilibili"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-bilibili.png" width="3%" alt="Ultralytics BiliBili"></a>
<img src="https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png" width="3%" alt="space">
<a href="https://discord.com/invite/ultralytics"><img src="https://github.com/ultralytics/assets/raw/main/social/logo-social-discord.png" width="3%" alt="Ultralytics Discord"></a>
</div>
================================================
FILE: benchmarks.py
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""
Run YOLOv3 benchmarks on all supported export formats.
Format | `export.py --include` | Model
--- | --- | ---
PyTorch | - | yolov5s.pt
TorchScript | `torchscript` | yolov5s.torchscript
ONNX | `onnx` | yolov5s.onnx
OpenVINO | `openvino` | yolov5s_openvino_model/
TensorRT | `engine` | yolov5s.engine
CoreML | `coreml` | yolov5s.mlmodel
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
TensorFlow GraphDef | `pb` | yolov5s.pb
TensorFlow Lite | `tflite` | yolov5s.tflite
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
TensorFlow.js | `tfjs` | yolov5s_web_model/
Requirements:
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
Usage:
$ python benchmarks.py --weights yolov5s.pt --img 640
"""
import argparse
import platform
import sys
import time
from pathlib import Path
import pandas as pd
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv3 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
# ROOT = ROOT.relative_to(Path.cwd()) # relative
import export
from models.experimental import attempt_load
from models.yolo import SegmentationModel
from segment.val import run as val_seg
from utils import notebook_init
from utils.general import LOGGER, check_yaml, file_size, print_args
from utils.torch_utils import select_device
from val import run as val_det
def run(
weights=ROOT / "yolov5s.pt", # weights path
imgsz=640, # inference size (pixels)
batch_size=1, # batch size
data=ROOT / "data/coco128.yaml", # dataset.yaml path
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
half=False, # use FP16 half-precision inference
test=False, # test exports only
pt_only=False, # test PyTorch only
hard_fail=False, # throw error on benchmark failure
):
"""Run YOLOv3 benchmarks on multiple export formats and validate performance metrics.
Args:
weights (str | Path): Path to the weights file. Defaults to 'yolov5s.pt'.
imgsz (int): Inference image size in pixels. Defaults to 640.
batch_size (int): Batch size for inference. Defaults to 1.
data (str | Path): Path to the dataset configuration file (dataset.yaml). Defaults to 'data/coco128.yaml'.
device (str): Device to be used for inference, e.g., '0' or '0,1,2,3' for GPU or 'cpu' for CPU. Defaults to ''.
half (bool): Use FP16 half-precision for inference. Defaults to False.
test (bool): Test exports only without running benchmarks. Defaults to False.
pt_only (bool): Run benchmarks only for PyTorch format. Defaults to False.
hard_fail (bool): Raise an error if any benchmark test fails. Defaults to False.
Returns:
None
Examples:
```python
# Run benchmarks on the default 'yolov5s.pt' model with an image size of 640 pixels
run()
# Run benchmarks on a specific model with GPU and half-precision enabled
run(weights='custom_model.pt', device='0', half=True)
# Test only PyTorch export
run(pt_only=True)
```
Notes:
This function iterates over multiple export formats, performs the export, and then validates the model's performance
using appropriate validation functions for detection and segmentation models. The results are logged, and optionally,
benchmarks can be configured to raise errors on failures using the `hard_fail` argument.
"""
y, t = [], time.time()
device = select_device(device)
model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
try:
assert i not in (9, 10), "inference not supported" # Edge TPU and TF.js are unsupported
assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
if "cpu" in device.type:
assert cpu, "inference not supported on CPU"
if "cuda" in device.type:
assert gpu, "inference not supported on GPU"
# Export
if f == "-":
w = weights # PyTorch format
else:
w = export.run(
weights=weights, imgsz=[imgsz], include=[f], batch_size=batch_size, device=device, half=half
)[-1] # all others
assert suffix in str(w), "export failed"
# Validate
if model_type == SegmentationModel:
result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
else: # DetectionModel:
result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
speed = result[2][1] # times (preprocess, inference, postprocess)
y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
except Exception as e:
if hard_fail:
assert type(e) is AssertionError, f"Benchmark --hard-fail for {name}: {e}"
LOGGER.warning(f"WARNING ⚠️ Benchmark failure for {name}: {e}")
y.append([name, None, None, None]) # mAP, t_inference
if pt_only and i == 0:
break # break after PyTorch
# Print results
LOGGER.info("\n")
parse_opt()
notebook_init() # print system info
c = ["Format", "Size (MB)", "mAP50-95", "Inference time (ms)"] if map else ["Format", "Export", "", ""]
py = pd.DataFrame(y, columns=c)
LOGGER.info(f"\nBenchmarks complete ({time.time() - t:.2f}s)")
LOGGER.info(str(py if map else py.iloc[:, :2]))
if hard_fail and isinstance(hard_fail, str):
metrics = py["mAP50-95"].array # values to compare to floor
floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
assert all(x > floor for x in metrics if pd.notna(x)), f"HARD FAIL: mAP50-95 < floor {floor}"
return py
def test(
weights=ROOT / "yolov5s.pt", # weights path
imgsz=640, # inference size (pixels)
batch_size=1, # batch size
data=ROOT / "data/coco128.yaml", # dataset.yaml path
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
half=False, # use FP16 half-precision inference
test=False, # test exports only
pt_only=False, # test PyTorch only
hard_fail=False, # throw error on benchmark failure
):
"""Run YOLOv3 export tests for various formats and log the results, including export success status.
Args:
weights (str | Path): Path to the weights file. Defaults to ROOT / "yolov5s.pt".
imgsz (int): Inference size in pixels. Defaults to 640.
batch_size (int): Number of images per batch. Defaults to 1.
data (str | Path): Path to the dataset yaml file. Defaults to ROOT / "data/coco128.yaml".
device (str): Device for inference. Accepts cuda device (e.g., "0" or "0,1,2,3") or "cpu". Defaults to "".
half (bool): Use FP16 half-precision inference. Defaults to False.
test (bool): Run export tests only, no inference. Defaults to False.
pt_only (bool): Run tests on PyTorch format only. Defaults to False.
hard_fail (bool): Raise an error on benchmark failure. Defaults to False.
Returns:
pd.DataFrame: A DataFrame containing the export formats and their success status.
Examples:
```python
from ultralytics import test
results = test(
weights="path/to/yolov5s.pt",
imgsz=640,
batch_size=1,
data="path/to/coco128.yaml",
device="0",
half=False,
test=True,
pt_only=False,
hard_fail=True,
)
print(results)
```
Notes:
Ensure all required packages are installed as specified in the Ultralytics YOLOv3 documentation:
https://github.com/ultralytics/ultralytics
"""
y, t = [], time.time()
device = select_device(device)
for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
try:
w = (
weights
if f == "-"
else export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]
) # weights
assert suffix in str(w), "export failed"
y.append([name, True])
except Exception:
y.append([name, False]) # mAP, t_inference
# Print results
LOGGER.info("\n")
parse_opt()
notebook_init() # print system info
py = pd.DataFrame(y, columns=["Format", "Export"])
LOGGER.info(f"\nExports complete ({time.time() - t:.2f}s)")
LOGGER.info(str(py))
return py
def parse_opt():
"""Parses command line arguments for YOLOv3 inference and export configurations.
Args:
--weights (str): Path to the weights file. Default is 'ROOT / "yolov3-tiny.pt"'.
--imgsz | --img | --img-size (int): Inference image size in pixels. Default is 640.
--batch-size (int): Batch size for inference. Default is 1.
--data (str): Path to the dataset configuration file (dataset.yaml). Default is 'ROOT / "data/coco128.yaml"'.
--device (str): CUDA device identifier, e.g., '0' for single GPU, '0,1,2,3' for multiple GPUs, or 'cpu' for CPU
inference. Default is "".
--half (bool): If set, use FP16 half-precision inference. Default is False.
--test (bool): If set, test only exports without running inference. Default is False.
--pt-only (bool): If set, test only the PyTorch model without exporting to other formats. Default is False.
--hard-fail (str | bool): If set, raise an exception on benchmark failure. Can also be a string representing the
minimum metric floor for success. Default is False.
Returns:
argparse.Namespace: The parsed arguments as a namespace object.
Examples:
To run inference on the YOLOv3-tiny model with a different image size:
```python
$ python benchmarks.py --weights yolov3-tiny.pt --imgsz 512 --device 0
```
Notes:
The `--hard-fail` argument can be a boolean or a string. If a string is provided, it should be an expression that
represents the minimum acceptable metric value, such as '0.29' for mAP (mean Average Precision).
Links:
https://github.com/ultralytics/ultralytics
"""
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov3-tiny.pt", help="weights path")
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="inference size (pixels)")
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
parser.add_argument("--test", action="store_true", help="test exports only")
parser.add_argument("--pt-only", action="store_true", help="test PyTorch only")
parser.add_argument("--hard-fail", nargs="?", const=True, default=False, help="Exception on error or < min metric")
opt = parser.parse_args()
opt.data = check_yaml(opt.data) # check YAML
print_args(vars(opt))
return opt
def main(opt):
"""Executes the export and benchmarking pipeline for YOLOv3 models, testing multiple export formats and validating
performance metrics.
Args:
opt (argparse.Namespace): Parsed command line arguments, including options for weights, image size, batch size,
dataset path, device, half-precision inference, test mode, PyTorch-only testing, and hard fail conditions.
Returns:
pd.DataFrame: A DataFrame containing benchmarking results with columns:
- Format: Name of the export format
- Size (MB): File size of the exported model
- mAP50-95: Mean Average Precision for the model
- Inference time (ms): Time taken for inference
Examples:
Running the function from command line with required arguments:
```python
$ python benchmarks.py --weights yolov5s.pt --img 640
```
For more details, visit the Ultralytics YOLOv3 repository on [GitHub](https://github.com/ultralytics/ultralytics).
Notes:
The function runs the main pipeline by exporting the YOLOv3 model to various formats and running benchmarks to
evaluate performance. If `opt.test` is set to True, it only tests the export process and logs the results.
"""
test(**vars(opt)) if opt.test else run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
================================================
FILE: classify/predict.py
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""
Run YOLOv3 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
Usage - sources:
$ python classify/predict.py --weights yolov5s-cls.pt --source 0 # webcam
img.jpg # image
vid.mp4 # video
screen # screenshot
path/ # directory
list.txt # list of images
list.streams # list of streams
'path/*.jpg' # glob
'https://youtu.be/LNwODJXcvt4' # YouTube
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
Usage - formats:
$ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
yolov5s-cls.torchscript # TorchScript
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
yolov5s-cls_openvino_model # OpenVINO
yolov5s-cls.engine # TensorRT
yolov5s-cls.mlmodel # CoreML (macOS-only)
yolov5s-cls_saved_model # TensorFlow SavedModel
yolov5s-cls.pb # TensorFlow GraphDef
yolov5s-cls.tflite # TensorFlow Lite
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
yolov5s-cls_paddle_model # PaddlePaddle
"""
import argparse
import os
import platform
import sys
from pathlib import Path
import torch
import torch.nn.functional as F
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv3 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from ultralytics.utils.plotting import Annotator
from models.common import DetectMultiBackend
from utils.augmentations import classify_transforms
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (
LOGGER,
Profile,
check_file,
check_img_size,
check_imshow,
check_requirements,
colorstr,
cv2,
increment_path,
print_args,
strip_optimizer,
)
from utils.torch_utils import select_device, smart_inference_mode
@smart_inference_mode()
def run(
weights=ROOT / "yolov5s-cls.pt", # model.pt path(s)
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
data=ROOT / "data/coco128.yaml", # dataset.yaml path
imgsz=(224, 224), # inference size (height, width)
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
view_img=False, # show results
save_txt=False, # save results to *.txt
nosave=False, # do not save images/videos
augment=False, # augmented inference
visualize=False, # visualize features
update=False, # update all models
project=ROOT / "runs/predict-cls", # save results to project/name
name="exp", # save results to project/name
exist_ok=False, # existing project/name ok, do not increment
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
vid_stride=1, # video frame-rate stride
):
"""Performs YOLOv3 classification inference on various input sources and saves or displays results."""
source = str(source)
save_img = not nosave and not source.endswith(".txt") # save inference images
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
screenshot = source.lower().startswith("screen")
if is_url and is_file:
source = check_file(source) # download
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
stride, names, pt = model.stride, model.names, model.pt
imgsz = check_img_size(imgsz, s=stride) # check image size
# Dataloader
bs = 1 # batch_size
if webcam:
view_img = check_imshow(warn=True)
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
bs = len(dataset)
elif screenshot:
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
else:
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
vid_path, vid_writer = [None] * bs, [None] * bs
# Run inference
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
for path, im, im0s, vid_cap, s in dataset:
with dt[0]:
im = torch.Tensor(im).to(model.device)
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
if len(im.shape) == 3:
im = im[None] # expand for batch dim
# Inference
with dt[1]:
results = model(im)
# Post-process
with dt[2]:
pred = F.softmax(results, dim=1) # probabilities
# Process predictions
for i, prob in enumerate(pred): # per image
seen += 1
if webcam: # batch_size >= 1
p, im0, frame = path[i], im0s[i].copy(), dataset.count
s += f"{i}: "
else:
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # im.jpg
txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
s += "{:g}x{:g} ".format(*im.shape[2:]) # print string
annotator = Annotator(im0, example=str(names), pil=True)
# Print results
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
# Write results
text = "\n".join(f"{prob[j]:.2f} {names[j]}" for j in top5i)
if save_img or view_img: # Add bbox to image
annotator.text([32, 32], text, txt_color=(255, 255, 255))
if save_txt: # Write to file
with open(f"{txt_path}.txt", "a") as f:
f.write(text + "\n")
# Stream results
im0 = annotator.result()
if view_img:
if platform.system() == "Linux" and p not in windows:
windows.append(p)
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
if dataset.mode == "image":
cv2.imwrite(save_path, im0)
else: # 'video' or 'stream'
if vid_path[i] != save_path: # new video
vid_path[i] = save_path
if isinstance(vid_writer[i], cv2.VideoWriter):
vid_writer[i].release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
vid_writer[i].write(im0)
# Print time (inference-only)
LOGGER.info(f"{s}{dt[1].dt * 1e3:.1f}ms")
# Print results
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
if update:
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
def parse_opt():
"""Parses command line arguments for model inference settings, returns a Namespace of options."""
parser = argparse.ArgumentParser()
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model path(s)")
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[224], help="inference size h,w")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--view-img", action="store_true", help="show results")
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
parser.add_argument("--augment", action="store_true", help="augmented inference")
parser.add_argument("--visualize", action="store_true", help="visualize features")
parser.add_argument("--update", action="store_true", help="update all models")
parser.add_argument("--project", default=ROOT / "runs/predict-cls", help="save results to project/name")
parser.add_argument("--name", default="exp", help="save results to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(vars(opt))
return opt
def main(opt):
"""Entry point for running the model; checks requirements and calls `run` with options parsed from CLI."""
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
================================================
FILE: classify/train.py
================================================
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""
Train a YOLOv3 classifier model on a classification dataset.
Usage - Single-GPU training:
$ python classify/train.py --model yolov5s-cls.pt --data imagenette160 --epochs 5 --img 224
Usage - Multi-GPU DDP training:
$ python -m torch.distributed.run --nproc_per_node 4 --master_port 2022 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
Datasets: --data mnist, fashion-mnist, cifar10, cifar100, imagenette, imagewoof, imagenet, or 'path/to/data'
YOLOv3-cls models: --model yolov5n-cls.pt, yolov5s-cls.pt, yolov5m-cls.pt, yolov5l-cls.pt, yolov5x-cls.pt
Torchvision models: --model resnet50, efficientnet_b0, etc. See https://pytorch.org/vision/stable/models.html
"""
import argparse
import os
import subprocess
import sys
import time
from copy import deepcopy
from datetime import datetime
from pathlib import Path
import torch
import torch.distributed as dist
import torch.hub as hub
import torch.optim.lr_scheduler as lr_scheduler
import torchvision
from torch.cuda import amp
from tqdm import tqdm
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv3 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from classify import val as validate
from models.experimental import attempt_load
from models.yolo import ClassificationModel, DetectionModel
from utils.dataloaders import create_classification_dataloader
from utils.general import (
DATASETS_DIR,
LOGGER,
TQDM_BAR_FORMAT,
WorkingDirectory,
check_git_info,
check_git_status,
check_requirements,
colorstr,
download,
increment_path,
init_seeds,
print_args,
yaml_save,
)
from utils.loggers import GenericLogger
from utils.plots import imshow_cls
from utils.torch_utils import (
ModelEMA,
de_parallel,
model_info,
reshape_classifier_output,
select_device,
smart_DDP,
smart_optimizer,
smartCrossEntropyLoss,
torch_distributed_zero_first,
)
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv("RANK", -1))
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
GIT_INFO = check_git_info()
def train(opt, device):
"""Trains a model on a given dataset using specified options and device, handling data loading, model optimization,
and logging.
"""
init_seeds(opt.seed + 1 + RANK, deterministic=True)
save_dir, data, bs, epochs, nw, imgsz, pretrained = (
opt.save_dir,
Path(opt.data),
opt.batch_size,
opt.epochs,
min(os.cpu_count() - 1, opt.workers),
opt.imgsz,
str(opt.pretrained).lower() == "true",
)
cuda = device.type != "cpu"
# Directories
wdir = save_dir / "weights"
wdir.mkdir(parents=True, exist_ok=True) # make dir
last, best = wdir / "last.pt", wdir / "best.pt"
# Save run settings
yaml_save(save_dir / "opt.yaml", vars(opt))
# Logger
logger = GenericLogger(opt=opt, console_logger=LOGGER) if RANK in {-1, 0} else None
# Download Dataset
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
data_dir = data if data.is_dir() else (DATASETS_DIR / data)
if not data_dir.is_dir():
LOGGER.info(f"\nDataset not found ⚠️, missing path {data_dir}, attempting download...")
t = time.time()
if str(data) == "imagenet":
subprocess.run(["bash", str(ROOT / "data/scripts/get_imagenet.sh")], shell=True, check=True)
else:
url = f"https://github.com/ultralytics/assets/releases/download/v0.0.0/{data}.zip"
download(url, dir=data_dir.parent)
s = f"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\n"
LOGGER.info(s)
# Dataloaders
nc = len([x for x in (data_dir / "train").glob("*") if x.is_dir()]) # number of classes
trainloader = create_classification_dataloader(
path=data_dir / "train",
imgsz=imgsz,
batch_size=bs // WORLD_SIZE,
augment=True,
cache=opt.cache,
rank=LOCAL_RANK,
workers=nw,
)
test_dir = data_dir / "test" if (data_dir / "test").exists() else data_dir / "val" # data/test or data/val
if RANK in {-1, 0}:
testloader = create_classification_dataloader(
path=test_dir,
imgsz=imgsz,
batch_size=bs // WORLD_SIZE * 2,
augment=False,
cache=opt.cache,
rank=-1,
workers=nw,
)
# Model
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
if Path(opt.model).is_file() or opt.model.endswith(".pt"):
model = attempt_load(opt.model, device="cpu", fuse=False)
elif opt.model in torchvision.models.__dict__: # TorchVision models i.e. resnet50, efficientnet_b0
model = torchvision.models.__dict__[opt.model](weights="IMAGENET1K_V1" if pretrained else None)
else:
m = hub.list("ultralytics/yolov5") # + hub.list('pytorch/vision') # models
raise ModuleNotFoundError(f"--model {opt.model} not found. Available models are: \n" + "\n".join(m))
if isinstance(model, DetectionModel):
LOGGER.warning("WARNING ⚠️ pass YOLOv3 classifier model with '-cls' suffix, i.e. '--model yolov5s-cls.pt'")
model = ClassificationModel(model=model, nc=nc, cutoff=opt.cutoff or 10) # convert to classification model
reshape_classifier_output(model, nc) # update class count
for m in model.modules():
if not pretrained and hasattr(m, "reset_parameters"):
m.reset_parameters()
if isinstance(m, torch.nn.Dropout) and opt.dropout is not None:
m.p = opt.dropout # set dropout
for p in model.parameters():
p.requires_grad = True # for training
model = model.to(device)
# Info
if RANK in {-1, 0}:
model.names = trainloader.dataset.classes # attach class names
model.transforms = testloader.dataset.torch_transforms # attach inference transforms
model_info(model)
if opt.verbose:
LOGGER.info(model)
images, labels = next(iter(trainloader))
file = imshow_cls(images[:25], labels[:25], names=model.names, f=save_dir / "train_images.jpg")
logger.log_images(file, name="Train Examples")
logger.log_graph(model, imgsz) # log model
# Optimizer
optimizer = smart_optimizer(model, opt.optimizer, opt.lr0, momentum=0.9, decay=opt.decay)
# Scheduler
lrf = 0.01 # final lr (fraction of lr0)
# lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - lrf) + lrf # cosine
def lf(x):
"""Linear learning rate scheduler function, scaling learning rate from initial value to `lrf` over `epochs`."""
return (1 - x / epochs) * (1 - lrf) + lrf # linear
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
# scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=lr0, total_steps=epochs, pct_start=0.1,
# final_div_factor=1 / 25 / lrf)
# EMA
ema = ModelEMA(model) if RANK in {-1, 0} else None
# DDP mode
if cuda and RANK != -1:
model = smart_DDP(model)
# Train
t0 = time.time()
criterion = smartCrossEntropyLoss(label_smoothing=opt.label_smoothing) # loss function
best_fitness = 0.0
scaler = amp.GradScaler(enabled=cuda)
val = test_dir.stem # 'val' or 'test'
LOGGER.info(
f"Image sizes {imgsz} train, {imgsz} test\n"
f"Using {nw * WORLD_SIZE} dataloader workers\n"
f"Logging results to {colorstr('bold', save_dir)}\n"
f"Starting {opt.model} training on {data} dataset with {nc} classes for {epochs} epochs...\n\n"
f"{'Epoch':>10}{'GPU_mem':>10}{'train_loss':>12}{f'{val}_loss':>12}{'top1_acc':>12}{'top5_acc':>12}"
)
for epoch in range(epochs): # loop over the dataset multiple times
tloss, vloss, fitness = 0.0, 0.0, 0.0 # train loss, val loss, fitness
model.train()
if RANK != -1:
trainloader.sampler.set_epoch(epoch)
pbar = enumerate(trainloader)
if RANK in {-1, 0}:
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format=TQDM_BAR_FORMAT)
for i, (images, labels) in pbar: # progress bar
images, labels = images.to(device, non_blocking=True), labels.to(device)
# Forward
with amp.autocast(enabled=cuda): # stability issues when enabled
loss = criterion(model(images), labels)
# Backward
scaler.scale(loss).backward()
# Optimize
scaler.unscale_(optimizer) # unscale gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()
if ema:
ema.update(model)
if RANK in {-1, 0}:
# Print
tloss = (tloss * i + loss.item()) / (i + 1) # update mean losses
mem = "%.3gG" % (torch.cuda.memory_reserved() / 1e9 if torch.cuda.is_available() else 0) # (GB)
pbar.desc = f"{f'{epoch + 1}/{epochs}':>10}{mem:>10}{tloss:>12.3g}" + " " * 36
# Test
if i == len(pbar) - 1: # last batch
top1, top5, vloss = validate.run(
model=ema.ema, dataloader=testloader, criterion=criterion, pbar=pbar
) # test accuracy, loss
fitness = top1 # define fitness as top1 accuracy
# Scheduler
scheduler.step()
# Log metrics
if RANK in {-1, 0}:
# Best fitness
if fitness > best_fitness:
best_fitness = fitness
# Log
metrics = {
"train/loss": tloss,
f"{val}/loss": vloss,
"metrics/accuracy_top1": top1,
"metrics/accuracy_top5": top5,
"lr/0": optimizer.param_groups[0]["lr"],
} # learning rate
logger.log_metrics(metrics, epoch)
# Save model
final_epoch = epoch + 1 == epochs
if (not opt.nosave) or final_epoch:
ckpt = {
"epoch": epoch,
"best_fitness": best_fitness,
"model": deepcopy(ema.ema).half(), # deepcopy(de_parallel(model)).half(),
"ema": None, # deepcopy(ema.ema).half(),
"updates": ema.updates,
"optimizer": None, # optimizer.state_dict(),
"opt": vars(opt),
"git": GIT_INFO, # {remote, branch, commit} if a git repo
"date": datetime.now().isoformat(),
}
# Save last, best and delete
torch.save(ckpt, last)
if best_fitness == fitness:
torch.save(ckpt, best)
del ckpt
# Train complete
if RANK in {-1, 0} and final_epoch:
LOGGER.info(
f"\nTraining complete ({(time.time() - t0) / 3600:.3f} hours)"
f"\nResults saved to {colorstr('bold', save_dir)}"
f"\nPredict: python classify/predict.py --weights {best} --source im.jpg"
f"\nValidate: python classify/val.py --weights {best} --data {data_dir}"
f"\nExport: python export.py --weights {best} --include onnx"
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{best}')"
f"\nVisualize: https://netron.app\n"
)
# Plot examples
images, labels = (x[:25] for x in next(iter(testloader))) # first 25 images and labels
pred = torch.max(ema.ema(images.to(device)), 1)[1]
file = imshow_cls(images, labels, pred, de_parallel(model).names, verbose=False, f=save_dir / "test_images.jpg")
# Log results
meta = {"epochs": epochs, "top1_acc": best_fitness, "date": datetime.now().isoformat()}
logger.log_images(file, name="Test Examples (true-predicted)", epoch=epoch)
logger.log_model(best, epochs, metadata=meta)
def parse_opt(known=False):
"""Parses command line arguments for model configuration and training options."""
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, default="yolov5s-cls.pt", help="initial weights path")
parser.add_argument("--data", type=str, default="imagenette160", help="cifar10, cifar100, mnist, imagenet, ...")
parser.add_argument("--epochs", type=int, default=10, help="total training epochs")
parser.add_argument("--batch-size", type=int, default=64, help="total batch size for all GPUs")
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=224, help="train, val image size (pixels)")
parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
parser.add_argument("--cache", type=str, nargs="?", const="ram", help='--cache images in "ram" (default) or "disk"')
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
parser.add_argument("--project", default=ROOT / "runs/train-cls", help="save to project/name")
parser.add_argument("--name", default="exp", help="save to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--pretrained", nargs="?", const=True, default=True, help="start from i.e. --pretrained False")
parser.add_argument("--optimizer", choices=["SGD", "Adam", "AdamW", "RMSProp"], default="Adam", help="optimizer")
parser.add_argument("--lr0", type=float, default=0.001, help="initial learning rate")
parser.add_argument("--decay", type=float, default=5e-5, help="weight decay")
parser.add_argument("--label-smoothing", type=float, default=0.1, help="Label smoothing epsilon")
parser.add_argument("--cutoff", type=int, default=None, help="Model layer cutoff index for Classify() head")
parser.add_argument("--dropout", type=float, default=None, help="Dropout (fraction)")
parser.add_argument("--verbose", action="store_true", help="Verbose mode")
parser.add_argument("--seed", type=int, default=0, help="Global training seed")
parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")
return parser.parse_known_args()[0] if known else parser.parse_args()
def main(opt):
"""Initializes training environment, checks, DDP mode setup, and starts training with given options."""
if RANK in {-1, 0}:
print_args(vars(opt))
check_git_status()
check_requirements(ROOT / "requirements.txt")
# DDP mode
device = select_device(opt.device, batch_size=opt.batch_size)
if LOCAL_RANK != -1:
assert opt.batch_size != -1, "AutoBatch is coming soon for classification, please pass a valid --batch-size"
assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE"
assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command"
torch.cuda.set_device(LOCAL_RANK)
device = torch.device("cuda", LOCAL_RANK)
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
# Parameters
opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
# Train
train(opt, device)
def run(**kwargs):
"""Executes YOLOv5 model training with dynamic options, e.g., `run(data='mnist', imgsz=320, model='yolov5m')`."""
opt = parse_opt(True)
for k, v in kwargs.items():
setattr(opt, k, v)
main(opt)
return opt
if __name__ == "__main__":
opt = parse_opt()
main(opt)
================================================
FILE: classify/tutorial.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "t6MPjfT5NrKQ"
},
"source": [
"<div align=\"center\">\n",
" <a href=\"https://ultralytics.com/yolo\" target=\"_blank\">\n",
" <img width=\"1024\" src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov5/v70/splash.png\">\n",
" </a>\n",
"\n",
" [中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [Türkçe](https://docs.ultralytics.com/tr/) | [Tiếng Việt](https://docs.ultralytics.com/vi/) | [العربية](https://docs.ultralytics.com/ar/)\n",
"\n",
" <a href=\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yml\"><img src=\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yml/badge.svg\" alt=\"Ultralytics CI\"></a>\n",
" <a href=\"https://console.paperspace.com/github/ultralytics/ultralytics\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"/></a>\n",
" <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
" <a href=\"https://www.kaggle.com/models/ultralytics/yolo11\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n",
"\n",
" <a href=\"https://ultralytics.com/discord\"><img alt=\"Discord\" src=\"https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue\"></a>\n",
" <a href=\"https://community.ultralytics.com\"><img alt=\"Ultralytics Forums\" src=\"https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue\"></a>\n",
" <a href=\"https://reddit.com/r/ultralytics\"><img alt=\"Ultralytics Reddit\" src=\"https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue\"></a>\n",
"</div>\n",
"\n",
"This **Ultralytics YOLOv5 Classification Notebook** is the easiest way to get started with [YOLO models](https://www.ultralytics.com/yolo)—no installation needed. Built by [Ultralytics](https://www.ultralytics.com/), the creators of YOLO, this notebook walks you through running **state-of-the-art** models directly in your browser.\n",
"\n",
"Ultralytics models are constantly updated for performance and flexibility. They're **fast**, **accurate**, and **easy to use**, and they excel at [object detection](https://docs.ultralytics.com/tasks/detect/), [tracking](https://docs.ultralytics.com/modes/track/), [instance segmentation](https://docs.ultralytics.com/tasks/segment/), [image classification](https://docs.ultralytics.com/tasks/classify/), and [pose estimation](https://docs.ultralytics.com/tasks/pose/).\n",
"\n",
"Find detailed documentation in the [Ultralytics Docs](https://docs.ultralytics.com/). Get support via [GitHub Issues](https://github.com/ultralytics/ultralytics/issues/new/choose). Join discussions on [Discord](https://discord.com/invite/ultralytics), [Reddit](https://www.reddit.com/r/ultralytics/), and the [Ultralytics Community Forums](https://community.ultralytics.com/)!\n",
"\n",
"Request an Enterprise License for commercial use at [Ultralytics Licensing](https://www.ultralytics.com/license).\n",
"\n",
"<br>\n",
"<div>\n",
" <a href=\"https://www.youtube.com/watch?v=ZN3nRZT7b24\" target=\"_blank\">\n",
" <img src=\"https://img.youtube.com/vi/ZN3nRZT7b24/maxresdefault.jpg\" alt=\"Ultralytics Video\" width=\"640\" style=\"border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);\">\n",
" </a>\n",
"\n",
" <p style=\"font-size: 16px; font-family: Arial, sans-serif; color: #555;\">\n",
" <strong>Watch: </strong> How to Train\n",
" <a href=\"https://github.com/ultralytics/ultralytics\">Ultralytics</a>\n",
" <a href=\"https://docs.ultralytics.com/models/yolo11/\">YOLO11</a> Model on Custom Dataset using Google Colab Notebook 🚀\n",
" </p>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7mGmQbAO5pQb"
},
"source": [
"# Setup\n",
"\n",
"Clone GitHub [repository](https://github.com/ultralytics/yolov5), install [dependencies](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) and check PyTorch and GPU."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "wbvMlHd_QwMG",
"outputId": "0806e375-610d-4ec0-c867-763dbb518279"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"YOLOv5 🚀 v7.0-3-g61ebf5e Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Setup complete ✅ (2 CPUs, 12.7 GB RAM, 22.6/78.2 GB disk)\n"
]
}
],
"source": [
"!git clone https://github.com/ultralytics/yolov5 # clone\n",
"%cd yolov5\n",
"%pip install -qr requirements.txt # install\n",
"\n",
"import torch\n",
"\n",
"import utils\n",
"\n",
"display = utils.notebook_init() # checks"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4JnkELT0cIJg"
},
"source": [
"# 1. Predict\n",
"\n",
"`classify/predict.py` runs YOLOv5 Classification inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases), and saving results to `runs/predict-cls`. Example inference sources are:\n",
"\n",
"```shell\n",
"python classify/predict.py --source 0 # webcam\n",
" img.jpg # image \n",
" vid.mp4 # video\n",
" screen # screenshot\n",
" path/ # directory\n",
" 'path/*.jpg' # glob\n",
" 'https://youtu.be/LNwODJXcvt4' # YouTube\n",
" 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "zR9ZbuQCH7FX",
"outputId": "50504ef7-aa3e-4281-a4e3-d0c7df3c0ffe"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001B[34m\u001B[1mclassify/predict: \u001B[0mweights=['yolov5s-cls.pt'], source=data/images, data=data/coco128.yaml, imgsz=[224, 224], device=, view_img=False, save_txt=False, nosave=False, augment=False, visualize=False, update=False, project=runs/predict-cls, name=exp, exist_ok=False, half=False, dnn=False, vid_stride=1\n",
"YOLOv5 🚀 v7.0-3-g61ebf5e Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n",
"\n",
"Downloading https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-cls.pt to yolov5s-cls.pt...\n",
"100% 10.5M/10.5M [00:00<00:00, 12.3MB/s]\n",
"\n",
"Fusing layers... \n",
"Model summary: 117 layers, 5447688 parameters, 0 gradients, 11.4 GFLOPs\n",
"image 1/2 /content/yolov5/data/images/bus.jpg: 224x224 minibus 0.39, police van 0.24, amphibious vehicle 0.05, recreational vehicle 0.04, trolleybus 0.03, 3.9ms\n",
"image 2/2 /content/yolov5/data/images/zidane.jpg: 224x224 suit 0.38, bow tie 0.19, bridegroom 0.18, rugby ball 0.04, stage 0.02, 4.6ms\n",
"Speed: 0.3ms pre-process, 4.3ms inference, 1.5ms NMS per image at shape (1, 3, 224, 224)\n",
"Results saved to \u001B[1mruns/predict-cls/exp\u001B[0m\n"
]
}
],
"source": [
"!python classify/predict.py --weights yolov5s-cls.pt --img 224 --source data/images\n",
"# display.Image(filename='runs/predict-cls/exp/zidane.jpg', width=600)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hkAzDWJ7cWTr"
},
"source": [
" \n",
"<img align=\"left\" src=\"https://user-images.githubusercontent.com/26833433/202808393-50deb439-ae1b-4246-a685-7560c9b37211.jpg\" width=\"600\">"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0eq1SMWl6Sfn"
},
"source": [
"# 2. Validate\n",
"Validate a model's accuracy on the [Imagenet](https://image-net.org/) dataset's `val` or `test` splits. Models are downloaded automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases). To show results by class use the `--verbose` flag."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "WQPtK1QYVaD_",
"outputId": "20fc0630-141e-4a90-ea06-342cbd7ce496"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--2022-11-22 19:53:40-- https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar\n",
"Resolving image-net.org (image-net.org)... 171.64.68.16\n",
"Connecting to image-net.org (image-net.org)|171.64.68.16|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 6744924160 (6.3G) [application/x-tar]\n",
"Saving to: ‘ILSVRC2012_img_val.tar’\n",
"\n",
"ILSVRC2012_img_val. 100%[===================>] 6.28G 16.1MB/s in 10m 52s \n",
"\n",
"2022-11-22 20:04:32 (9.87 MB/s) - ‘ILSVRC2012_img_val.tar’ saved [6744924160/6744924160]\n",
"\n"
]
}
],
"source": [
"# Download Imagenet val (6.3G, 50000 images)\n",
"!bash data/scripts/get_imagenet.sh --val"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "X58w8JLpMnjH",
"outputId": "41843132-98e2-4c25-d474-4cd7b246fb8e"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001B[34m\u001B[1mclassify/val: \u001B[0mdata=../datasets/imagenet, weights=['yolov5s-cls.pt'], batch_size=128, imgsz=224, device=, workers=8, verbose=True, project=runs/val-cls, name=exp, exist_ok=False, half=True, dnn=False\n",
"YOLOv5 🚀 v7.0-3-g61ebf5e Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n",
"\n",
"Fusing layers... \n",
"Model summary: 117 layers, 5447688 parameters, 0 gradients, 11.4 GFLOPs\n",
"validating: 100% 391/391 [04:57<00:00, 1.31it/s]\n",
" Class Images top1_acc top5_acc\n",
" all 50000 0.715 0.902\n",
" tench 50 0.94 0.98\n",
" goldfish 50 0.88 0.92\n",
" great white shark 50 0.78 0.96\n",
" tiger shark 50 0.68 0.96\n",
" hammerhead shark 50 0.82 0.92\n",
" electric ray 50 0.76 0.9\n",
" stingray 50 0.7 0.9\n",
" cock 50 0.78 0.92\n",
" hen 50 0.84 0.96\n",
" ostrich 50 0.98 1\n",
" brambling 50 0.9 0.96\n",
" goldfinch 50 0.92 0.98\n",
" house finch 50 0.88 0.96\n",
" junco 50 0.94 0.98\n",
" indigo bunting 50 0.86 0.88\n",
" American robin 50 0.9 0.96\n",
" bulbul 50 0.84 0.96\n",
" jay 50 0.9 0.96\n",
" magpie 50 0.84 0.96\n",
" chickadee 50 0.9 1\n",
" American dipper 50 0.82 0.92\n",
" kite 50 0.76 0.94\n",
" bald eagle 50 0.92 1\n",
" vulture 50 0.96 1\n",
" great grey owl 50 0.94 0.98\n",
" fire salamander 50 0.96 0.98\n",
" smooth newt 50 0.58 0.94\n",
" newt 50 0.74 0.9\n",
" spotted salamander 50 0.86 0.94\n",
" axolotl 50 0.86 0.96\n",
" American bullfrog 50 0.78 0.92\n",
" tree frog 50 0.84 0.96\n",
" tailed frog 50 0.48 0.8\n",
" loggerhead sea turtle 50 0.68 0.94\n",
" leatherback sea turtle 50 0.5 0.8\n",
" mud turtle 50 0.64 0.84\n",
" terrapin 50 0.52 0.98\n",
" box turtle 50 0.84 0.98\n",
" banded gecko 50 0.7 0.88\n",
" green iguana 50 0.76 0.94\n",
" Carolina anole 50 0.58 0.96\n",
"desert grassland whiptail lizard 50 0.82 0.94\n",
" agama 50 0.74 0.92\n",
" frilled-necked lizard 50 0.84 0.86\n",
" alligator lizard 50 0.58 0.78\n",
" Gila monster 50 0.72 0.8\n",
" European green lizard 50 0.42 0.9\n",
" chameleon 50 0.76 0.84\n",
" Komodo dragon 50 0.86 0.96\n",
" Nile crocodile 50 0.7 0.84\n",
" American alligator 50 0.76 0.96\n",
" triceratops 50 0.9 0.94\n",
" worm snake 50 0.76 0.88\n",
" ring-necked snake 50 0.8 0.92\n",
" eastern hog-nosed snake 50 0.58 0.88\n",
" smooth green snake 50 0.6 0.94\n",
" kingsnake 50 0.82 0.9\n",
" garter snake 50 0.88 0.94\n",
" water snake 50 0.7 0.94\n",
" vine snake 50 0.66 0.76\n",
" night snake 50 0.34 0.82\n",
" boa constrictor 50 0.8 0.96\n",
" African rock python 50 0.48 0.76\n",
" Indian cobra 50 0.82 0.94\n",
" green mamba 50 0.54 0.86\n",
" sea snake 50 0.62 0.9\n",
" Saharan horned viper 50 0.56 0.86\n",
"eastern diamondback rattlesnake 50 0.6 0.86\n",
" sidewinder 50 0.28 0.86\n",
" trilobite 50 0.98 0.98\n",
" harvestman 50 0.86 0.94\n",
" scorpion 50 0.86 0.94\n",
" yellow garden spider 50 0.92 0.96\n",
" barn spider 50 0.38 0.98\n",
" European garden spider 50 0.62 0.98\n",
" southern black widow 50 0.88 0.94\n",
" tarantula 50 0.94 1\n",
" wolf spider 50 0.82 0.92\n",
" tick 50 0.74 0.84\n",
" centipede 50 0.68 0.82\n",
" black grouse 50 0.88 0.98\n",
" ptarmigan 50 0.78 0.94\n",
" ruffed grouse 50 0.88 1\n",
" prairie grouse 50 0.92 1\n",
" peacock 50 0.88 0.9\n",
" quail 50 0.9 0.94\n",
" partridge 50 0.74 0.96\n",
" grey parrot 50 0.9 0.96\n",
" macaw 50 0.88 0.98\n",
"sulphur-crested cockatoo 50 0.86 0.92\n",
" lorikeet 50 0.96 1\n",
" coucal 50 0.82 0.88\n",
" bee eater 50 0.96 0.98\n",
" hornbill 50 0.9 0.96\n",
" hummingbird 50 0.88 0.96\n",
" jacamar 50 0.92 0.94\n",
" toucan 50 0.84 0.94\n",
" duck 50 0.76 0.94\n",
" red-breasted merganser 50 0.86 0.96\n",
" goose 50 0.74 0.96\n",
" black swan 50 0.94 0.98\n",
" tusker 50 0.54 0.92\n",
" echidna 50 0.98 1\n",
" platypus 50 0.72 0.84\n",
" wallaby 50 0.78 0.88\n",
" koala 50 0.84 0.92\n",
" wombat 50 0.78 0.84\n",
" jellyfish 50 0.88 0.96\n",
" sea anemone 50 0.72 0.9\n",
" brain coral 50 0.88 0.96\n",
" flatworm 50 0.8 0.98\n",
" nematode 50 0.86 0.9\n",
" conch 50 0.74 0.88\n",
" snail 50 0.78 0.88\n",
" slug 50 0.74 0.82\n",
" sea slug 50 0.88 0.98\n",
" chiton 50 0.88 0.98\n",
" chambered nautilus 50 0.88 0.92\n",
" Dungeness crab 50 0.78 0.94\n",
" rock crab 50 0.68 0.86\n",
" fiddler crab 50 0.64 0.86\n",
" red king crab 50 0.76 0.96\n",
" American lobster 50 0.78 0.96\n",
" spiny lobster 50 0.74 0.88\n",
" crayfish 50 0.56 0.86\n",
" hermit crab 50 0.78 0.96\n",
" isopod 50 0.66 0.78\n",
" white stork 50 0.88 0.96\n",
" black stork 50 0.84 0.98\n",
" spoonbill 50 0.96 1\n",
" flamingo 50 0.94 1\n",
" little blue heron 50 0.92 0.98\n",
" great egret 50 0.9 0.96\n",
" bittern 50 0.86 0.94\n",
" crane (bird) 50 0.62 0.9\n",
" limpkin 50 0.98 1\n",
" common gallinule 50 0.92 0.96\n",
" American coot 50 0.9 0.98\n",
" bustard 50 0.92 0.96\n",
" ruddy turnstone 50 0.94 1\n",
" dunlin 50 0.86 0.94\n",
" common redshank 50 0.9 0.96\n",
" dowitcher 50 0.84 0.96\n",
" oystercatcher 50 0.86 0.94\n",
" pelican 50 0.92 0.96\n",
" king penguin 50 0.88 0.96\n",
" albatross 50 0.9 1\n",
" grey whale 50 0.84 0.92\n",
" killer whale 50 0.92 1\n",
" dugong 50 0.84 0.96\n",
" sea lion 50 0.82 0.92\n",
" Chihuahua 50 0.66 0.84\n",
" Japanese Chin 50 0.72 0.98\n",
" Maltese 50 0.76 0.94\n",
" Pekingese 50 0.84 0.94\n",
" Shih Tzu 50 0.74 0.96\n",
" King Charles Spaniel 50 0.88 0.98\n",
" Papillon 50 0.86 0.94\n",
" toy terrier 50 0.48 0.94\n",
" Rhodesian Ridgeback 50 0.76 0.98\n",
" Afghan Hound 50 0.84 1\n",
" Basset Hound 50 0.8 0.92\n",
" Beagle 50 0.82 0.96\n",
" Bloodhound 50 0.48 0.72\n",
" Bluetick Coonhound 50 0.86 0.94\n",
" Black and Tan Coonhound 50 0.54 0.8\n",
"Treeing Walker Coonhound 50 0.66 0.98\n",
" English foxhound 50 0.32 0.84\n",
" Redbone Coonhound 50 0.62 0.94\n",
" borzoi 50 0.92 1\n",
" Irish Wolfhound 50 0.48 0.88\n",
" Italian Greyhound 50 0.76 0.98\n",
" Whippet 50 0.74 0.92\n",
" Ibizan Hound 50 0.6 0.86\n",
" Norwegian Elkhound 50 0.88 0.98\n",
" Otterhound 50 0.62 0.9\n",
" Saluki 50 0.72 0.92\n",
" Scottish Deerhound 50 0.86 0.98\n",
" Weimaraner 50 0.88 0.94\n",
"Staffordshire Bull Terrier 50 0.66 0.98\n",
"American Staffordshire Terrier 50 0.64 0.92\n",
" Bedlington Terrier 50 0.9 0.92\n",
" Border Terrier 50 0.86 0.92\n",
" Kerry Blue Terrier 50 0.78 0.98\n",
" Irish Terrier 50 0.7 0.96\n",
" Norfolk Terrier 50 0.68 0.9\n",
" Norwich Terrier 50 0.72 1\n",
" Yorkshire Terrier 50 0.66 0.9\n",
" Wire Fox Terrier 50 0.64 0.98\n",
" Lakeland Terrier 50 0.74 0.92\n",
" Sealyham Terrier 50 0.76 0.9\n",
" Airedale Terrier 50 0.82 0.92\n",
" Cairn Terrier 50 0.76 0.9\n",
" Australian Terrier 50 0.48 0.84\n",
" Dandie Dinmont Terrier 50 0.82 0.92\n",
" Boston Terrier 50 0.92 1\n",
" Miniature Schnauzer 50 0.68 0.9\n",
" Giant Schnauzer 50 0.72 0.98\n",
" Standard Schnauzer 50 0.74 1\n",
" Scottish Terrier 50 0.76 0.96\n",
" Tibetan Terrier 50 0.48 1\n",
"Australian Silky Terrier 50 0.66 0.96\n",
"Soft-coated Wheaten Terrier 50 0.74 0.96\n",
"West Highland White Terrier 50 0.88 0.96\n",
" Lhasa Apso 50 0.68 0.96\n",
" Flat-Coated Retriever 50 0.72 0.94\n",
" Curly-coated Retriever 50 0.82 0.94\n",
" Golden Retriever 50 0.86 0.94\n",
" Labrador Retriever 50 0.82 0.94\n",
"Chesapeake Bay Retriever 50 0.76 0.96\n",
"German Shorthaired Pointer 50 0.8 0.96\n",
" Vizsla 50 0.68 0.96\n",
" English Setter 50 0.7 1\n",
" Irish Setter 50 0.8 0.9\n",
" Gordon Setter 50 0.84 0.92\n",
" Brittany 50 0.84 0.96\n",
" Clumber Spaniel 50 0.92 0.96\n",
"English Springer Spaniel 50 0.88 1\n",
" Welsh Springer Spaniel 50 0.92 1\n",
" Cocker Spaniels 50 0.7 0.94\n",
" Sussex Spaniel 50 0.72 0.92\n",
" Irish Water Spaniel 50 0.88 0.98\n",
" Kuvasz 50 0.66 0.9\n",
" Schipperke 50 0.9 0.98\n",
" Groenendael 50 0.8 0.94\n",
" Malinois 50 0.86 0.98\n",
" Briard 50 0.52 0.8\n",
" Australian Kelpie 50 0.6 0.88\n",
" Komondor 50 0.88 0.94\n",
" Old English Sheepdog 50 0.94 0.98\n",
" Shetland Sheepdog 50 0.74 0.9\n",
" collie 50 0.6 0.96\n",
" Border Collie 50 0.74 0.96\n",
" Bouvier des Flandres 50 0.78 0.94\n",
" Rottweiler 50 0.88 0.96\n",
" German Shepherd Dog 50 0.8 0.98\n",
" Dobermann 50 0.68 0.96\n",
" Miniature Pinscher 50 0.76 0.88\n",
"Greater Swiss Mountain Dog 50 0.68 0.94\n",
" Bernese Mountain Dog 50 0.96 1\n",
" Appenzeller Sennenhund 50 0.22 1\n",
" Entlebucher Sennenhund 50 0.64 0.98\n",
" Boxer 50 0.7 0.92\n",
" Bullmastiff 50 0.78 0.98\n",
" Tibetan Mastiff 50 0.88 0.96\n",
" French Bulldog 50 0.84 0.94\n",
" Great Dane 50 0.54 0.9\n",
" St. Bernard 50 0.92 1\n",
" husky 50 0.46 0.98\n",
" Alaskan Malamute 50 0.76 0.96\n",
" Siberian Husky 50 0.46 0.98\n",
" Dalmatian 50 0.94 0.98\n",
" Affenpinscher 50 0.78 0.9\n",
" Basenji 50 0.92 0.94\n",
" pug 50 0.94 0.98\n",
" Leonberger 50 1 1\n",
" Newfoundland 50 0.78 0.96\n",
" Pyrenean Mountain Dog 50 0.78 0.96\n",
" Samoyed 50 0.96 1\n",
" Pomeranian 50 0.98 1\n",
" Chow Chow 50 0.9 0.96\n",
" Keeshond 50 0.88 0.94\n",
" Griffon Bruxellois 50 0.84 0.98\n",
" Pembroke Welsh Corgi 50 0.82 0.94\n",
" Cardigan Welsh Corgi 50 0.66 0.98\n",
" Toy Poodle 50 0.52 0.88\n",
" Miniature Poodle 50 0.52 0.92\n",
" Standard Poodle 50 0.8 1\n",
" Mexican hairless dog 50 0.88 0.98\n",
" grey wolf 50 0.82 0.92\n",
" Alaskan tundra wolf 50 0.78 0.98\n",
" red wolf 50 0.48 0.9\n",
" coyote 50 0.64 0.86\n",
" dingo 50 0.76 0.88\n",
" dhole 50 0.9 0.98\n",
" African wild dog 50 0.98 1\n",
" hyena 50 0.88 0.96\n",
" red fox 50 0.54 0.92\n",
" kit fox 50 0.72 0.98\n",
" Arctic fox 50 0.94 1\n",
" grey fox 50 0.7 0.94\n",
" tabby cat 50 0.54 0.92\n",
" tiger cat 50 0.22 0.94\n",
" Persian cat 50 0.9 0.98\n",
" Siamese cat 50 0.96 1\n",
" Egyptian Mau 50 0.54 0.8\n",
" cougar 50 0.9 1\n",
" lynx 50 0.72 0.88\n",
" leopard 50 0.78 0.98\n",
" snow leopard 50 0.9 0.98\n",
" jaguar 50 0.7 0.94\n",
" lion 50 0.9 0.98\n",
" tiger 50 0.92 0.98\n",
" cheetah 50 0.94 0.98\n",
" brown bear 50 0.94 0.98\n",
" American black bear 50 0.8 1\n",
" polar bear 50 0.84 0.96\n",
" sloth bear 50 0.72 0.92\n",
" mongoose 50 0.7 0.92\n",
" meerkat 50 0.82 0.92\n",
" tiger beetle 50 0.92 0.94\n",
" ladybug 50 0.86 0.94\n",
" ground beetle 50 0.64 0.94\n",
" longhorn beetle 50 0.62 0.88\n",
" leaf beetle 50 0.64 0.98\n",
" dung beetle 50 0.86 0.98\n",
" rhinoceros beetle 50 0.86 0.94\n",
" weevil 50 0.9 1\n",
" fly 50 0.78 0.94\n",
" bee 50 0.68 0.94\n",
" ant 50 0.68 0.78\n",
" grasshopper 50 0.5 0.92\n",
" cricket 50 0.64 0.92\n",
" stick insect 50 0.64 0.92\n",
" cockroach 50 0.72 0.8\n",
" mantis 50 0.64 0.86\n",
" cicada 50 0.9 0.96\n",
" leafhopper 50 0.88 0.94\n",
" lacewing 50 0.78 0.92\n",
" dragonfly 50 0.82 0.98\n",
" damselfly 50 0.82 1\n",
" red admiral 50 0.94 0.96\n",
" ringlet 50 0.86 0.98\n",
" monarch butterfly 50 0.9 0.92\n",
" small white 50 0.9 1\n",
" sulfur butterfly 50 0.92 1\n",
"gossamer-winged butterfly 50 0.88 1\n",
" starfish 50 0.88 0.92\n",
" sea urchin 50 0.84 0.94\n",
" sea cucumber 50 0.66 0.84\n",
" cottontail rabbit 50 0.72 0.94\n",
" hare 50 0.84 0.96\n",
" Angora rabbit 50 0.94 0.98\n",
" hamster 50 0.96 1\n",
" porcupine 50 0.88 0.98\n",
" fox squirrel 50 0.76 0.94\n",
" marmot 50 0.92 0.96\n",
" beaver 50 0.78 0.94\n",
" guinea pig 50 0.78 0.94\n",
" common sorrel 50 0.96 0.98\n",
" zebra 50 0.94 0.96\n",
" pig 50 0.5 0.76\n",
" wild boar 50 0.84 0.96\n",
" warthog 50 0.84 0.96\n",
" hippopotamus 50 0.88 0.96\n",
" ox 50 0.48 0.94\n",
" water buffalo 50 0.78 0.94\n",
" bison 50 0.88 0.96\n",
" ram 50 0.58 0.92\n",
" bighorn sheep 50 0.66 1\n",
" Alpine ibex 50 0.92 0.98\n",
" hartebeest 50 0.94 1\n",
" impala 50 0.82 0.96\n",
" gazelle 50 0.7 0.96\n",
" dromedary 50 0.9 1\n",
" llama 50 0.82 0.94\n",
" weasel 50 0.44 0.92\n",
" mink 50 0.78 0.96\n",
" Europ
gitextract_9q02duc2/ ├── .dockerignore ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug-report.yml │ │ ├── config.yml │ │ ├── feature-request.yml │ │ └── question.yml │ ├── dependabot.yml │ └── workflows/ │ ├── ci-testing.yml │ ├── cla.yml │ ├── docker.yml │ ├── format.yml │ ├── links.yml │ ├── merge-main-into-prs.yml │ └── stale.yml ├── .gitignore ├── CITATION.cff ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── README.zh-CN.md ├── benchmarks.py ├── classify/ │ ├── predict.py │ ├── train.py │ ├── tutorial.ipynb │ └── val.py ├── data/ │ ├── Argoverse.yaml │ ├── GlobalWheat2020.yaml │ ├── ImageNet.yaml │ ├── SKU-110K.yaml │ ├── VisDrone.yaml │ ├── coco.yaml │ ├── coco128-seg.yaml │ ├── coco128.yaml │ ├── hyps/ │ │ ├── hyp.Objects365.yaml │ │ ├── hyp.VOC.yaml │ │ ├── hyp.no-augmentation.yaml │ │ ├── hyp.scratch-high.yaml │ │ ├── hyp.scratch-low.yaml │ │ └── hyp.scratch-med.yaml │ ├── objects365.yaml │ ├── scripts/ │ │ ├── download_weights.sh │ │ ├── get_coco.sh │ │ ├── get_coco128.sh │ │ └── get_imagenet.sh │ ├── voc.yaml │ └── xView.yaml ├── detect.py ├── export.py ├── hubconf.py ├── models/ │ ├── __init__.py │ ├── common.py │ ├── experimental.py │ ├── hub/ │ │ ├── anchors.yaml │ │ ├── yolov5-bifpn.yaml │ │ ├── yolov5-fpn.yaml │ │ ├── yolov5-p2.yaml │ │ ├── yolov5-p34.yaml │ │ ├── yolov5-p6.yaml │ │ ├── yolov5-p7.yaml │ │ ├── yolov5-panet.yaml │ │ ├── yolov5l6.yaml │ │ ├── yolov5m6.yaml │ │ ├── yolov5n6.yaml │ │ ├── yolov5s-LeakyReLU.yaml │ │ ├── yolov5s-ghost.yaml │ │ ├── yolov5s-transformer.yaml │ │ ├── yolov5s6.yaml │ │ └── yolov5x6.yaml │ ├── segment/ │ │ ├── yolov5l-seg.yaml │ │ ├── yolov5m-seg.yaml │ │ ├── yolov5n-seg.yaml │ │ ├── yolov5s-seg.yaml │ │ └── yolov5x-seg.yaml │ ├── tf.py │ ├── yolo.py │ ├── yolov3-spp.yaml │ ├── yolov3-tiny.yaml │ ├── yolov3.yaml │ ├── yolov5l.yaml │ ├── yolov5m.yaml │ ├── yolov5n.yaml │ ├── yolov5s.yaml │ └── yolov5x.yaml ├── pyproject.toml ├── requirements.txt ├── segment/ │ ├── predict.py │ ├── train.py │ ├── tutorial.ipynb │ └── val.py ├── train.py ├── tutorial.ipynb ├── utils/ │ ├── __init__.py │ ├── activations.py │ ├── augmentations.py │ ├── autoanchor.py │ ├── autobatch.py │ ├── aws/ │ │ ├── __init__.py │ │ ├── mime.sh │ │ ├── resume.py │ │ └── userdata.sh │ ├── callbacks.py │ ├── dataloaders.py │ ├── docker/ │ │ ├── Dockerfile │ │ ├── Dockerfile-arm64 │ │ └── Dockerfile-cpu │ ├── downloads.py │ ├── flask_rest_api/ │ │ ├── README.md │ │ ├── example_request.py │ │ └── restapi.py │ ├── general.py │ ├── google_app_engine/ │ │ ├── Dockerfile │ │ ├── additional_requirements.txt │ │ └── app.yaml │ ├── loggers/ │ │ ├── __init__.py │ │ ├── clearml/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── clearml_utils.py │ │ │ └── hpo.py │ │ ├── comet/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── comet_utils.py │ │ │ └── hpo.py │ │ └── wandb/ │ │ ├── __init__.py │ │ └── wandb_utils.py │ ├── loss.py │ ├── metrics.py │ ├── plots.py │ ├── segment/ │ │ ├── __init__.py │ │ ├── augmentations.py │ │ ├── dataloaders.py │ │ ├── general.py │ │ ├── loss.py │ │ ├── metrics.py │ │ └── plots.py │ ├── torch_utils.py │ └── triton.py └── val.py
SYMBOL INDEX (683 symbols across 43 files)
FILE: benchmarks.py
function run (line 52) | def run(
function test (line 149) | def test(
function parse_opt (line 222) | def parse_opt():
function main (line 271) | def main(opt):
FILE: classify/predict.py
function run (line 68) | def run(
function parse_opt (line 207) | def parse_opt():
function main (line 233) | def main(opt):
FILE: classify/train.py
function train (line 78) | def train(opt, device):
function parse_opt (line 315) | def parse_opt(known=False):
function main (line 343) | def main(opt):
function run (line 367) | def run(**kwargs):
FILE: classify/val.py
function run (line 53) | def run(
function parse_opt (line 150) | def parse_opt():
function main (line 170) | def main(opt):
FILE: detect.py
function run (line 69) | def run(
function parse_opt (line 288) | def parse_opt():
function main (line 365) | def main(opt):
FILE: export.py
class iOSModel (line 93) | class iOSModel(torch.nn.Module):
method __init__ (line 96) | def __init__(self, model, im):
method forward (line 126) | def forward(self, x):
function export_formats (line 164) | def export_formats():
function try_export (line 201) | def try_export(inner_func):
function export_torchscript (line 241) | def export_torchscript(model, im, file, optimize, prefix=colorstr("Torch...
function export_onnx (line 291) | def export_onnx(model, im, file, opset, dynamic, simplify, prefix=colors...
function export_openvino (line 386) | def export_openvino(file, metadata, half, int8, data, prefix=colorstr("O...
function export_paddle (line 475) | def export_paddle(model, im, file, metadata, prefix=colorstr("PaddlePadd...
function export_coreml (line 524) | def export_coreml(model, im, file, int8, half, nms, prefix=colorstr("Cor...
function export_engine (line 583) | def export_engine(model, im, file, half, dynamic, simplify, workspace=4,...
function export_saved_model (line 680) | def export_saved_model(
function export_pb (line 777) | def export_pb(keras_model, file, prefix=colorstr("TensorFlow GraphDef:")):
function export_tflite (line 819) | def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, ...
function export_edgetpu (line 888) | def export_edgetpu(file, prefix=colorstr("Edge TPU:")):
function export_tfjs (line 957) | def export_tfjs(file, int8, prefix=colorstr("TensorFlow.js:")):
function add_tflite_metadata (line 1042) | def add_tflite_metadata(file, metadata, num_outputs):
function pipeline_coreml (line 1131) | def pipeline_coreml(model, im, file, names, y, prefix=colorstr("CoreML P...
function run (line 1312) | def run(
function parse_opt (line 1493) | def parse_opt(known=False):
function main (line 1547) | def main(opt):
FILE: hubconf.py
function _create (line 16) | def _create(name, pretrained=True, channels=3, classes=80, autoshape=Tru...
function custom (line 97) | def custom(path="path/to/model.pt", autoshape=True, _verbose=True, devic...
function yolov5n (line 126) | def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _ve...
function yolov5s (line 158) | def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _ve...
function yolov5m (line 186) | def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _ve...
function yolov5l (line 212) | def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _ve...
function yolov5x (line 240) | def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _ve...
function yolov5n6 (line 273) | def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _v...
function yolov5s6 (line 300) | def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _v...
function yolov5m6 (line 328) | def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _v...
function yolov5l6 (line 361) | def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _v...
function yolov5x6 (line 391) | def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _v...
FILE: models/common.py
function autopad (line 48) | def autopad(k, p=None, d=1): # kernel, padding, dilation
class Conv (line 57) | class Conv(nn.Module):
method __init__ (line 62) | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
method forward (line 71) | def forward(self, x):
method forward_fuse (line 77) | def forward_fuse(self, x):
class DWConv (line 84) | class DWConv(Conv):
method __init__ (line 87) | def __init__(self, c1, c2, k=1, s=1, d=1, act=True): # ch_in, ch_out,...
class DWConvTranspose2d (line 94) | class DWConvTranspose2d(nn.ConvTranspose2d):
method __init__ (line 97) | def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, ke...
class TransformerLayer (line 104) | class TransformerLayer(nn.Module):
method __init__ (line 107) | def __init__(self, c, num_heads):
method forward (line 119) | def forward(self, x):
class TransformerBlock (line 128) | class TransformerBlock(nn.Module):
method __init__ (line 131) | def __init__(self, c1, c2, num_heads, num_layers):
method forward (line 141) | def forward(self, x):
class Bottleneck (line 150) | class Bottleneck(nn.Module):
method __init__ (line 153) | def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_ou...
method forward (line 163) | def forward(self, x):
class BottleneckCSP (line 169) | class BottleneckCSP(nn.Module):
method __init__ (line 172) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ...
method forward (line 186) | def forward(self, x):
class CrossConv (line 194) | class CrossConv(nn.Module):
method __init__ (line 197) | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
method forward (line 207) | def forward(self, x):
class C3 (line 212) | class C3(nn.Module):
method __init__ (line 215) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ...
method forward (line 225) | def forward(self, x):
class C3x (line 230) | class C3x(C3):
method __init__ (line 233) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
class C3TR (line 240) | class C3TR(C3):
method __init__ (line 243) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
class C3SPP (line 250) | class C3SPP(C3):
method __init__ (line 253) | def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
class C3Ghost (line 260) | class C3Ghost(C3):
method __init__ (line 263) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
class SPP (line 270) | class SPP(nn.Module):
method __init__ (line 273) | def __init__(self, c1, c2, k=(5, 9, 13)):
method forward (line 284) | def forward(self, x):
class SPPF (line 296) | class SPPF(nn.Module):
method __init__ (line 299) | def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
method forward (line 307) | def forward(self, x):
class Focus (line 319) | class Focus(nn.Module):
method __init__ (line 322) | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in,...
method forward (line 330) | def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
class GhostConv (line 336) | class GhostConv(nn.Module):
method __init__ (line 339) | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out,...
method forward (line 348) | def forward(self, x):
class GhostBottleneck (line 354) | class GhostBottleneck(nn.Module):
method __init__ (line 357) | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
method forward (line 372) | def forward(self, x):
class Contract (line 377) | class Contract(nn.Module):
method __init__ (line 380) | def __init__(self, gain=2):
method forward (line 387) | def forward(self, x):
class Expand (line 398) | class Expand(nn.Module):
method __init__ (line 401) | def __init__(self, gain=2):
method forward (line 408) | def forward(self, x):
class Concat (line 419) | class Concat(nn.Module):
method __init__ (line 422) | def __init__(self, dimension=1):
method forward (line 427) | def forward(self, x):
class DetectMultiBackend (line 434) | class DetectMultiBackend(nn.Module):
method __init__ (line 437) | def __init__(self, weights="yolov5s.pt", device=torch.device("cpu"), d...
method forward (line 644) | def forward(self, im, augment=False, visualize=False):
method from_numpy (line 726) | def from_numpy(self, x):
method warmup (line 732) | def warmup(self, imgsz=(1, 3, 640, 640)):
method _model_type (line 741) | def _model_type(p="path/to/model.pt"):
method _load_metadata (line 760) | def _load_metadata(f=Path("path/to/meta.yaml")):
class AutoShape (line 768) | class AutoShape(nn.Module):
method __init__ (line 779) | def __init__(self, model, verbose=True):
method _apply (line 795) | def _apply(self, fn):
method forward (line 809) | def forward(self, ims, size=640, augment=False, profile=False):
class Detections (line 877) | class Detections:
method __init__ (line 880) | def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shap...
method _run (line 900) | def _run(self, pprint=False, show=False, save=False, crop=False, rende...
method show (line 955) | def show(self, labels=True):
method save (line 962) | def save(self, labels=True, save_dir="runs/detect/exp", exist_ok=False):
method crop (line 970) | def crop(self, save=True, save_dir="runs/detect/exp", exist_ok=False):
method render (line 978) | def render(self, labels=True):
method pandas (line 986) | def pandas(self):
method tolist (line 996) | def tolist(self):
method print (line 1011) | def print(self):
method __len__ (line 1015) | def __len__(self): # override len(results)
method __str__ (line 1019) | def __str__(self): # override print(results)
method __repr__ (line 1023) | def __repr__(self):
class Proto (line 1028) | class Proto(nn.Module):
method __init__ (line 1031) | def __init__(self, c1, c_=256, c2=32): # ch_in, number of protos, num...
method forward (line 1039) | def forward(self, x):
class Classify (line 1044) | class Classify(nn.Module):
method __init__ (line 1047) | def __init__(
method forward (line 1060) | def forward(self, x):
FILE: models/experimental.py
class Sum (line 14) | class Sum(nn.Module):
method __init__ (line 17) | def __init__(self, n, weight=False): # n: number of inputs
method forward (line 28) | def forward(self, x):
class MixConv2d (line 44) | class MixConv2d(nn.Module):
method __init__ (line 47) | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch...
method forward (line 69) | def forward(self, x):
class Ensemble (line 74) | class Ensemble(nn.ModuleList):
method __init__ (line 77) | def __init__(self):
method forward (line 81) | def forward(self, x, augment=False, profile=False, visualize=False):
function attempt_load (line 92) | def attempt_load(weights, device=None, inplace=True, fuse=True):
FILE: models/tf.py
class TFBN (line 51) | class TFBN(keras.layers.Layer):
method __init__ (line 54) | def __init__(self, w=None):
method call (line 65) | def call(self, inputs):
class TFPad (line 70) | class TFPad(keras.layers.Layer):
method __init__ (line 73) | def __init__(self, pad):
method call (line 81) | def call(self, inputs):
class TFConv (line 88) | class TFConv(keras.layers.Layer):
method __init__ (line 91) | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
method call (line 112) | def call(self, inputs):
class TFDWConv (line 117) | class TFDWConv(keras.layers.Layer):
method __init__ (line 120) | def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
method call (line 137) | def call(self, inputs):
class TFDWConvTranspose2d (line 142) | class TFDWConvTranspose2d(keras.layers.Layer):
method __init__ (line 145) | def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
method call (line 166) | def call(self, inputs):
class TFFocus (line 173) | class TFFocus(keras.layers.Layer):
method __init__ (line 176) | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
method call (line 183) | def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
class TFBottleneck (line 191) | class TFBottleneck(keras.layers.Layer):
method __init__ (line 194) | def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_i...
method call (line 202) | def call(self, inputs):
class TFCrossConv (line 209) | class TFCrossConv(keras.layers.Layer):
method __init__ (line 212) | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
method call (line 222) | def call(self, inputs):
class TFConv2d (line 227) | class TFConv2d(keras.layers.Layer):
method __init__ (line 230) | def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
method call (line 246) | def call(self, inputs):
class TFBottleneckCSP (line 251) | class TFBottleneckCSP(keras.layers.Layer):
method __init__ (line 254) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
method call (line 268) | def call(self, inputs):
class TFC3 (line 275) | class TFC3(keras.layers.Layer):
method __init__ (line 278) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
method call (line 287) | def call(self, inputs):
class TFC3x (line 294) | class TFC3x(keras.layers.Layer):
method __init__ (line 297) | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
method call (line 310) | def call(self, inputs):
class TFSPP (line 315) | class TFSPP(keras.layers.Layer):
method __init__ (line 318) | def __init__(self, c1, c2, k=(5, 9, 13), w=None):
method call (line 328) | def call(self, inputs):
class TFSPPF (line 334) | class TFSPPF(keras.layers.Layer):
method __init__ (line 337) | def __init__(self, c1, c2, k=5, w=None):
method call (line 346) | def call(self, inputs):
class TFDetect (line 354) | class TFDetect(keras.layers.Layer):
method __init__ (line 357) | def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None)...
method call (line 375) | def call(self, inputs):
method _make_grid (line 402) | def _make_grid(nx=20, ny=20):
class TFSegment (line 409) | class TFSegment(TFDetect):
method __init__ (line 412) | def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), imgsz=(64...
method call (line 422) | def call(self, x):
class TFProto (line 431) | class TFProto(keras.layers.Layer):
method __init__ (line 434) | def __init__(self, c1, c_=256, c2=32, w=None):
method call (line 442) | def call(self, inputs):
class TFUpsample (line 447) | class TFUpsample(keras.layers.Layer):
method __init__ (line 450) | def __init__(self, size, scale_factor, mode, w=None): # warning: all ...
method call (line 462) | def call(self, inputs):
class TFConcat (line 467) | class TFConcat(keras.layers.Layer):
method __init__ (line 470) | def __init__(self, dimension=1, w=None):
method call (line 476) | def call(self, inputs):
function parse_model (line 481) | def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
class TFModel (line 554) | class TFModel:
method __init__ (line 557) | def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, model=None, imgs...
method predict (line 576) | def predict(
method _xywh2xyxy (line 618) | def _xywh2xyxy(xywh):
class AgnosticNMS (line 625) | class AgnosticNMS(keras.layers.Layer):
method call (line 628) | def call(self, input, topk_all, iou_thres, conf_thres):
method _nms (line 638) | def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnosti...
function activations (line 673) | def activations(act=nn.SiLU):
function representative_dataset_gen (line 685) | def representative_dataset_gen(dataset, ncalib=100):
function run (line 698) | def run(
function parse_opt (line 724) | def parse_opt():
function main (line 739) | def main(opt):
FILE: models/yolo.py
class Detect (line 44) | class Detect(nn.Module):
method __init__ (line 51) | def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detecti...
method forward (line 64) | def forward(self, x):
method _make_grid (line 93) | def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch...
class Segment (line 106) | class Segment(Detect):
method __init__ (line 109) | def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=T...
method forward (line 121) | def forward(self, x):
class BaseModel (line 130) | class BaseModel(nn.Module):
method forward (line 133) | def forward(self, x, profile=False, visualize=False):
method _forward_once (line 139) | def _forward_once(self, x, profile=False, visualize=False):
method _profile_one_layer (line 153) | def _profile_one_layer(self, m, x, dt):
method fuse (line 167) | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
method info (line 178) | def info(self, verbose=False, img_size=640): # print model information
method _apply (line 182) | def _apply(self, fn):
class DetectionModel (line 194) | class DetectionModel(BaseModel):
method __init__ (line 197) | def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, anchors=None): ...
method forward (line 242) | def forward(self, x, augment=False, profile=False, visualize=False):
method _forward_augment (line 248) | def _forward_augment(self, x):
method _descale_pred (line 263) | def _descale_pred(self, p, flips, scale, img_size):
method _clip_augmented (line 280) | def _clip_augmented(self, y):
method _initialize_biases (line 291) | def _initialize_biases(self, cf=None): # initialize biases into Detec...
class SegmentationModel (line 307) | class SegmentationModel(DetectionModel):
method __init__ (line 310) | def __init__(self, cfg="yolov5s-seg.yaml", ch=3, nc=None, anchors=None):
class ClassificationModel (line 315) | class ClassificationModel(BaseModel):
method __init__ (line 318) | def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml,...
method _from_detection_model (line 323) | def _from_detection_model(self, model, nc=1000, cutoff=10):
method _from_yaml (line 338) | def _from_yaml(self, cfg):
function parse_model (line 343) | def parse_model(d, ch): # model_dict, input_channels(3)
FILE: segment/predict.py
function run (line 70) | def run(
function parse_opt (line 260) | def parse_opt():
function main (line 297) | def main(opt):
FILE: segment/train.py
function train (line 100) | def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hy...
function parse_opt (line 543) | def parse_opt(known=False):
function main (line 588) | def main(opt, callbacks=Callbacks()):
function run (line 747) | def run(**kwargs):
FILE: segment/val.py
function save_one_txt (line 73) | def save_one_txt(predn, save_conf, shape, file):
function save_one_json (line 83) | def save_one_json(predn, jdict, path, class_map, pred_masks):
function process_batch (line 111) | def process_batch(detections, labels, iouv, pred_masks=None, gt_masks=No...
function run (line 149) | def run(
function parse_opt (line 441) | def parse_opt():
function main (line 474) | def main(opt):
FILE: train.py
function train (line 105) | def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hy...
function parse_opt (line 544) | def parse_opt(known=False):
function main (line 613) | def main(opt, callbacks=Callbacks()):
function run (line 810) | def run(**kwargs):
FILE: utils/__init__.py
function emojis (line 9) | def emojis(str=""):
class TryExcept (line 14) | class TryExcept(contextlib.ContextDecorator):
method __init__ (line 17) | def __init__(self, msg=""):
method __enter__ (line 23) | def __enter__(self):
method __exit__ (line 29) | def __exit__(self, exc_type, value, traceback):
function threaded (line 38) | def threaded(func):
function join_threads (line 56) | def join_threads(verbose=False):
function notebook_init (line 66) | def notebook_init(verbose=True):
FILE: utils/activations.py
class SiLU (line 9) | class SiLU(nn.Module):
method forward (line 13) | def forward(x):
class Hardswish (line 20) | class Hardswish(nn.Module):
method forward (line 24) | def forward(x):
class Mish (line 31) | class Mish(nn.Module):
method forward (line 35) | def forward(x):
class MemoryEfficientMish (line 43) | class MemoryEfficientMish(nn.Module):
class F (line 46) | class F(torch.autograd.Function):
method forward (line 50) | def forward(ctx, x):
method backward (line 58) | def backward(ctx, grad_output):
method forward (line 67) | def forward(self, x):
class FReLU (line 72) | class FReLU(nn.Module):
method __init__ (line 75) | def __init__(self, c1, k=3): # ch_in, kernel
method forward (line 83) | def forward(self, x):
class AconC (line 88) | class AconC(nn.Module):
method __init__ (line 93) | def __init__(self, c1):
method forward (line 102) | def forward(self, x):
class MetaAconC (line 109) | class MetaAconC(nn.Module):
method __init__ (line 115) | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
method forward (line 128) | def forward(self, x):
FILE: utils/augmentations.py
class Albumentations (line 20) | class Albumentations:
method __init__ (line 23) | def __init__(self, size=640):
method __call__ (line 50) | def __call__(self, im, labels, p=1.0):
function normalize (line 58) | def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
function denormalize (line 63) | def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
function augment_hsv (line 73) | def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
function hist_equalize (line 92) | def hist_equalize(im, clahe=True, bgr=False):
function replicate (line 103) | def replicate(im, labels):
function letterbox (line 120) | def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True...
function random_perspective (line 153) | def random_perspective(
function copy_paste (line 235) | def copy_paste(im, labels, segments, p=0.5):
function cutout (line 259) | def cutout(im, labels, p=0.5):
function mixup (line 286) | def mixup(im, labels, im2, labels2):
function box_candidates (line 295) | def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1...
function classify_albumentations (line 303) | def classify_albumentations(
function classify_transforms (line 348) | def classify_transforms(size=224):
class LetterBox (line 355) | class LetterBox:
method __init__ (line 358) | def __init__(self, size=(640, 640), auto=False, stride=32):
method __call__ (line 367) | def __call__(self, im): # im = np.array HWC
class CenterCrop (line 381) | class CenterCrop:
method __init__ (line 384) | def __init__(self, size=640):
method __call__ (line 389) | def __call__(self, im): # im = np.array HWC
class ToTensor (line 397) | class ToTensor:
method __init__ (line 400) | def __init__(self, half=False):
method __call__ (line 407) | def __call__(self, im): # im = np.array HWC in BGR order
FILE: utils/autoanchor.py
function check_anchor_order (line 17) | def check_anchor_order(m):
function check_anchors (line 28) | def check_anchors(dataset, model, thr=4.0, imgsz=640):
function kmean_anchors (line 67) | def kmean_anchors(dataset="./data/coco128.yaml", n=9, img_size=640, thr=...
FILE: utils/autobatch.py
function check_train_batch_size (line 13) | def check_train_batch_size(model, imgsz=640, amp=True):
function autobatch (line 19) | def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
FILE: utils/callbacks.py
class Callbacks (line 7) | class Callbacks:
method __init__ (line 10) | def __init__(self):
method register_action (line 35) | def register_action(self, hook, name="", callback=None):
method get_registered_actions (line 47) | def get_registered_actions(self, hook=None):
method run (line 55) | def run(self, hook, *args, thread=False, **kwargs):
FILE: utils/dataloaders.py
function get_hash (line 74) | def get_hash(paths):
function exif_size (line 82) | def exif_size(img):
function exif_transpose (line 92) | def exif_transpose(image):
function seed_worker (line 119) | def seed_worker(worker_id):
function create_dataloader (line 126) | def create_dataloader(
class InfiniteDataLoader (line 185) | class InfiniteDataLoader(dataloader.DataLoader):
method __init__ (line 191) | def __init__(self, *args, **kwargs):
method __len__ (line 199) | def __len__(self):
method __iter__ (line 203) | def __iter__(self):
class _RepeatSampler (line 209) | class _RepeatSampler:
method __init__ (line 216) | def __init__(self, sampler):
method __iter__ (line 220) | def __iter__(self):
class LoadScreenshots (line 226) | class LoadScreenshots:
method __init__ (line 229) | def __init__(self, source, img_size=640, stride=32, auto=True, transfo...
method __iter__ (line 260) | def __iter__(self):
method __next__ (line 264) | def __next__(self):
class LoadImages (line 279) | class LoadImages:
method __init__ (line 282) | def __init__(self, path, img_size=640, stride=32, auto=True, transform...
method __iter__ (line 321) | def __iter__(self):
method __next__ (line 326) | def __next__(self):
method _new_video (line 367) | def _new_video(self, path):
method _cv2_rotate (line 375) | def _cv2_rotate(self, im):
method __len__ (line 385) | def __len__(self):
class LoadStreams (line 390) | class LoadStreams:
method __init__ (line 393) | def __init__(self, sources="file.streams", img_size=640, stride=32, au...
method update (line 441) | def update(self, i, cap, stream):
method __iter__ (line 459) | def __iter__(self):
method __next__ (line 464) | def __next__(self):
method __len__ (line 481) | def __len__(self):
function img2label_paths (line 486) | def img2label_paths(img_paths):
class LoadImagesAndLabels (line 493) | class LoadImagesAndLabels(Dataset):
method __init__ (line 499) | def __init__(
method check_cache_ram (line 653) | def check_cache_ram(self, safety_margin=0.1, prefix=""):
method cache_labels (line 672) | def cache_labels(self, path=Path("./labels.cache"), prefix=""):
method __len__ (line 712) | def __len__(self):
method __getitem__ (line 722) | def __getitem__(self, index):
method load_image (line 800) | def load_image(self, i):
method cache_images_to_disk (line 821) | def cache_images_to_disk(self, i):
method load_mosaic (line 827) | def load_mosaic(self, index):
method load_mosaic9 (line 888) | def load_mosaic9(self, index):
method collate_fn (line 968) | def collate_fn(batch):
method collate_fn4 (line 976) | def collate_fn4(batch):
function flatten_recursive (line 1005) | def flatten_recursive(path=DATASETS_DIR / "coco128"):
function extract_boxes (line 1015) | def extract_boxes(path=DATASETS_DIR / "coco128"): # from utils.dataload...
function autosplit (line 1051) | def autosplit(path=DATASETS_DIR / "coco128/images", weights=(0.9, 0.1, 0...
function verify_image_label (line 1078) | def verify_image_label(args):
class HUBDatasetStats (line 1129) | class HUBDatasetStats:
method __init__ (line 1144) | def __init__(self, path="coco128.yaml", autodownload=False):
method _find_yaml (line 1163) | def _find_yaml(dir):
method _unzip (line 1173) | def _unzip(self, path):
method _hub_ops (line 1185) | def _hub_ops(self, f, max_dim=1920):
method get_json (line 1205) | def get_json(self, save=False, verbose=False):
method process_images (line 1245) | def process_images(self):
class ClassificationDataset (line 1261) | class ClassificationDataset(torchvision.datasets.ImageFolder):
method __init__ (line 1270) | def __init__(self, root, augment, imgsz, cache=False):
method __getitem__ (line 1281) | def __getitem__(self, i):
function create_classification_dataloader (line 1299) | def create_classification_dataloader(
FILE: utils/downloads.py
function is_url (line 13) | def is_url(url, check=True):
function gsutil_getsize (line 24) | def gsutil_getsize(url=""):
function url_getsize (line 30) | def url_getsize(url="https://ultralytics.com/images/bus.jpg"):
function curl_download (line 36) | def curl_download(url, filename, *, silent: bool = False) -> bool:
function safe_download (line 56) | def safe_download(file, url, url2=None, min_bytes=1e0, error_msg=""):
function attempt_download (line 80) | def attempt_download(file, repo="ultralytics/yolov5", release="v7.0"):
FILE: utils/flask_rest_api/restapi.py
function predict (line 18) | def predict(model):
FILE: utils/general.py
function is_ascii (line 65) | def is_ascii(s=""):
function is_chinese (line 71) | def is_chinese(s="人工智能"):
function is_colab (line 76) | def is_colab():
function is_jupyter (line 81) | def is_jupyter():
function is_kaggle (line 95) | def is_kaggle():
function is_docker (line 100) | def is_docker() -> bool:
function is_writeable (line 111) | def is_writeable(dir, test=False):
function set_logging (line 128) | def set_logging(name=LOGGING_NAME, verbose=True):
function user_config_dir (line 162) | def user_config_dir(dir="Ultralytics", env_var="YOLOV5_CONFIG_DIR"):
class Profile (line 179) | class Profile(contextlib.ContextDecorator):
method __init__ (line 182) | def __init__(self, t=0.0):
method __enter__ (line 188) | def __enter__(self):
method __exit__ (line 195) | def __exit__(self, type, value, traceback):
method time (line 200) | def time(self):
class Timeout (line 207) | class Timeout(contextlib.ContextDecorator):
method __init__ (line 210) | def __init__(self, seconds, *, timeout_msg="", suppress_timeout_errors...
method _timeout_handler (line 217) | def _timeout_handler(self, signum, frame):
method __enter__ (line 221) | def __enter__(self):
method __exit__ (line 227) | def __exit__(self, exc_type, exc_val, exc_tb):
class WorkingDirectory (line 235) | class WorkingDirectory(contextlib.ContextDecorator):
method __init__ (line 238) | def __init__(self, new_dir):
method __enter__ (line 243) | def __enter__(self):
method __exit__ (line 247) | def __exit__(self, exc_type, exc_val, exc_tb):
function methods (line 252) | def methods(instance):
function print_args (line 257) | def print_args(args: dict | None = None, show_file=True, show_func=False):
function init_seeds (line 272) | def init_seeds(seed=0, deterministic=False):
function intersect_dicts (line 289) | def intersect_dicts(da, db, exclude=()):
function get_default_args (line 296) | def get_default_args(func):
function get_latest_run (line 302) | def get_latest_run(search_dir="."):
function file_age (line 309) | def file_age(path=__file__):
function file_date (line 315) | def file_date(path=__file__):
function file_size (line 321) | def file_size(path):
function check_online (line 333) | def check_online():
function git_describe (line 349) | def git_describe(path=ROOT): # path must be a directory
function check_git_status (line 360) | def check_git_status(repo="ultralytics/yolov5", branch="master"):
function check_git_info (line 389) | def check_git_info(path="."):
function check_python (line 410) | def check_python(minimum="3.7.0"):
function check_version (line 415) | def check_version(current="0.0.0", minimum="0.0.0", name="version ", pin...
function check_img_size (line 427) | def check_img_size(imgsz, s=32, floor=0):
function check_imshow (line 441) | def check_imshow(warn=False):
function check_suffix (line 457) | def check_suffix(file="yolov5s.pt", suffix=(".pt",), msg=""):
function check_yaml (line 468) | def check_yaml(file, suffix=(".yaml", ".yml")):
function check_file (line 473) | def check_file(file, suffix=""):
function check_font (line 505) | def check_font(font=FONT, progress=False):
function check_dataset (line 515) | def check_dataset(data, autodownload=True):
function check_amp (line 580) | def check_amp(model):
function yaml_load (line 608) | def yaml_load(file="data.yaml"):
function yaml_save (line 614) | def yaml_save(file="data.yaml", data=None):
function unzip_file (line 622) | def unzip_file(file, path=None, exclude=(".DS_Store", "__MACOSX")):
function url2file (line 634) | def url2file(url):
function download (line 640) | def download(url, dir=".", unzip=True, delete=True, curl=False, threads=...
function make_divisible (line 689) | def make_divisible(x, divisor):
function clean_str (line 696) | def clean_str(s):
function one_cycle (line 701) | def one_cycle(y1=0.0, y2=1.0, steps=100):
function colorstr (line 708) | def colorstr(*input):
function labels_to_class_weights (line 738) | def labels_to_class_weights(labels, nc=80):
function labels_to_image_weights (line 759) | def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
function coco80_to_coco91_class (line 766) | def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index...
function xyxy2xywh (line 859) | def xyxy2xywh(x):
function xywh2xyxy (line 869) | def xywh2xyxy(x):
function xywhn2xyxy (line 879) | def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
function xyxy2xywhn (line 889) | def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
function xyn2xy (line 901) | def xyn2xy(x, w=640, h=640, padw=0, padh=0):
function segment2box (line 909) | def segment2box(segment, width=640, height=640):
function segments2boxes (line 922) | def segments2boxes(segments):
function resample_segments (line 931) | def resample_segments(segments, n=1000):
function scale_boxes (line 941) | def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):
function scale_segments (line 957) | def scale_segments(img1_shape, segments, img0_shape, ratio_pad=None, nor...
function clip_boxes (line 978) | def clip_boxes(boxes, shape):
function clip_segments (line 990) | def clip_segments(segments, shape):
function non_max_suppression (line 1000) | def non_max_suppression(
function strip_optimizer (line 1112) | def strip_optimizer(f="best.pt", s=""): # from utils.general import *; ...
function print_mutation (line 1128) | def print_mutation(keys, results, hyp, save_dir, bucket, prefix=colorstr...
function apply_classifier (line 1183) | def apply_classifier(x, model, img, im0):
function increment_path (line 1218) | def increment_path(path, exist_ok=False, sep="", mkdir=False):
function imread (line 1252) | def imread(filename, flags=cv2.IMREAD_COLOR):
function imwrite (line 1257) | def imwrite(filename, img):
function imshow (line 1269) | def imshow(path, im):
FILE: utils/loggers/__init__.py
function SummaryWriter (line 24) | def SummaryWriter(*args):
class Loggers (line 65) | class Loggers:
method __init__ (line 68) | def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, lo...
method remote_dataset (line 145) | def remote_dataset(self):
method on_train_start (line 157) | def on_train_start(self):
method on_pretrain_routine_start (line 162) | def on_pretrain_routine_start(self):
method on_pretrain_routine_end (line 167) | def on_pretrain_routine_end(self, labels, names):
method on_train_batch_end (line 182) | def on_train_batch_end(self, model, ni, imgs, targets, paths, vals):
method on_train_epoch_end (line 203) | def on_train_epoch_end(self, epoch):
method on_val_start (line 211) | def on_val_start(self):
method on_val_image_end (line 216) | def on_val_image_end(self, pred, predn, path, names, im):
method on_val_batch_end (line 225) | def on_val_batch_end(self, batch_i, im, targets, paths, shapes, out):
method on_val_end (line 233) | def on_val_end(self, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusi...
method on_fit_epoch_end (line 245) | def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
method on_model_save (line 278) | def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
method on_train_end (line 292) | def on_train_end(self, last, best, epoch, results):
method on_params_update (line 328) | def on_params_update(self, params: dict):
class GenericLogger (line 336) | class GenericLogger:
method __init__ (line 346) | def __init__(self, opt, console_logger, include=("tb", "wandb")):
method log_metrics (line 366) | def log_metrics(self, metrics, epoch):
method log_images (line 382) | def log_images(self, files, name="Images", epoch=0):
method log_graph (line 394) | def log_graph(self, model, imgsz=(640, 640)):
method log_model (line 399) | def log_model(self, model_path, epoch=0, metadata=None):
method update_params (line 408) | def update_params(self, params):
function log_tensorboard_graph (line 414) | def log_tensorboard_graph(tb, model, imgsz=(640, 640)):
function web_project_name (line 427) | def web_project_name(project):
FILE: utils/loggers/clearml/clearml_utils.py
function construct_dataset (line 21) | def construct_dataset(clearml_info_string):
class ClearmlLogger (line 63) | class ClearmlLogger:
method __init__ (line 73) | def __init__(self, opt, hyp):
method log_debug_samples (line 122) | def log_debug_samples(self, files, title="Debug Samples"):
method log_image_with_boxes (line 137) | def log_image_with_boxes(self, image_path, boxes, class_names, image, ...
FILE: utils/loggers/comet/__init__.py
class CometLogger (line 66) | class CometLogger:
method __init__ (line 69) | def __init__(self, opt, hyp, run_id=None, job_type="Training", **exper...
method _get_experiment (line 168) | def _get_experiment(self, mode, experiment_id=None):
method log_metrics (line 203) | def log_metrics(self, log_dict, **kwargs):
method log_parameters (line 207) | def log_parameters(self, log_dict, **kwargs):
method log_asset (line 211) | def log_asset(self, asset_path, **kwargs):
method log_asset_data (line 215) | def log_asset_data(self, asset, **kwargs):
method log_image (line 219) | def log_image(self, img, **kwargs):
method log_model (line 223) | def log_model(self, path, opt, epoch, fitness_score, best_model=False):
method check_dataset (line 249) | def check_dataset(self, data_file):
method log_predictions (line 262) | def log_predictions(self, image, labelsn, path, shape, predn):
method preprocess_prediction (line 303) | def preprocess_prediction(self, image, labels, shape, pred):
method add_assets_to_artifact (line 325) | def add_assets_to_artifact(self, artifact, path, asset_path, split):
method upload_dataset_artifact (line 351) | def upload_dataset_artifact(self):
method download_dataset_artifact (line 376) | def download_dataset_artifact(self, artifact_path):
method update_data_paths (line 396) | def update_data_paths(self, data_dict):
method on_pretrain_routine_end (line 409) | def on_pretrain_routine_end(self, paths):
method on_train_start (line 422) | def on_train_start(self):
method on_train_epoch_start (line 426) | def on_train_epoch_start(self):
method on_train_epoch_end (line 430) | def on_train_epoch_end(self, epoch):
method on_train_batch_start (line 436) | def on_train_batch_start(self):
method on_train_batch_end (line 440) | def on_train_batch_end(self, log_dict, step):
method on_train_end (line 448) | def on_train_end(self, files, save_dir, last, best, epoch, results):
method on_val_start (line 476) | def on_val_start(self):
method on_val_batch_start (line 480) | def on_val_batch_start(self):
method on_val_batch_end (line 484) | def on_val_batch_end(self, batch_i, images, targets, paths, shapes, ou...
method on_val_end (line 503) | def on_val_end(self, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusi...
method on_fit_epoch_end (line 540) | def on_fit_epoch_end(self, result, epoch):
method on_model_save (line 544) | def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
method on_params_update (line 549) | def on_params_update(self, params):
method finish_run (line 553) | def finish_run(self):
FILE: utils/loggers/comet/comet_utils.py
function download_model_checkpoint (line 21) | def download_model_checkpoint(opt, experiment):
function set_opt_parameters (line 69) | def set_opt_parameters(opt, experiment):
function check_comet_weights (line 99) | def check_comet_weights(opt):
function check_comet_resume (line 122) | def check_comet_resume(opt):
FILE: utils/loggers/comet/hpo.py
function get_args (line 29) | def get_args(known=False):
function run (line 88) | def run(parameters, opt):
FILE: utils/loggers/wandb/wandb_utils.py
class WandbLogger (line 33) | class WandbLogger:
method __init__ (line 45) | def __init__(self, opt, run_id=None, job_type="Training"):
method setup_training (line 81) | def setup_training(self, opt):
method log_model (line 112) | def log_model(self, path, opt, epoch, fitness_score, best_model=False):
method val_one_image (line 144) | def val_one_image(self, pred, predn, path, names, im):
method log (line 148) | def log(self, log_dict):
method end_epoch (line 158) | def end_epoch(self):
method finish_run (line 176) | def finish_run(self):
function all_logging_disabled (line 187) | def all_logging_disabled(highest_level=logging.CRITICAL):
FILE: utils/loss.py
function smooth_BCE (line 11) | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues...
class BCEBlurWithLogitsLoss (line 16) | class BCEBlurWithLogitsLoss(nn.Module):
method __init__ (line 19) | def __init__(self, alpha=0.05):
method forward (line 25) | def forward(self, pred, true):
class FocalLoss (line 38) | class FocalLoss(nn.Module):
method __init__ (line 41) | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
method forward (line 52) | def forward(self, pred, true):
class QFocalLoss (line 75) | class QFocalLoss(nn.Module):
method __init__ (line 78) | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
method forward (line 89) | def forward(self, pred, true):
class ComputeLoss (line 107) | class ComputeLoss:
method __init__ (line 113) | def __init__(self, model, autobalance=False):
method __call__ (line 140) | def __call__(self, p, targets): # predictions, targets
method build_targets (line 192) | def build_targets(self, p, targets):
FILE: utils/metrics.py
function fitness (line 15) | def fitness(x):
function smooth (line 21) | def smooth(y, f=0.05):
function ap_per_class (line 29) | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir="....
function compute_ap (line 95) | def compute_ap(recall, precision):
class ConfusionMatrix (line 118) | class ConfusionMatrix:
method __init__ (line 121) | def __init__(self, nc, conf=0.25, iou_thres=0.45):
method process_batch (line 128) | def process_batch(self, detections, labels):
method tp_fp (line 175) | def tp_fp(self):
method plot (line 183) | def plot(self, normalize=True, save_dir="", names=()):
method print (line 215) | def print(self):
function bbox_iou (line 221) | def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, ...
function box_iou (line 262) | def box_iou(box1, box2, eps=1e-7):
function bbox_ioa (line 282) | def bbox_ioa(box1, box2, eps=1e-7):
function wh_iou (line 303) | def wh_iou(wh1, wh2, eps=1e-7):
function plot_pr_curve (line 315) | def plot_pr_curve(px, py, ap, save_dir=Path("pr_curve.png"), names=()):
function plot_mc_curve (line 340) | def plot_mc_curve(px, py, save_dir=Path("mc_curve.png"), names=(), xlabe...
FILE: utils/plots.py
class Colors (line 31) | class Colors:
method __init__ (line 34) | def __init__(self):
method __call__ (line 61) | def __call__(self, i, bgr=False):
method hex2rgb (line 67) | def hex2rgb(h): # rgb order (PIL)
function feature_visualization (line 75) | def feature_visualization(x, module_type, stage, n=32, save_dir=Path("ru...
function hist2d (line 99) | def hist2d(x, y, n=100):
function butter_lowpass_filtfilt (line 108) | def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
function output_to_target (line 128) | def output_to_target(output, max_det=300):
function plot_images (line 141) | def plot_images(images, targets, paths=None, fname="images.jpg", names=N...
function plot_lr_scheduler (line 205) | def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=""):
function plot_val_txt (line 222) | def plot_val_txt(): # from utils.plots import *; plot_val()
function plot_targets_txt (line 239) | def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
function plot_val_study (line 252) | def plot_val_study(file="", dir="", x=None): # from utils.plots import ...
function plot_labels (line 303) | def plot_labels(labels, names=(), save_dir=Path("")):
function imshow_cls (line 348) | def imshow_cls(im, labels=None, pred=None, names=None, nmax=25, verbose=...
function plot_evolve (line 378) | def plot_evolve(evolve_csv="path/to/evolve.csv"): # from utils.plots im...
function plot_results (line 405) | def plot_results(file="path/to/results.csv", dir=""):
function profile_idetection (line 432) | def profile_idetection(start=0, stop=0, labels=(), save_dir=""):
function save_one_box (line 465) | def save_one_box(xyxy, im, file=Path("im.jpg"), gain=1.02, pad=10, squar...
FILE: utils/segment/augmentations.py
function mixup (line 14) | def mixup(im, labels, segments, im2, labels2, segments2):
function random_perspective (line 25) | def random_perspective(
FILE: utils/segment/dataloaders.py
function create_dataloader (line 21) | def create_dataloader(
class LoadImagesAndLabelsAndMasks (line 84) | class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels): # for training/...
method __init__ (line 87) | def __init__(
method __getitem__ (line 124) | def __getitem__(self, index):
method load_mosaic (line 231) | def load_mosaic(self, index):
method collate_fn (line 294) | def collate_fn(batch):
function polygon2mask (line 303) | def polygon2mask(img_size, polygons, color=1, downsample_ratio=1):
function polygons2masks (line 322) | def polygons2masks(img_size, polygons, color, downsample_ratio=1):
function polygons2masks_overlap (line 336) | def polygons2masks_overlap(img_size, segments, downsample_ratio=1):
FILE: utils/segment/general.py
function crop_mask (line 9) | def crop_mask(masks, boxes):
function process_mask_upsample (line 24) | def process_mask_upsample(protos, masks_in, bboxes, shape):
function process_mask (line 37) | def process_mask(protos, masks_in, bboxes, shape, upsample=False):
function process_mask_native (line 59) | def process_mask_native(protos, masks_in, bboxes, shape):
function scale_image (line 78) | def scale_image(im1_shape, masks, im0_shape, ratio_pad=None):
function mask_iou (line 102) | def mask_iou(mask1, mask2, eps=1e-7):
function masks_iou (line 113) | def masks_iou(mask1, mask2, eps=1e-7):
function masks2segments (line 124) | def masks2segments(masks, strategy="largest"):
FILE: utils/segment/loss.py
class ComputeLoss (line 14) | class ComputeLoss:
method __init__ (line 17) | def __init__(self, model, autobalance=False, overlap=False):
method __call__ (line 47) | def __call__(self, preds, targets, masks): # predictions, targets, model
method single_mask_loss (line 117) | def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):
method build_targets (line 126) | def build_targets(self, p, targets):
FILE: utils/segment/metrics.py
function fitness (line 9) | def fitness(x):
function ap_per_class_box_and_mask (line 15) | def ap_per_class_box_and_mask(
class Metric (line 56) | class Metric:
method __init__ (line 59) | def __init__(self) -> None:
method ap50 (line 68) | def ap50(self):
method ap (line 77) | def ap(self):
method mp (line 86) | def mp(self):
method mr (line 95) | def mr(self):
method map50 (line 104) | def map50(self):
method map (line 113) | def map(self):
method mean_results (line 121) | def mean_results(self):
method class_result (line 125) | def class_result(self, i):
method get_maps (line 129) | def get_maps(self, nc):
method update (line 138) | def update(self, results):
class Metrics (line 151) | class Metrics:
method __init__ (line 154) | def __init__(self) -> None:
method update (line 159) | def update(self, results):
method mean_results (line 167) | def mean_results(self):
method class_result (line 171) | def class_result(self, i):
method get_maps (line 175) | def get_maps(self, nc):
method ap_class_index (line 180) | def ap_class_index(self):
FILE: utils/segment/plots.py
function plot_images_and_masks (line 19) | def plot_images_and_masks(images, targets, masks, paths=None, fname="ima...
function plot_results_with_masks (line 115) | def plot_results_with_masks(file="path/to/results.csv", dir="", best=True):
FILE: utils/torch_utils.py
function smart_inference_mode (line 36) | def smart_inference_mode(torch_1_9=check_version(torch.__version__, "1.9...
function smartCrossEntropyLoss (line 46) | def smartCrossEntropyLoss(label_smoothing=0.0):
function smart_DDP (line 57) | def smart_DDP(model):
function reshape_classifier_output (line 72) | def reshape_classifier_output(model, n=1000):
function torch_distributed_zero_first (line 98) | def torch_distributed_zero_first(local_rank: int):
function device_count (line 107) | def device_count():
function select_device (line 117) | def select_device(device="", batch_size=0, newline=True):
function time_sync (line 154) | def time_sync():
function profile (line 161) | def profile(input, ops, n=10, device=None):
function is_parallel (line 215) | def is_parallel(model):
function de_parallel (line 220) | def de_parallel(model):
function initialize_weights (line 225) | def initialize_weights(model):
function find_modules (line 240) | def find_modules(model, mclass=nn.Conv2d):
function sparsity (line 245) | def sparsity(model):
function prune (line 255) | def prune(model, amount=0.3):
function fuse_conv_and_bn (line 266) | def fuse_conv_and_bn(conv, bn):
function model_info (line 296) | def model_info(model, verbose=False, imgsz=640):
function scale_img (line 326) | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,...
function copy_attr (line 340) | def copy_attr(a, b, include=(), exclude=()):
function smart_optimizer (line 349) | def smart_optimizer(model, name="Adam", lr=0.001, momentum=0.9, decay=1e...
function smart_hub_load (line 382) | def smart_hub_load(repo="ultralytics/yolov5", model="yolov5s", **kwargs):
function smart_resume (line 397) | def smart_resume(ckpt, optimizer, ema=None, weights="yolov5s.pt", epochs...
class EarlyStopping (line 421) | class EarlyStopping:
method __init__ (line 424) | def __init__(self, patience=30):
method __call__ (line 433) | def __call__(self, epoch, fitness):
class ModelEMA (line 451) | class ModelEMA:
method __init__ (line 457) | def __init__(self, model, decay=0.9999, tau=2000, updates=0):
method update (line 467) | def update(self, model):
method update_attr (line 479) | def update_attr(self, model, include=(), exclude=("process_group", "re...
FILE: utils/triton.py
class TritonRemoteModel (line 11) | class TritonRemoteModel:
method __init__ (line 18) | def __init__(self, url: str):
method runtime (line 50) | def runtime(self):
method __call__ (line 54) | def __call__(self, *args, **kwargs) -> torch.Tensor | tuple[torch.Tens...
method _create_inputs (line 68) | def _create_inputs(self, *args, **kwargs):
FILE: val.py
function save_one_txt (line 64) | def save_one_txt(predn, save_conf, shape, file):
function save_one_json (line 106) | def save_one_json(predn, jdict, path, class_map):
function process_batch (line 147) | def process_batch(detections, labels, iouv):
function run (line 192) | def run(
function parse_opt (line 489) | def parse_opt():
function main (line 562) | def main(opt):
Condensed preview — 136 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,287K chars).
[
{
"path": ".dockerignore",
"chars": 3701,
"preview": "# Repo-specific DockerIgnore -------------------------------------------------------------------------------------------"
},
{
"path": ".github/ISSUE_TEMPLATE/bug-report.yml",
"chars": 3015,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nname: 🐛 Bug Report\ndescription: \"Problems with Ultra"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 594,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nblank_issues_enabled: true\ncontact_links:\n - name: "
},
{
"path": ".github/ISSUE_TEMPLATE/feature-request.yml",
"chars": 1876,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nname: 🚀 Feature Request\ndescription: \"Suggest an Ult"
},
{
"path": ".github/ISSUE_TEMPLATE/question.yml",
"chars": 1351,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nname: ❓ Question\ndescription: \"Ask an Ultralytics YO"
},
{
"path": ".github/dependabot.yml",
"chars": 601,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Dependabot for package version updates\n# https://d"
},
{
"path": ".github/workflows/ci-testing.yml",
"chars": 5636,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# YOLOv3 Continuous Integration (CI) GitHub Actions "
},
{
"path": ".github/workflows/cla.yml",
"chars": 1627,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Ultralytics Contributor License Agreement (CLA) ac"
},
{
"path": ".github/workflows/docker.yml",
"chars": 1644,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Builds ultralytics/yolov3:latest images on DockerH"
},
{
"path": ".github/workflows/format.yml",
"chars": 1316,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Ultralytics Actions https://github.com/ultralytics"
},
{
"path": ".github/workflows/links.yml",
"chars": 3106,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Continuous Integration (CI) GitHub Actions tests b"
},
{
"path": ".github/workflows/merge-main-into-prs.yml",
"chars": 3172,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Automatically merges repository 'main' branch into"
},
{
"path": ".github/workflows/stale.yml",
"chars": 2460,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nname: Close stale issues\n\npermissions:\n contents: r"
},
{
"path": ".gitignore",
"chars": 3998,
"preview": "# Repo-specific GitIgnore ----------------------------------------------------------------------------------------------"
},
{
"path": "CITATION.cff",
"chars": 399,
"preview": "cff-version: 1.2.0\npreferred-citation:\n type: software\n message: If you use YOLOv5, please cite it as below.\n authors"
},
{
"path": "CONTRIBUTING.md",
"chars": 4680,
"preview": "# Contributing To YOLOv3 🚀\n\nWe value your input and welcome your contributions to Ultralytics YOLOv3! Whether you're int"
},
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 24456,
"preview": "<div align=\"center\">\n <p>\n <a href=\"https://platform.ultralytics.com/?utm_source=github&utm_medium=referral&utm_camp"
},
{
"path": "README.zh-CN.md",
"chars": 19383,
"preview": "<a href=\"https://www.ultralytics.com/\"><img src=\"https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralyt"
},
{
"path": "benchmarks.py",
"chars": 14039,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nRun YOLOv3 benchmarks on all supported export for"
},
{
"path": "classify/predict.py",
"chars": 12077,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nRun YOLOv3 classification inference on images, vi"
},
{
"path": "classify/train.py",
"chars": 16368,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nTrain a YOLOv3 classifier model on a classificati"
},
{
"path": "classify/tutorial.ipynb",
"chars": 97652,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"id\": \"t6MPjfT5NrKQ\"\n },\n \"source\": [\n \"<div a"
},
{
"path": "classify/val.py",
"chars": 8216,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nValidate a trained YOLOv3 classification model on"
},
{
"path": "data/Argoverse.yaml",
"chars": 2729,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Argoverse-HD dataset (ring-front-center camera) ht"
},
{
"path": "data/GlobalWheat2020.yaml",
"chars": 1886,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Global Wheat 2020 dataset http://www.global-wheat."
},
{
"path": "data/ImageNet.yaml",
"chars": 18866,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# ImageNet-1k dataset https://www.image-net.org/inde"
},
{
"path": "data/SKU-110K.yaml",
"chars": 2337,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# SKU-110K retail items dataset https://github.com/e"
},
{
"path": "data/VisDrone.yaml",
"chars": 2975,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# VisDrone2019-DET dataset https://github.com/VisDro"
},
{
"path": "data/coco.yaml",
"chars": 2493,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# COCO 2017 dataset http://cocodataset.org by Micros"
},
{
"path": "data/coco128-seg.yaml",
"chars": 1905,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# COCO128-seg dataset https://www.kaggle.com/dataset"
},
{
"path": "data/coco128.yaml",
"chars": 1889,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# COCO128 dataset https://www.kaggle.com/datasets/ul"
},
{
"path": "data/hyps/hyp.Objects365.yaml",
"chars": 695,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Hyperparameters for Objects365 training\n# python t"
},
{
"path": "data/hyps/hyp.VOC.yaml",
"chars": 1178,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Hyperparameters for VOC training\n# python train.py"
},
{
"path": "data/hyps/hyp.no-augmentation.yaml",
"chars": 1677,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Hyperparameters when using Albumentations framewor"
},
{
"path": "data/hyps/hyp.scratch-high.yaml",
"chars": 1677,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Hyperparameters for high-augmentation COCO trainin"
},
{
"path": "data/hyps/hyp.scratch-low.yaml",
"chars": 1685,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Hyperparameters for low-augmentation COCO training"
},
{
"path": "data/hyps/hyp.scratch-med.yaml",
"chars": 1679,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Hyperparameters for medium-augmentation COCO train"
},
{
"path": "data/objects365.yaml",
"chars": 9200,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Objects365 dataset https://www.objects365.org/ by "
},
{
"path": "data/scripts/download_weights.sh",
"chars": 637,
"preview": "#!/bin/bash\n# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Download latest models from https://gi"
},
{
"path": "data/scripts/get_coco.sh",
"chars": 1576,
"preview": "#!/bin/bash\n# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Download COCO 2017 dataset http://coco"
},
{
"path": "data/scripts/get_coco128.sh",
"chars": 620,
"preview": "#!/bin/bash\n# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Download COCO128 dataset https://www.k"
},
{
"path": "data/scripts/get_imagenet.sh",
"chars": 1677,
"preview": "#!/bin/bash\n# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Download ILSVRC2012 ImageNet dataset h"
},
{
"path": "data/voc.yaml",
"chars": 3495,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# PASCAL VOC dataset http://host.robots.ox.ac.uk/pas"
},
{
"path": "data/xView.yaml",
"chars": 5167,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# DIUx xView 2018 Challenge https://challenge.xviewd"
},
{
"path": "detect.py",
"chars": 23118,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nRun YOLOv3 detection inference on images, videos,"
},
{
"path": "export.py",
"chars": 69445,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nExport a YOLOv3 PyTorch model to other formats. T"
},
{
"path": "hubconf.py",
"chars": 22256,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nPyTorch Hub models https://pytorch.org/hub/ultral"
},
{
"path": "models/__init__.py",
"chars": 67,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n"
},
{
"path": "models/common.py",
"chars": 51000,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Common modules.\"\"\"\n\nimport ast\nimport contextlib\ni"
},
{
"path": "models/experimental.py",
"chars": 5360,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Experimental modules.\"\"\"\n\nimport math\n\nimport nump"
},
{
"path": "models/hub/anchors.yaml",
"chars": 3360,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Default anchors for COCO data\n\n# P5 --------------"
},
{
"path": "models/hub/yolov5-bifpn.yaml",
"chars": 1463,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5-fpn.yaml",
"chars": 1252,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5-p2.yaml",
"chars": 1723,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5-p34.yaml",
"chars": 1263,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5-p6.yaml",
"chars": 1778,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5-p7.yaml",
"chars": 2163,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5-panet.yaml",
"chars": 1447,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5l6.yaml",
"chars": 1858,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5m6.yaml",
"chars": 1860,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5n6.yaml",
"chars": 1860,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5s-LeakyReLU.yaml",
"chars": 1536,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\nactivation: "
},
{
"path": "models/hub/yolov5s-ghost.yaml",
"chars": 1523,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5s-transformer.yaml",
"chars": 1480,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5s6.yaml",
"chars": 1860,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/hub/yolov5x6.yaml",
"chars": 1860,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/segment/yolov5l-seg.yaml",
"chars": 1451,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/segment/yolov5m-seg.yaml",
"chars": 1453,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/segment/yolov5n-seg.yaml",
"chars": 1453,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/segment/yolov5s-seg.yaml",
"chars": 1452,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/segment/yolov5x-seg.yaml",
"chars": 1453,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/tf.py",
"chars": 33274,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nTensorFlow, Keras and TFLite versions of YOLOv3\nA"
},
{
"path": "models/yolo.py",
"chars": 20698,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nYOLO-specific modules.\n\nUsage:\n $ python model"
},
{
"path": "models/yolov3-spp.yaml",
"chars": 1612,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov3-tiny.yaml",
"chars": 1269,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov3.yaml",
"chars": 1603,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov5l.yaml",
"chars": 1441,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov5m.yaml",
"chars": 1443,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov5n.yaml",
"chars": 1443,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov5s.yaml",
"chars": 1443,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "models/yolov5x.yaml",
"chars": 1443,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Parameters\nnc: 80 # number of classes\ndepth_multip"
},
{
"path": "pyproject.toml",
"chars": 5376,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Overview:\n# This pyproject.toml file manages the b"
},
{
"path": "requirements.txt",
"chars": 2855,
"preview": "# YOLOv3 requirements\n# Usage: pip install -r requirements.txt\n# Python >= 3.8 recommended\n\n# Base ---------------------"
},
{
"path": "segment/predict.py",
"chars": 16239,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nRun YOLOv3 segmentation inference on images, vide"
},
{
"path": "segment/train.py",
"chars": 35233,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nTrain a YOLOv3 segment model on a segment dataset"
},
{
"path": "segment/tutorial.ipynb",
"chars": 42789,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"id\": \"t6MPjfT5NrKQ\"\n },\n \"source\": [\n \"<div a"
},
{
"path": "segment/val.py",
"chars": 24117,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nValidate a trained YOLOv3 segment model on a segm"
},
{
"path": "train.py",
"chars": 40327,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nTrain a YOLOv3 model on a custom dataset. Models "
},
{
"path": "tutorial.ipynb",
"chars": 41110,
"preview": "{\n \"nbformat\": 4,\n \"nbformat_minor\": 0,\n \"metadata\": {\n \"colab\": {\n \"name\": \"YOLOv5 Tutorial\",\n \"provenance\": []\n "
},
{
"path": "utils/__init__.py",
"chars": 3338,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"utils/initialization.\"\"\"\n\nimport contextlib\nimport"
},
{
"path": "utils/activations.py",
"chars": 5516,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Activation functions.\"\"\"\n\nimport torch\nimport torc"
},
{
"path": "utils/augmentations.py",
"chars": 18399,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Image augmentation functions.\"\"\"\n\nimport math\nimpo"
},
{
"path": "utils/autoanchor.py",
"chars": 7930,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"AutoAnchor utils.\"\"\"\n\nimport random\n\nimport numpy "
},
{
"path": "utils/autobatch.py",
"chars": 3106,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Auto-batch utils.\"\"\"\n\nfrom copy import deepcopy\n\ni"
},
{
"path": "utils/aws/__init__.py",
"chars": 67,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n"
},
{
"path": "utils/aws/mime.sh",
"chars": 843,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# AWS EC2 instance startup 'MIME' script https://aws"
},
{
"path": "utils/aws/resume.py",
"chars": 1315,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Resume all interrupted trainings in yolov5/ dir in"
},
{
"path": "utils/aws/userdata.sh",
"chars": 1316,
"preview": "#!/bin/bash\n# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# AWS EC2 instance startup script https:"
},
{
"path": "utils/callbacks.py",
"chars": 2721,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Callback utils.\"\"\"\n\nimport threading\n\n\nclass Callb"
},
{
"path": "utils/dataloaders.py",
"chars": 58478,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Dataloaders and dataset utils.\"\"\"\n\nimport contextl"
},
{
"path": "utils/docker/Dockerfile",
"chars": 2682,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Builds ultralytics/yolov5:latest image on DockerHu"
},
{
"path": "utils/docker/Dockerfile-arm64",
"chars": 1693,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Builds ultralytics/yolov5:latest-arm64 image on Do"
},
{
"path": "utils/docker/Dockerfile-cpu",
"chars": 1946,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# Builds ultralytics/yolov5:latest-cpu image on Dock"
},
{
"path": "utils/downloads.py",
"chars": 5181,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Download utils.\"\"\"\n\nimport logging\nimport subproce"
},
{
"path": "utils/flask_rest_api/README.md",
"chars": 3874,
"preview": "<a href=\"https://www.ultralytics.com/\"><img src=\"https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralyt"
},
{
"path": "utils/flask_rest_api/example_request.py",
"chars": 388,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Perform test request.\"\"\"\n\nimport pprint\n\nimport re"
},
{
"path": "utils/flask_rest_api/restapi.py",
"chars": 1594,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Run a Flask REST API exposing one or more YOLOv5s "
},
{
"path": "utils/general.py",
"chars": 50889,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"General utils.\"\"\"\n\nfrom __future__ import annotati"
},
{
"path": "utils/google_app_engine/Dockerfile",
"chars": 821,
"preview": "FROM gcr.io/google-appengine/python\n\n# Create a virtualenv for dependencies. This isolates these packages from\n# system-"
},
{
"path": "utils/google_app_engine/additional_requirements.txt",
"chars": 264,
"preview": "# add these requirements in your app on top of the existing ones\npip==26.0\nFlask==3.1.3\ngunicorn==23.0.0\nwerkzeug>=3.0.1"
},
{
"path": "utils/google_app_engine/app.yaml",
"chars": 242,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nruntime: custom\nenv: flex\n\nservice: yolov5app\n\nliven"
},
{
"path": "utils/loggers/__init__.py",
"chars": 18485,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Logging utils.\"\"\"\n\nimport os\nimport warnings\nfrom "
},
{
"path": "utils/loggers/clearml/README.md",
"chars": 12266,
"preview": "<a href=\"https://www.ultralytics.com/\"><img src=\"https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralyt"
},
{
"path": "utils/loggers/clearml/__init__.py",
"chars": 67,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n"
},
{
"path": "utils/loggers/clearml/clearml_utils.py",
"chars": 7760,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Main Logger class for ClearML experiment tracking."
},
{
"path": "utils/loggers/clearml/hpo.py",
"chars": 5314,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nfrom clearml import Task\n\n# Connecting ClearML with "
},
{
"path": "utils/loggers/comet/README.md",
"chars": 11523,
"preview": "<a href=\"https://www.ultralytics.com/\"><img src=\"https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralyt"
},
{
"path": "utils/loggers/comet/__init__.py",
"chars": 21938,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport glob\nimport json\nimport logging\nimport os\nimp"
},
{
"path": "utils/loggers/comet/comet_utils.py",
"chars": 4779,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport logging\nimport os\nfrom urllib.parse import ur"
},
{
"path": "utils/loggers/comet/hpo.py",
"chars": 6945,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport argparse\nimport json\nimport logging\nimport os"
},
{
"path": "utils/loggers/wandb/__init__.py",
"chars": 67,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n"
},
{
"path": "utils/loggers/wandb/wandb_utils.py",
"chars": 8099,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\n# WARNING ⚠️ wandb is deprecated and will be removed"
},
{
"path": "utils/loss.py",
"chars": 11107,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Loss functions.\"\"\"\n\nimport torch\nimport torch.nn a"
},
{
"path": "utils/metrics.py",
"chars": 15384,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Model validation metrics.\"\"\"\n\nimport math\nimport w"
},
{
"path": "utils/plots.py",
"chars": 20194,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Plotting utils.\"\"\"\n\nimport contextlib\nimport math\n"
},
{
"path": "utils/segment/__init__.py",
"chars": 67,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n"
},
{
"path": "utils/segment/augmentations.py",
"chars": 3538,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Image augmentation functions.\"\"\"\n\nimport math\nimpo"
},
{
"path": "utils/segment/dataloaders.py",
"chars": 13585,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Dataloaders.\"\"\"\n\nimport os\nimport random\n\nimport c"
},
{
"path": "utils/segment/general.py",
"chars": 5877,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport cv2\nimport numpy as np\nimport torch\nimport to"
},
{
"path": "utils/segment/loss.py",
"chars": 9249,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.f"
},
{
"path": "utils/segment/metrics.py",
"chars": 5909,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Model validation metrics.\"\"\"\n\nimport numpy as np\n\n"
},
{
"path": "utils/segment/plots.py",
"chars": 6624,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\nimport contextlib\nimport math\nfrom pathlib import Pa"
},
{
"path": "utils/torch_utils.py",
"chars": 21588,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"PyTorch utils.\"\"\"\n\nimport math\nimport os\nimport pl"
},
{
"path": "utils/triton.py",
"chars": 3783,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"Utils to interact with the Triton Inference Server"
},
{
"path": "val.py",
"chars": 30624,
"preview": "# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license\n\"\"\"\nValidate a trained YOLOv3 detection model on a de"
}
]
About this extraction
This page contains the full source code of the ultralytics/yolov3 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 136 files (1.2 MB), approximately 349.3k tokens, and a symbol index with 683 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.