onipot
commited on
Commit
•
b025645
1
Parent(s):
b8f7f04
first
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- Roboto-Regular.ttf +0 -0
- app.py +63 -0
- images/cover1.jpg +0 -0
- images/google1.jpg +0 -0
- images/gradientgpu.jpg +0 -0
- images/scontrino1.jpg +0 -0
- images/sugar.jpg +0 -0
- requirements.txt +29 -0
- util.py +85 -0
- yolov5/.dockerignore +222 -0
- yolov5/.gitattributes +2 -0
- yolov5/.gitignore +256 -0
- yolov5/.pre-commit-config.yaml +66 -0
- yolov5/CONTRIBUTING.md +94 -0
- yolov5/Dockerfile +64 -0
- yolov5/LICENSE +674 -0
- yolov5/README.md +304 -0
- yolov5/__init__.py +0 -0
- yolov5/data/Argoverse.yaml +67 -0
- yolov5/data/GlobalWheat2020.yaml +53 -0
- yolov5/data/Objects365.yaml +112 -0
- yolov5/data/SKU-110K.yaml +52 -0
- yolov5/data/VOC.yaml +80 -0
- yolov5/data/VisDrone.yaml +61 -0
- yolov5/data/coco.yaml +44 -0
- yolov5/data/coco128.yaml +30 -0
- yolov5/data/hyps/hyp.finetune.yaml +39 -0
- yolov5/data/hyps/hyp.finetune_objects365.yaml +31 -0
- yolov5/data/hyps/hyp.scratch-high.yaml +34 -0
- yolov5/data/hyps/hyp.scratch-low.yaml +34 -0
- yolov5/data/hyps/hyp.scratch-med.yaml +34 -0
- yolov5/data/hyps/hyp.scratch.yaml +34 -0
- yolov5/data/images/bus.jpg +0 -0
- yolov5/data/images/zidane.jpg +0 -0
- yolov5/data/scripts/download_weights.sh +20 -0
- yolov5/data/scripts/get_coco.sh +27 -0
- yolov5/data/scripts/get_coco128.sh +17 -0
- yolov5/data/xView.yaml +102 -0
- yolov5/detect.py +332 -0
- yolov5/export.py +564 -0
- yolov5/models/__init__.py +0 -0
- yolov5/models/common.c +0 -0
- yolov5/models/common.py +572 -0
- yolov5/models/experimental.c +0 -0
- yolov5/models/experimental.py +120 -0
- yolov5/models/hub/anchors.yaml +59 -0
- yolov5/models/hub/yolov3-spp.yaml +51 -0
- yolov5/models/hub/yolov3-tiny.yaml +41 -0
- yolov5/models/hub/yolov3.yaml +51 -0
- yolov5/models/hub/yolov5-bifpn.yaml +48 -0
Roboto-Regular.ttf
ADDED
Binary file (159 kB). View file
|
|
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image,ImageDraw, ImageFont
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
model = os.environ.get('MODEL')
|
6 |
+
import torch
|
7 |
+
torch.hub.download_url_to_file(model, 'model.pt')
|
8 |
+
|
9 |
+
from util import Detection, classes
|
10 |
+
sys.path.append("./")
|
11 |
+
sys.path.append("./yolov5")
|
12 |
+
from yolov5.detect import predict, load_yolo_model
|
13 |
+
|
14 |
+
# Model
|
15 |
+
|
16 |
+
model, stride, names, pt, jit, onnx, engine = load_yolo_model("model.pt")
|
17 |
+
|
18 |
+
def run_yolo(img):
|
19 |
+
|
20 |
+
img0 = Image.open(img.name).convert("RGB")
|
21 |
+
draw = ImageDraw.Draw(img0)
|
22 |
+
|
23 |
+
predictions = predict(model, stride, names, pt, jit, onnx, engine, imgsz=[1280, 1280], conf_thres=0.5, iou_thres=0.3, save_conf=True,
|
24 |
+
exist_ok=True, save_txt=False, source=img.name, project=None, name=None)
|
25 |
+
|
26 |
+
detections : list[Detection] = []
|
27 |
+
for k, (bboxes, img) in enumerate(predictions):
|
28 |
+
|
29 |
+
#print(bboxes)
|
30 |
+
# exp.imgs.append(img_info)
|
31 |
+
for i, bbox in enumerate(bboxes):
|
32 |
+
det = Detection(
|
33 |
+
(k+1)*(i+1),
|
34 |
+
bbox["xmin"],
|
35 |
+
bbox["ymin"],
|
36 |
+
bbox["xmax"],
|
37 |
+
bbox["ymax"],
|
38 |
+
bbox["conf"],
|
39 |
+
bbox["class"],
|
40 |
+
classes[int(bbox["class"])],
|
41 |
+
img0.size
|
42 |
+
)
|
43 |
+
same = list(filter(lambda x: x.xmin == det.xmin and x.ymin == det.ymin or ( det.xmin > x.xmin and det.ymin > x.ymin and det.xmax < x.xmax and det.ymax < x.ymax ) or ( det.xmin < x.xmin and det.ymin < x.ymin and det.xmax > x.xmax and det.ymax > x.ymax ) or Detection.get_iou(det, x) > 0.6, detections))
|
44 |
+
|
45 |
+
if len(same) == 0:
|
46 |
+
detections.append(det)
|
47 |
+
draw.rectangle(((det.xmin, det.ymin), (det.xmax, det.ymax)), fill=None, outline=(255,255,255))
|
48 |
+
draw.rectangle(((det.xmin, det.ymin - 10), (det.xmax, det.ymin)), fill=(255,255,255))
|
49 |
+
draw.text((det.xmin, det.ymin - 10), det.class_name, fill=(0,0,0), font=ImageFont.truetype("Roboto-Regular.ttf"))
|
50 |
+
|
51 |
+
return img0
|
52 |
+
|
53 |
+
|
54 |
+
inputs = gr.inputs.Image(type='file', label="Original Image")
|
55 |
+
outputs = gr.outputs.Image(type="pil", label="Output Image")
|
56 |
+
|
57 |
+
title = "Letter Detection"
|
58 |
+
description = "Object Detection-based OCR. Upload an image or click an example image to use."
|
59 |
+
article = "<p style='text-align: center'>This is a character-level OCR trained on: <ul><li>Screenshots</li><li>Random photos taken from smartphone</li><li>Synthetic images</li><li>Receipts</li></p>"
|
60 |
+
|
61 |
+
examples = [['images/cover1.jpg'], ['images/scontrino1.jpg'], ['images/gradientgpu.jpg'], ['images/sugar.jpg'], ['images/google1.jpg'], ]
|
62 |
+
|
63 |
+
gr.Interface(run_yolo, inputs, outputs, title=title, description=description, article=article, examples=examples, theme="huggingface").launch(enable_queue=True)
|
images/cover1.jpg
ADDED
images/google1.jpg
ADDED
images/gradientgpu.jpg
ADDED
images/scontrino1.jpg
ADDED
images/sugar.jpg
ADDED
requirements.txt
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# base ----------------------------------------
|
2 |
+
matplotlib>=3.2.2
|
3 |
+
numpy>=1.18.5
|
4 |
+
opencv-python-headless
|
5 |
+
Pillow
|
6 |
+
PyYAML>=5.3.1
|
7 |
+
scipy>=1.4.1
|
8 |
+
torch>=1.7.0
|
9 |
+
torchvision>=0.8.1
|
10 |
+
tqdm>=4.41.0
|
11 |
+
|
12 |
+
# logging -------------------------------------
|
13 |
+
# tensorboard>=2.4.1
|
14 |
+
# wandb
|
15 |
+
|
16 |
+
# plotting ------------------------------------
|
17 |
+
seaborn>=0.11.0
|
18 |
+
pandas
|
19 |
+
|
20 |
+
# export --------------------------------------
|
21 |
+
# coremltools>=4.1
|
22 |
+
# onnx>=1.9.0
|
23 |
+
# scikit-learn==0.19.2 # for coreml quantization
|
24 |
+
|
25 |
+
# extras --------------------------------------
|
26 |
+
# Cython # for pycocotools https://github.com/cocodataset/cocoapi/issues/172
|
27 |
+
# pycocotools>=2.0 # COCO mAP
|
28 |
+
# albumentations>=1.0.3
|
29 |
+
thop # FLOPs computation
|
util.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
classes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
3 |
+
|
4 |
+
class Detection(object):
|
5 |
+
|
6 |
+
|
7 |
+
def __init__(self, id: int, xmin: int, ymin: int, xmax:int, ymax:int, conf: float, class_id:int, class_name:str, orig_img_sz: "tuple[int]") -> None:
|
8 |
+
|
9 |
+
self.id = id
|
10 |
+
|
11 |
+
self.xmin = xmin
|
12 |
+
self.ymin = ymin
|
13 |
+
self.xmax = xmax
|
14 |
+
self.ymax = ymax
|
15 |
+
|
16 |
+
self.w = self.xmax - self.xmin
|
17 |
+
self.h = self.ymax - self.ymin
|
18 |
+
|
19 |
+
self.conf = conf
|
20 |
+
self.class_id = class_id
|
21 |
+
self.class_name = class_name
|
22 |
+
|
23 |
+
self.orig_img_h = orig_img_sz[1]
|
24 |
+
self.orig_img_w = orig_img_sz[0]
|
25 |
+
|
26 |
+
def get_hw_ratio(self):
|
27 |
+
|
28 |
+
return self.h / self.w
|
29 |
+
|
30 |
+
def get_height_proportion(self):
|
31 |
+
|
32 |
+
return self.h / self.orig_img_h
|
33 |
+
|
34 |
+
def get_width_proportion(self):
|
35 |
+
|
36 |
+
return self.w / self.orig_img_w
|
37 |
+
|
38 |
+
def contains(self, detection2: "Detection"):
|
39 |
+
|
40 |
+
if self.xmin <= detection2.xmin and self.xmax >= detection2.xmax and \
|
41 |
+
self.ymin <= detection2.ymin and self.ymax >= detection2.ymax:
|
42 |
+
return True
|
43 |
+
|
44 |
+
return False
|
45 |
+
|
46 |
+
def get_iou(self, detection2: "Detection"):
|
47 |
+
"""
|
48 |
+
Calculate the Intersection over Union (IoU) of two bounding boxes.
|
49 |
+
|
50 |
+
Returns
|
51 |
+
-------
|
52 |
+
float
|
53 |
+
in [0, 1]
|
54 |
+
"""
|
55 |
+
assert self.xmin < self.xmax
|
56 |
+
assert self.ymin < self.ymax
|
57 |
+
assert detection2.xmin < detection2.xmax
|
58 |
+
assert detection2.ymin < detection2.ymax
|
59 |
+
|
60 |
+
# determine the coordinates of the intersection rectangle
|
61 |
+
x_left = max(self.xmin, detection2.xmin)
|
62 |
+
y_top = max(self.ymin, detection2.ymin)
|
63 |
+
x_right = min(self.xmax, detection2.xmax)
|
64 |
+
y_bottom = min(self.ymax, detection2.ymax)
|
65 |
+
|
66 |
+
if x_right < x_left or y_bottom < y_top:
|
67 |
+
return 0.0
|
68 |
+
|
69 |
+
# The intersection of two axis-aligned bounding boxes is always an
|
70 |
+
# axis-aligned bounding box
|
71 |
+
intersection_area = (x_right - x_left) * (y_bottom - y_top)
|
72 |
+
|
73 |
+
# compute the area of both AABBs
|
74 |
+
bb1_area = (self.xmax - self.xmin) * (self.ymax - self.ymin)
|
75 |
+
bb2_area = (detection2.xmax - detection2.xmin) * (detection2.ymax - detection2.ymin)
|
76 |
+
|
77 |
+
# compute the intersection over union by taking the intersection
|
78 |
+
# area and dividing it by the sum of prediction + ground-truth
|
79 |
+
# areas - the interesection area
|
80 |
+
iou = intersection_area / float(bb1_area + bb2_area - intersection_area)
|
81 |
+
|
82 |
+
return iou
|
83 |
+
|
84 |
+
def __str__(self) -> str:
|
85 |
+
return f"[{self.xmin}, {self.ymin}, {self.xmax}, {self.ymax}]"
|
yolov5/.dockerignore
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Repo-specific DockerIgnore -------------------------------------------------------------------------------------------
|
2 |
+
#.git
|
3 |
+
.cache
|
4 |
+
.idea
|
5 |
+
runs
|
6 |
+
output
|
7 |
+
coco
|
8 |
+
storage.googleapis.com
|
9 |
+
|
10 |
+
data/samples/*
|
11 |
+
**/results*.csv
|
12 |
+
*.jpg
|
13 |
+
|
14 |
+
# Neural Network weights -----------------------------------------------------------------------------------------------
|
15 |
+
**/*.pt
|
16 |
+
**/*.pth
|
17 |
+
**/*.onnx
|
18 |
+
**/*.engine
|
19 |
+
**/*.mlmodel
|
20 |
+
**/*.torchscript
|
21 |
+
**/*.torchscript.pt
|
22 |
+
**/*.tflite
|
23 |
+
**/*.h5
|
24 |
+
**/*.pb
|
25 |
+
*_saved_model/
|
26 |
+
*_web_model/
|
27 |
+
*_openvino_model/
|
28 |
+
|
29 |
+
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
30 |
+
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
31 |
+
|
32 |
+
|
33 |
+
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
34 |
+
# Byte-compiled / optimized / DLL files
|
35 |
+
__pycache__/
|
36 |
+
*.py[cod]
|
37 |
+
*$py.class
|
38 |
+
|
39 |
+
# C extensions
|
40 |
+
*.so
|
41 |
+
|
42 |
+
# Distribution / packaging
|
43 |
+
.Python
|
44 |
+
env/
|
45 |
+
build/
|
46 |
+
develop-eggs/
|
47 |
+
dist/
|
48 |
+
downloads/
|
49 |
+
eggs/
|
50 |
+
.eggs/
|
51 |
+
lib/
|
52 |
+
lib64/
|
53 |
+
parts/
|
54 |
+
sdist/
|
55 |
+
var/
|
56 |
+
wheels/
|
57 |
+
*.egg-info/
|
58 |
+
wandb/
|
59 |
+
.installed.cfg
|
60 |
+
*.egg
|
61 |
+
|
62 |
+
# PyInstaller
|
63 |
+
# Usually these files are written by a python script from a template
|
64 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
65 |
+
*.manifest
|
66 |
+
*.spec
|
67 |
+
|
68 |
+
# Installer logs
|
69 |
+
pip-log.txt
|
70 |
+
pip-delete-this-directory.txt
|
71 |
+
|
72 |
+
# Unit test / coverage reports
|
73 |
+
htmlcov/
|
74 |
+
.tox/
|
75 |
+
.coverage
|
76 |
+
.coverage.*
|
77 |
+
.cache
|
78 |
+
nosetests.xml
|
79 |
+
coverage.xml
|
80 |
+
*.cover
|
81 |
+
.hypothesis/
|
82 |
+
|
83 |
+
# Translations
|
84 |
+
*.mo
|
85 |
+
*.pot
|
86 |
+
|
87 |
+
# Django stuff:
|
88 |
+
*.log
|
89 |
+
local_settings.py
|
90 |
+
|
91 |
+
# Flask stuff:
|
92 |
+
instance/
|
93 |
+
.webassets-cache
|
94 |
+
|
95 |
+
# Scrapy stuff:
|
96 |
+
.scrapy
|
97 |
+
|
98 |
+
# Sphinx documentation
|
99 |
+
docs/_build/
|
100 |
+
|
101 |
+
# PyBuilder
|
102 |
+
target/
|
103 |
+
|
104 |
+
# Jupyter Notebook
|
105 |
+
.ipynb_checkpoints
|
106 |
+
|
107 |
+
# pyenv
|
108 |
+
.python-version
|
109 |
+
|
110 |
+
# celery beat schedule file
|
111 |
+
celerybeat-schedule
|
112 |
+
|
113 |
+
# SageMath parsed files
|
114 |
+
*.sage.py
|
115 |
+
|
116 |
+
# dotenv
|
117 |
+
.env
|
118 |
+
|
119 |
+
# virtualenv
|
120 |
+
.venv*
|
121 |
+
venv*/
|
122 |
+
ENV*/
|
123 |
+
|
124 |
+
# Spyder project settings
|
125 |
+
.spyderproject
|
126 |
+
.spyproject
|
127 |
+
|
128 |
+
# Rope project settings
|
129 |
+
.ropeproject
|
130 |
+
|
131 |
+
# mkdocs documentation
|
132 |
+
/site
|
133 |
+
|
134 |
+
# mypy
|
135 |
+
.mypy_cache/
|
136 |
+
|
137 |
+
|
138 |
+
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
139 |
+
|
140 |
+
# General
|
141 |
+
.DS_Store
|
142 |
+
.AppleDouble
|
143 |
+
.LSOverride
|
144 |
+
|
145 |
+
# Icon must end with two \r
|
146 |
+
Icon
|
147 |
+
Icon?
|
148 |
+
|
149 |
+
# Thumbnails
|
150 |
+
._*
|
151 |
+
|
152 |
+
# Files that might appear in the root of a volume
|
153 |
+
.DocumentRevisions-V100
|
154 |
+
.fseventsd
|
155 |
+
.Spotlight-V100
|
156 |
+
.TemporaryItems
|
157 |
+
.Trashes
|
158 |
+
.VolumeIcon.icns
|
159 |
+
.com.apple.timemachine.donotpresent
|
160 |
+
|
161 |
+
# Directories potentially created on remote AFP share
|
162 |
+
.AppleDB
|
163 |
+
.AppleDesktop
|
164 |
+
Network Trash Folder
|
165 |
+
Temporary Items
|
166 |
+
.apdisk
|
167 |
+
|
168 |
+
|
169 |
+
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
170 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
171 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
172 |
+
|
173 |
+
# User-specific stuff:
|
174 |
+
.idea/*
|
175 |
+
.idea/**/workspace.xml
|
176 |
+
.idea/**/tasks.xml
|
177 |
+
.idea/dictionaries
|
178 |
+
.html # Bokeh Plots
|
179 |
+
.pg # TensorFlow Frozen Graphs
|
180 |
+
.avi # videos
|
181 |
+
|
182 |
+
# Sensitive or high-churn files:
|
183 |
+
.idea/**/dataSources/
|
184 |
+
.idea/**/dataSources.ids
|
185 |
+
.idea/**/dataSources.local.xml
|
186 |
+
.idea/**/sqlDataSources.xml
|
187 |
+
.idea/**/dynamic.xml
|
188 |
+
.idea/**/uiDesigner.xml
|
189 |
+
|
190 |
+
# Gradle:
|
191 |
+
.idea/**/gradle.xml
|
192 |
+
.idea/**/libraries
|
193 |
+
|
194 |
+
# CMake
|
195 |
+
cmake-build-debug/
|
196 |
+
cmake-build-release/
|
197 |
+
|
198 |
+
# Mongo Explorer plugin:
|
199 |
+
.idea/**/mongoSettings.xml
|
200 |
+
|
201 |
+
## File-based project format:
|
202 |
+
*.iws
|
203 |
+
|
204 |
+
## Plugin-specific files:
|
205 |
+
|
206 |
+
# IntelliJ
|
207 |
+
out/
|
208 |
+
|
209 |
+
# mpeltonen/sbt-idea plugin
|
210 |
+
.idea_modules/
|
211 |
+
|
212 |
+
# JIRA plugin
|
213 |
+
atlassian-ide-plugin.xml
|
214 |
+
|
215 |
+
# Cursive Clojure plugin
|
216 |
+
.idea/replstate.xml
|
217 |
+
|
218 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
219 |
+
com_crashlytics_export_strings.xml
|
220 |
+
crashlytics.properties
|
221 |
+
crashlytics-build.properties
|
222 |
+
fabric.properties
|
yolov5/.gitattributes
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# this drop notebooks from GitHub language stats
|
2 |
+
*.ipynb linguist-vendored
|
yolov5/.gitignore
ADDED
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Repo-specific GitIgnore ----------------------------------------------------------------------------------------------
|
2 |
+
*.jpg
|
3 |
+
*.jpeg
|
4 |
+
*.png
|
5 |
+
*.bmp
|
6 |
+
*.tif
|
7 |
+
*.tiff
|
8 |
+
*.heic
|
9 |
+
*.JPG
|
10 |
+
*.JPEG
|
11 |
+
*.PNG
|
12 |
+
*.BMP
|
13 |
+
*.TIF
|
14 |
+
*.TIFF
|
15 |
+
*.HEIC
|
16 |
+
*.mp4
|
17 |
+
*.mov
|
18 |
+
*.MOV
|
19 |
+
*.avi
|
20 |
+
*.data
|
21 |
+
*.json
|
22 |
+
*.cfg
|
23 |
+
!setup.cfg
|
24 |
+
!cfg/yolov3*.cfg
|
25 |
+
|
26 |
+
storage.googleapis.com
|
27 |
+
runs/*
|
28 |
+
data/*
|
29 |
+
data/images/*
|
30 |
+
!data/*.yaml
|
31 |
+
!data/hyps
|
32 |
+
!data/scripts
|
33 |
+
!data/images
|
34 |
+
!data/images/zidane.jpg
|
35 |
+
!data/images/bus.jpg
|
36 |
+
!data/*.sh
|
37 |
+
|
38 |
+
results*.csv
|
39 |
+
|
40 |
+
# Datasets -------------------------------------------------------------------------------------------------------------
|
41 |
+
coco/
|
42 |
+
coco128/
|
43 |
+
VOC/
|
44 |
+
|
45 |
+
# MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
|
46 |
+
*.m~
|
47 |
+
*.mat
|
48 |
+
!targets*.mat
|
49 |
+
|
50 |
+
# Neural Network weights -----------------------------------------------------------------------------------------------
|
51 |
+
*.weights
|
52 |
+
*.pt
|
53 |
+
*.pb
|
54 |
+
*.onnx
|
55 |
+
*.engine
|
56 |
+
*.mlmodel
|
57 |
+
*.torchscript
|
58 |
+
*.tflite
|
59 |
+
*.h5
|
60 |
+
*_saved_model/
|
61 |
+
*_web_model/
|
62 |
+
*_openvino_model/
|
63 |
+
darknet53.conv.74
|
64 |
+
yolov3-tiny.conv.15
|
65 |
+
|
66 |
+
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
67 |
+
# Byte-compiled / optimized / DLL files
|
68 |
+
__pycache__/
|
69 |
+
*.py[cod]
|
70 |
+
*$py.class
|
71 |
+
|
72 |
+
# C extensions
|
73 |
+
*.so
|
74 |
+
|
75 |
+
# Distribution / packaging
|
76 |
+
.Python
|
77 |
+
env/
|
78 |
+
build/
|
79 |
+
develop-eggs/
|
80 |
+
dist/
|
81 |
+
downloads/
|
82 |
+
eggs/
|
83 |
+
.eggs/
|
84 |
+
lib/
|
85 |
+
lib64/
|
86 |
+
parts/
|
87 |
+
sdist/
|
88 |
+
var/
|
89 |
+
wheels/
|
90 |
+
*.egg-info/
|
91 |
+
/wandb/
|
92 |
+
.installed.cfg
|
93 |
+
*.egg
|
94 |
+
|
95 |
+
|
96 |
+
# PyInstaller
|
97 |
+
# Usually these files are written by a python script from a template
|
98 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
99 |
+
*.manifest
|
100 |
+
*.spec
|
101 |
+
|
102 |
+
# Installer logs
|
103 |
+
pip-log.txt
|
104 |
+
pip-delete-this-directory.txt
|
105 |
+
|
106 |
+
# Unit test / coverage reports
|
107 |
+
htmlcov/
|
108 |
+
.tox/
|
109 |
+
.coverage
|
110 |
+
.coverage.*
|
111 |
+
.cache
|
112 |
+
nosetests.xml
|
113 |
+
coverage.xml
|
114 |
+
*.cover
|
115 |
+
.hypothesis/
|
116 |
+
|
117 |
+
# Translations
|
118 |
+
*.mo
|
119 |
+
*.pot
|
120 |
+
|
121 |
+
# Django stuff:
|
122 |
+
*.log
|
123 |
+
local_settings.py
|
124 |
+
|
125 |
+
# Flask stuff:
|
126 |
+
instance/
|
127 |
+
.webassets-cache
|
128 |
+
|
129 |
+
# Scrapy stuff:
|
130 |
+
.scrapy
|
131 |
+
|
132 |
+
# Sphinx documentation
|
133 |
+
docs/_build/
|
134 |
+
|
135 |
+
# PyBuilder
|
136 |
+
target/
|
137 |
+
|
138 |
+
# Jupyter Notebook
|
139 |
+
.ipynb_checkpoints
|
140 |
+
|
141 |
+
# pyenv
|
142 |
+
.python-version
|
143 |
+
|
144 |
+
# celery beat schedule file
|
145 |
+
celerybeat-schedule
|
146 |
+
|
147 |
+
# SageMath parsed files
|
148 |
+
*.sage.py
|
149 |
+
|
150 |
+
# dotenv
|
151 |
+
.env
|
152 |
+
|
153 |
+
# virtualenv
|
154 |
+
.venv*
|
155 |
+
venv*/
|
156 |
+
ENV*/
|
157 |
+
|
158 |
+
# Spyder project settings
|
159 |
+
.spyderproject
|
160 |
+
.spyproject
|
161 |
+
|
162 |
+
# Rope project settings
|
163 |
+
.ropeproject
|
164 |
+
|
165 |
+
# mkdocs documentation
|
166 |
+
/site
|
167 |
+
|
168 |
+
# mypy
|
169 |
+
.mypy_cache/
|
170 |
+
|
171 |
+
|
172 |
+
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
173 |
+
|
174 |
+
# General
|
175 |
+
.DS_Store
|
176 |
+
.AppleDouble
|
177 |
+
.LSOverride
|
178 |
+
|
179 |
+
# Icon must end with two \r
|
180 |
+
Icon
|
181 |
+
Icon?
|
182 |
+
|
183 |
+
# Thumbnails
|
184 |
+
._*
|
185 |
+
|
186 |
+
# Files that might appear in the root of a volume
|
187 |
+
.DocumentRevisions-V100
|
188 |
+
.fseventsd
|
189 |
+
.Spotlight-V100
|
190 |
+
.TemporaryItems
|
191 |
+
.Trashes
|
192 |
+
.VolumeIcon.icns
|
193 |
+
.com.apple.timemachine.donotpresent
|
194 |
+
|
195 |
+
# Directories potentially created on remote AFP share
|
196 |
+
.AppleDB
|
197 |
+
.AppleDesktop
|
198 |
+
Network Trash Folder
|
199 |
+
Temporary Items
|
200 |
+
.apdisk
|
201 |
+
|
202 |
+
|
203 |
+
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
204 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
205 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
206 |
+
|
207 |
+
# User-specific stuff:
|
208 |
+
.idea/*
|
209 |
+
.idea/**/workspace.xml
|
210 |
+
.idea/**/tasks.xml
|
211 |
+
.idea/dictionaries
|
212 |
+
.html # Bokeh Plots
|
213 |
+
.pg # TensorFlow Frozen Graphs
|
214 |
+
.avi # videos
|
215 |
+
|
216 |
+
# Sensitive or high-churn files:
|
217 |
+
.idea/**/dataSources/
|
218 |
+
.idea/**/dataSources.ids
|
219 |
+
.idea/**/dataSources.local.xml
|
220 |
+
.idea/**/sqlDataSources.xml
|
221 |
+
.idea/**/dynamic.xml
|
222 |
+
.idea/**/uiDesigner.xml
|
223 |
+
|
224 |
+
# Gradle:
|
225 |
+
.idea/**/gradle.xml
|
226 |
+
.idea/**/libraries
|
227 |
+
|
228 |
+
# CMake
|
229 |
+
cmake-build-debug/
|
230 |
+
cmake-build-release/
|
231 |
+
|
232 |
+
# Mongo Explorer plugin:
|
233 |
+
.idea/**/mongoSettings.xml
|
234 |
+
|
235 |
+
## File-based project format:
|
236 |
+
*.iws
|
237 |
+
|
238 |
+
## Plugin-specific files:
|
239 |
+
|
240 |
+
# IntelliJ
|
241 |
+
out/
|
242 |
+
|
243 |
+
# mpeltonen/sbt-idea plugin
|
244 |
+
.idea_modules/
|
245 |
+
|
246 |
+
# JIRA plugin
|
247 |
+
atlassian-ide-plugin.xml
|
248 |
+
|
249 |
+
# Cursive Clojure plugin
|
250 |
+
.idea/replstate.xml
|
251 |
+
|
252 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
253 |
+
com_crashlytics_export_strings.xml
|
254 |
+
crashlytics.properties
|
255 |
+
crashlytics-build.properties
|
256 |
+
fabric.properties
|
yolov5/.pre-commit-config.yaml
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Define hooks for code formations
|
2 |
+
# Will be applied on any updated commit files if a user has installed and linked commit hook
|
3 |
+
|
4 |
+
default_language_version:
|
5 |
+
python: python3.8
|
6 |
+
|
7 |
+
# Define bot property if installed via https://github.com/marketplace/pre-commit-ci
|
8 |
+
ci:
|
9 |
+
autofix_prs: true
|
10 |
+
autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
|
11 |
+
autoupdate_schedule: quarterly
|
12 |
+
# submodules: true
|
13 |
+
|
14 |
+
repos:
|
15 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
16 |
+
rev: v4.1.0
|
17 |
+
hooks:
|
18 |
+
- id: end-of-file-fixer
|
19 |
+
- id: trailing-whitespace
|
20 |
+
- id: check-case-conflict
|
21 |
+
- id: check-yaml
|
22 |
+
- id: check-toml
|
23 |
+
- id: pretty-format-json
|
24 |
+
- id: check-docstring-first
|
25 |
+
|
26 |
+
- repo: https://github.com/asottile/pyupgrade
|
27 |
+
rev: v2.31.0
|
28 |
+
hooks:
|
29 |
+
- id: pyupgrade
|
30 |
+
args: [--py36-plus]
|
31 |
+
name: Upgrade code
|
32 |
+
|
33 |
+
- repo: https://github.com/PyCQA/isort
|
34 |
+
rev: 5.10.1
|
35 |
+
hooks:
|
36 |
+
- id: isort
|
37 |
+
name: Sort imports
|
38 |
+
|
39 |
+
# TODO
|
40 |
+
#- repo: https://github.com/pre-commit/mirrors-yapf
|
41 |
+
# rev: v0.31.0
|
42 |
+
# hooks:
|
43 |
+
# - id: yapf
|
44 |
+
# name: formatting
|
45 |
+
|
46 |
+
# TODO
|
47 |
+
#- repo: https://github.com/executablebooks/mdformat
|
48 |
+
# rev: 0.7.7
|
49 |
+
# hooks:
|
50 |
+
# - id: mdformat
|
51 |
+
# additional_dependencies:
|
52 |
+
# - mdformat-gfm
|
53 |
+
# - mdformat-black
|
54 |
+
# - mdformat_frontmatter
|
55 |
+
|
56 |
+
# TODO
|
57 |
+
#- repo: https://github.com/asottile/yesqa
|
58 |
+
# rev: v1.2.3
|
59 |
+
# hooks:
|
60 |
+
# - id: yesqa
|
61 |
+
|
62 |
+
- repo: https://github.com/PyCQA/flake8
|
63 |
+
rev: 4.0.1
|
64 |
+
hooks:
|
65 |
+
- id: flake8
|
66 |
+
name: PEP8
|
yolov5/CONTRIBUTING.md
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Contributing to YOLOv5 🚀
|
2 |
+
|
3 |
+
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
|
4 |
+
|
5 |
+
- Reporting a bug
|
6 |
+
- Discussing the current state of the code
|
7 |
+
- Submitting a fix
|
8 |
+
- Proposing a new feature
|
9 |
+
- Becoming a maintainer
|
10 |
+
|
11 |
+
YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
|
12 |
+
helping push the frontiers of what's possible in AI 😃!
|
13 |
+
|
14 |
+
## Submitting a Pull Request (PR) 🛠️
|
15 |
+
|
16 |
+
Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
|
17 |
+
|
18 |
+
### 1. Select File to Update
|
19 |
+
|
20 |
+
Select `requirements.txt` to update by clicking on it in GitHub.
|
21 |
+
<p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
|
22 |
+
|
23 |
+
### 2. Click 'Edit this file'
|
24 |
+
|
25 |
+
Button is in top-right corner.
|
26 |
+
<p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
|
27 |
+
|
28 |
+
### 3. Make Changes
|
29 |
+
|
30 |
+
Change `matplotlib` version from `3.2.2` to `3.3`.
|
31 |
+
<p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
|
32 |
+
|
33 |
+
### 4. Preview Changes and Submit PR
|
34 |
+
|
35 |
+
Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
|
36 |
+
for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
|
37 |
+
changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
|
38 |
+
<p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
|
39 |
+
|
40 |
+
### PR recommendations
|
41 |
+
|
42 |
+
To allow your work to be integrated as seamlessly as possible, we advise you to:
|
43 |
+
|
44 |
+
- ✅ Verify your PR is **up-to-date with upstream/master.** If your PR is behind upstream/master an
|
45 |
+
automatic [GitHub actions](https://github.com/ultralytics/yolov5/blob/master/.github/workflows/rebase.yml) rebase may
|
46 |
+
be attempted by including the /rebase command in a comment body, or by running the following code, replacing 'feature'
|
47 |
+
with the name of your local branch:
|
48 |
+
|
49 |
+
```bash
|
50 |
+
git remote add upstream https://github.com/ultralytics/yolov5.git
|
51 |
+
git fetch upstream
|
52 |
+
git checkout feature # <----- replace 'feature' with local branch name
|
53 |
+
git merge upstream/master
|
54 |
+
git push -u origin -f
|
55 |
+
```
|
56 |
+
|
57 |
+
- ✅ Verify all Continuous Integration (CI) **checks are passing**.
|
58 |
+
- ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
|
59 |
+
but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
|
60 |
+
|
61 |
+
## Submitting a Bug Report 🐛
|
62 |
+
|
63 |
+
If you spot a problem with YOLOv5 please submit a Bug Report!
|
64 |
+
|
65 |
+
For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few
|
66 |
+
short guidelines below to help users provide what we need in order to get started.
|
67 |
+
|
68 |
+
When asking a question, people will be better able to provide help if you provide **code** that they can easily
|
69 |
+
understand and use to **reproduce** the problem. This is referred to by community members as creating
|
70 |
+
a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
|
71 |
+
the problem should be:
|
72 |
+
|
73 |
+
* ✅ **Minimal** – Use as little code as possible that still produces the same problem
|
74 |
+
* ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
|
75 |
+
* ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
|
76 |
+
|
77 |
+
In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
|
78 |
+
should be:
|
79 |
+
|
80 |
+
* ✅ **Current** – Verify that your code is up-to-date with current
|
81 |
+
GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
|
82 |
+
copy to ensure your problem has not already been resolved by previous commits.
|
83 |
+
* ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this
|
84 |
+
repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
|
85 |
+
|
86 |
+
If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛 **
|
87 |
+
Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing
|
88 |
+
a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
|
89 |
+
understand and diagnose your problem.
|
90 |
+
|
91 |
+
## License
|
92 |
+
|
93 |
+
By contributing, you agree that your contributions will be licensed under
|
94 |
+
the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/)
|
yolov5/Dockerfile
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
|
4 |
+
FROM nvcr.io/nvidia/pytorch:21.10-py3
|
5 |
+
|
6 |
+
# Install linux packages
|
7 |
+
RUN apt update && apt install -y zip htop screen libgl1-mesa-glx
|
8 |
+
|
9 |
+
# Install python dependencies
|
10 |
+
COPY requirements.txt .
|
11 |
+
RUN python -m pip install --upgrade pip
|
12 |
+
RUN pip uninstall -y nvidia-tensorboard nvidia-tensorboard-plugin-dlprof
|
13 |
+
RUN pip install --no-cache -r requirements.txt albumentations coremltools onnx gsutil notebook numpy Pillow wandb>=0.12.2
|
14 |
+
RUN pip install --no-cache torch==1.10.1+cu113 torchvision==0.11.2+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
|
15 |
+
# RUN pip install --no-cache -U torch torchvision
|
16 |
+
|
17 |
+
# Create working directory
|
18 |
+
RUN mkdir -p /usr/src/app
|
19 |
+
WORKDIR /usr/src/app
|
20 |
+
|
21 |
+
# Copy contents
|
22 |
+
COPY . /usr/src/app
|
23 |
+
|
24 |
+
# Downloads to user config dir
|
25 |
+
ADD https://ultralytics.com/assets/Arial.ttf /root/.config/Ultralytics/
|
26 |
+
|
27 |
+
# Set environment variables
|
28 |
+
# ENV HOME=/usr/src/app
|
29 |
+
|
30 |
+
|
31 |
+
# Usage Examples -------------------------------------------------------------------------------------------------------
|
32 |
+
|
33 |
+
# Build and Push
|
34 |
+
# t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t
|
35 |
+
|
36 |
+
# Pull and Run
|
37 |
+
# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t
|
38 |
+
|
39 |
+
# Pull and Run with local directory access
|
40 |
+
# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t
|
41 |
+
|
42 |
+
# Kill all
|
43 |
+
# sudo docker kill $(sudo docker ps -q)
|
44 |
+
|
45 |
+
# Kill all image-based
|
46 |
+
# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)
|
47 |
+
|
48 |
+
# Bash into running container
|
49 |
+
# sudo docker exec -it 5a9b5863d93d bash
|
50 |
+
|
51 |
+
# Bash into stopped container
|
52 |
+
# id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash
|
53 |
+
|
54 |
+
# Clean up
|
55 |
+
# docker system prune -a --volumes
|
56 |
+
|
57 |
+
# Update Ubuntu drivers
|
58 |
+
# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/
|
59 |
+
|
60 |
+
# DDP test
|
61 |
+
# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3
|
62 |
+
|
63 |
+
# GCP VM from Image
|
64 |
+
# docker.io/ultralytics/yolov5:latest
|
yolov5/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<http://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
yolov5/README.md
ADDED
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<div align="center">
|
2 |
+
<p>
|
3 |
+
<a align="left" href="https://ultralytics.com/yolov5" target="_blank">
|
4 |
+
<img width="850" src="https://github.com/ultralytics/yolov5/releases/download/v1.0/splash.jpg"></a>
|
5 |
+
</p>
|
6 |
+
<br>
|
7 |
+
<div>
|
8 |
+
<a href="https://github.com/ultralytics/yolov5/actions"><img src="https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg" alt="CI CPU testing"></a>
|
9 |
+
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
|
10 |
+
<a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
|
11 |
+
<br>
|
12 |
+
<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>
|
13 |
+
<a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
|
14 |
+
<a href="https://join.slack.com/t/ultralytics/shared_invite/zt-w29ei8bp-jczz7QYUmDtgo6r6KcMIAg"><img src="https://img.shields.io/badge/Slack-Join_Forum-blue.svg?logo=slack" alt="Join Forum"></a>
|
15 |
+
</div>
|
16 |
+
<br>
|
17 |
+
<div align="center">
|
18 |
+
<a href="https://github.com/ultralytics">
|
19 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-github.png" width="2%"/>
|
20 |
+
</a>
|
21 |
+
<img width="2%" />
|
22 |
+
<a href="https://www.linkedin.com/company/ultralytics">
|
23 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-linkedin.png" width="2%"/>
|
24 |
+
</a>
|
25 |
+
<img width="2%" />
|
26 |
+
<a href="https://twitter.com/ultralytics">
|
27 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-twitter.png" width="2%"/>
|
28 |
+
</a>
|
29 |
+
<img width="2%" />
|
30 |
+
<a href="https://www.producthunt.com/@glenn_jocher">
|
31 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-producthunt.png" width="2%"/>
|
32 |
+
</a>
|
33 |
+
<img width="2%" />
|
34 |
+
<a href="https://youtube.com/ultralytics">
|
35 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-youtube.png" width="2%"/>
|
36 |
+
</a>
|
37 |
+
<img width="2%" />
|
38 |
+
<a href="https://www.facebook.com/ultralytics">
|
39 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-facebook.png" width="2%"/>
|
40 |
+
</a>
|
41 |
+
<img width="2%" />
|
42 |
+
<a href="https://www.instagram.com/ultralytics/">
|
43 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-instagram.png" width="2%"/>
|
44 |
+
</a>
|
45 |
+
</div>
|
46 |
+
|
47 |
+
<br>
|
48 |
+
<p>
|
49 |
+
YOLOv5 🚀 is a family of object detection architectures and models pretrained on the COCO dataset, and represents <a href="https://ultralytics.com">Ultralytics</a>
|
50 |
+
open-source research into future vision AI methods, incorporating lessons learned and best practices evolved over thousands of hours of research and development.
|
51 |
+
</p>
|
52 |
+
|
53 |
+
<!--
|
54 |
+
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
55 |
+
<img width="800" src="https://github.com/ultralytics/yolov5/releases/download/v1.0/banner-api.png"></a>
|
56 |
+
-->
|
57 |
+
|
58 |
+
</div>
|
59 |
+
|
60 |
+
## <div align="center">Documentation</div>
|
61 |
+
|
62 |
+
See the [YOLOv5 Docs](https://docs.ultralytics.com) for full documentation on training, testing and deployment.
|
63 |
+
|
64 |
+
## <div align="center">Quick Start Examples</div>
|
65 |
+
|
66 |
+
<details open>
|
67 |
+
<summary>Install</summary>
|
68 |
+
|
69 |
+
Clone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a
|
70 |
+
[**Python>=3.7.0**](https://www.python.org/) environment, including
|
71 |
+
[**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).
|
72 |
+
|
73 |
+
```bash
|
74 |
+
git clone https://github.com/ultralytics/yolov5 # clone
|
75 |
+
cd yolov5
|
76 |
+
pip install -r requirements.txt # install
|
77 |
+
```
|
78 |
+
|
79 |
+
</details>
|
80 |
+
|
81 |
+
<details open>
|
82 |
+
<summary>Inference</summary>
|
83 |
+
|
84 |
+
Inference with YOLOv5 and [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36)
|
85 |
+
. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest
|
86 |
+
YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).
|
87 |
+
|
88 |
+
```python
|
89 |
+
import torch
|
90 |
+
|
91 |
+
# Model
|
92 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5m, yolov5l, yolov5x, custom
|
93 |
+
|
94 |
+
# Images
|
95 |
+
img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
|
96 |
+
|
97 |
+
# Inference
|
98 |
+
results = model(img)
|
99 |
+
|
100 |
+
# Results
|
101 |
+
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
|
102 |
+
```
|
103 |
+
|
104 |
+
</details>
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
<details>
|
109 |
+
<summary>Inference with detect.py</summary>
|
110 |
+
|
111 |
+
`detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from
|
112 |
+
the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
|
113 |
+
|
114 |
+
```bash
|
115 |
+
python detect.py --source 0 # webcam
|
116 |
+
img.jpg # image
|
117 |
+
vid.mp4 # video
|
118 |
+
path/ # directory
|
119 |
+
path/*.jpg # glob
|
120 |
+
'https://youtu.be/Zgi9g1ksQHc' # YouTube
|
121 |
+
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
122 |
+
```
|
123 |
+
|
124 |
+
</details>
|
125 |
+
|
126 |
+
<details>
|
127 |
+
<summary>Training</summary>
|
128 |
+
|
129 |
+
The commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh)
|
130 |
+
results. [Models](https://github.com/ultralytics/yolov5/tree/master/models)
|
131 |
+
and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest
|
132 |
+
YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are
|
133 |
+
1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://github.com/ultralytics/yolov5/issues/475) times faster). Use the
|
134 |
+
largest `--batch-size` possible, or pass `--batch-size -1` for
|
135 |
+
YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB.
|
136 |
+
|
137 |
+
```bash
|
138 |
+
python train.py --data coco.yaml --cfg yolov5n.yaml --weights '' --batch-size 128
|
139 |
+
yolov5s 64
|
140 |
+
yolov5m 40
|
141 |
+
yolov5l 24
|
142 |
+
yolov5x 16
|
143 |
+
```
|
144 |
+
|
145 |
+
<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
|
146 |
+
|
147 |
+
</details>
|
148 |
+
|
149 |
+
<details open>
|
150 |
+
<summary>Tutorials</summary>
|
151 |
+
|
152 |
+
* [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 🚀 RECOMMENDED
|
153 |
+
* [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results) ☘️
|
154 |
+
RECOMMENDED
|
155 |
+
* [Weights & Biases Logging](https://github.com/ultralytics/yolov5/issues/1289) 🌟 NEW
|
156 |
+
* [Roboflow for Datasets, Labeling, and Active Learning](https://github.com/ultralytics/yolov5/issues/4975) 🌟 NEW
|
157 |
+
* [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475)
|
158 |
+
* [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) ⭐ NEW
|
159 |
+
* [TFLite, ONNX, CoreML, TensorRT Export](https://github.com/ultralytics/yolov5/issues/251) 🚀
|
160 |
+
* [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303)
|
161 |
+
* [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318)
|
162 |
+
* [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304)
|
163 |
+
* [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607)
|
164 |
+
* [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314) ⭐ NEW
|
165 |
+
* [TensorRT Deployment](https://github.com/wang-xinyu/tensorrtx)
|
166 |
+
|
167 |
+
</details>
|
168 |
+
|
169 |
+
## <div align="center">Environments</div>
|
170 |
+
|
171 |
+
Get started in seconds with our verified environments. Click each icon below for details.
|
172 |
+
|
173 |
+
<div align="center">
|
174 |
+
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
|
175 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-colab-small.png" width="15%"/>
|
176 |
+
</a>
|
177 |
+
<a href="https://www.kaggle.com/ultralytics/yolov5">
|
178 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-kaggle-small.png" width="15%"/>
|
179 |
+
</a>
|
180 |
+
<a href="https://hub.docker.com/r/ultralytics/yolov5">
|
181 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-docker-small.png" width="15%"/>
|
182 |
+
</a>
|
183 |
+
<a href="https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart">
|
184 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-aws-small.png" width="15%"/>
|
185 |
+
</a>
|
186 |
+
<a href="https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart">
|
187 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-gcp-small.png" width="15%"/>
|
188 |
+
</a>
|
189 |
+
</div>
|
190 |
+
|
191 |
+
## <div align="center">Integrations</div>
|
192 |
+
|
193 |
+
<div align="center">
|
194 |
+
<a href="https://wandb.ai/site?utm_campaign=repo_yolo_readme">
|
195 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-wb-long.png" width="49%"/>
|
196 |
+
</a>
|
197 |
+
<a href="https://roboflow.com/?ref=ultralytics">
|
198 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-roboflow-long.png" width="49%"/>
|
199 |
+
</a>
|
200 |
+
</div>
|
201 |
+
|
202 |
+
|Weights and Biases|Roboflow ⭐ NEW|
|
203 |
+
|:-:|:-:|
|
204 |
+
|Automatically track and visualize all your YOLOv5 training runs in the cloud with [Weights & Biases](https://wandb.ai/site?utm_campaign=repo_yolo_readme)|Label and export your custom datasets directly to YOLOv5 for training with [Roboflow](https://roboflow.com/?ref=ultralytics) |
|
205 |
+
|
206 |
+
|
207 |
+
<!-- ## <div align="center">Compete and Win</div>
|
208 |
+
|
209 |
+
We are super excited about our first-ever Ultralytics YOLOv5 🚀 EXPORT Competition with **$10,000** in cash prizes!
|
210 |
+
|
211 |
+
<p align="center">
|
212 |
+
<a href="https://github.com/ultralytics/yolov5/discussions/3213">
|
213 |
+
<img width="850" src="https://github.com/ultralytics/yolov5/releases/download/v1.0/banner-export-competition.png"></a>
|
214 |
+
</p> -->
|
215 |
+
|
216 |
+
## <div align="center">Why YOLOv5</div>
|
217 |
+
|
218 |
+
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/136901921-abcfcd9d-f978-4942-9b97-0e3f202907df.png"></p>
|
219 |
+
<details>
|
220 |
+
<summary>YOLOv5-P5 640 Figure (click to expand)</summary>
|
221 |
+
|
222 |
+
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/136763877-b174052b-c12f-48d2-8bc4-545e3853398e.png"></p>
|
223 |
+
</details>
|
224 |
+
<details>
|
225 |
+
<summary>Figure Notes (click to expand)</summary>
|
226 |
+
|
227 |
+
* **COCO AP val** denotes [email protected]:0.95 metric measured on the 5000-image [COCO val2017](http://cocodataset.org) dataset over various inference sizes from 256 to 1536.
|
228 |
+
* **GPU Speed** measures average inference time per image on [COCO val2017](http://cocodataset.org) dataset using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100 instance at batch-size 32.
|
229 |
+
* **EfficientDet** data from [google/automl](https://github.com/google/automl) at batch size 8.
|
230 |
+
* **Reproduce** by `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
|
231 |
+
</details>
|
232 |
+
|
233 |
+
### Pretrained Checkpoints
|
234 |
+
|
235 |
+
[assets]: https://github.com/ultralytics/yolov5/releases
|
236 |
+
|
237 |
+
[TTA]: https://github.com/ultralytics/yolov5/issues/303
|
238 |
+
|
239 |
+
|Model |size<br><sup>(pixels) |mAP<sup>val<br>0.5:0.95 |mAP<sup>val<br>0.5 |Speed<br><sup>CPU b1<br>(ms) |Speed<br><sup>V100 b1<br>(ms) |Speed<br><sup>V100 b32<br>(ms) |params<br><sup>(M) |FLOPs<br><sup>@640 (B)
|
240 |
+
|--- |--- |--- |--- |--- |--- |--- |--- |---
|
241 |
+
|[YOLOv5n][assets] |640 |28.4 |46.0 |**45** |**6.3**|**0.6**|**1.9**|**4.5**
|
242 |
+
|[YOLOv5s][assets] |640 |37.2 |56.0 |98 |6.4 |0.9 |7.2 |16.5
|
243 |
+
|[YOLOv5m][assets] |640 |45.2 |63.9 |224 |8.2 |1.7 |21.2 |49.0
|
244 |
+
|[YOLOv5l][assets] |640 |48.8 |67.2 |430 |10.1 |2.7 |46.5 |109.1
|
245 |
+
|[YOLOv5x][assets] |640 |50.7 |68.9 |766 |12.1 |4.8 |86.7 |205.7
|
246 |
+
| | | | | | | | |
|
247 |
+
|[YOLOv5n6][assets] |1280 |34.0 |50.7 |153 |8.1 |2.1 |3.2 |4.6
|
248 |
+
|[YOLOv5s6][assets] |1280 |44.5 |63.0 |385 |8.2 |3.6 |12.6 |16.8
|
249 |
+
|[YOLOv5m6][assets] |1280 |51.0 |69.0 |887 |11.1 |6.8 |35.7 |50.0
|
250 |
+
|[YOLOv5l6][assets] |1280 |53.6 |71.6 |1784 |15.8 |10.5 |76.7 |111.4
|
251 |
+
|[YOLOv5x6][assets]<br>+ [TTA][TTA]|1280<br>1536 |54.7<br>**55.4** |**72.4**<br>72.3 |3136<br>- |26.2<br>- |19.4<br>- |140.7<br>- |209.8<br>-
|
252 |
+
|
253 |
+
<details>
|
254 |
+
<summary>Table Notes (click to expand)</summary>
|
255 |
+
|
256 |
+
* All checkpoints are trained to 300 epochs with default settings and hyperparameters.
|
257 |
+
* **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.<br>Reproduce by `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
|
258 |
+
* **Speed** averaged over COCO val images using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) instance. NMS times (~1 ms/img) not included.<br>Reproduce by `python val.py --data coco.yaml --img 640 --task speed --batch 1`
|
259 |
+
* **TTA** [Test Time Augmentation](https://github.com/ultralytics/yolov5/issues/303) includes reflection and scale augmentations.<br>Reproduce by `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
|
260 |
+
|
261 |
+
</details>
|
262 |
+
|
263 |
+
## <div align="center">Contribute</div>
|
264 |
+
|
265 |
+
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible. Please see our [Contributing Guide](CONTRIBUTING.md) to get started, and fill out the [YOLOv5 Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experiences. Thank you to all our contributors!
|
266 |
+
|
267 |
+
<a href="https://github.com/ultralytics/yolov5/graphs/contributors"><img src="https://opencollective.com/ultralytics/contributors.svg?width=990" /></a>
|
268 |
+
|
269 |
+
## <div align="center">Contact</div>
|
270 |
+
|
271 |
+
For YOLOv5 bugs and feature requests please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For business inquiries or
|
272 |
+
professional support requests please visit [https://ultralytics.com/contact](https://ultralytics.com/contact).
|
273 |
+
|
274 |
+
<br>
|
275 |
+
|
276 |
+
<div align="center">
|
277 |
+
<a href="https://github.com/ultralytics">
|
278 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-github.png" width="3%"/>
|
279 |
+
</a>
|
280 |
+
<img width="3%" />
|
281 |
+
<a href="https://www.linkedin.com/company/ultralytics">
|
282 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-linkedin.png" width="3%"/>
|
283 |
+
</a>
|
284 |
+
<img width="3%" />
|
285 |
+
<a href="https://twitter.com/ultralytics">
|
286 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-twitter.png" width="3%"/>
|
287 |
+
</a>
|
288 |
+
<img width="3%" />
|
289 |
+
<a href="https://www.producthunt.com/@glenn_jocher">
|
290 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-producthunt.png" width="3%"/>
|
291 |
+
</a>
|
292 |
+
<img width="3%" />
|
293 |
+
<a href="https://youtube.com/ultralytics">
|
294 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-youtube.png" width="3%"/>
|
295 |
+
</a>
|
296 |
+
<img width="3%" />
|
297 |
+
<a href="https://www.facebook.com/ultralytics">
|
298 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-facebook.png" width="3%"/>
|
299 |
+
</a>
|
300 |
+
<img width="3%" />
|
301 |
+
<a href="https://www.instagram.com/ultralytics/">
|
302 |
+
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-social-instagram.png" width="3%"/>
|
303 |
+
</a>
|
304 |
+
</div>
|
yolov5/__init__.py
ADDED
File without changes
|
yolov5/data/Argoverse.yaml
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI
|
3 |
+
# Example usage: python train.py --data Argoverse.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── Argoverse ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/Argoverse # dataset root dir
|
12 |
+
train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
|
13 |
+
val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
|
14 |
+
test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 8 # number of classes
|
18 |
+
names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names
|
19 |
+
|
20 |
+
|
21 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
22 |
+
download: |
|
23 |
+
import json
|
24 |
+
|
25 |
+
from tqdm import tqdm
|
26 |
+
from utils.general import download, Path
|
27 |
+
|
28 |
+
|
29 |
+
def argoverse2yolo(set):
|
30 |
+
labels = {}
|
31 |
+
a = json.load(open(set, "rb"))
|
32 |
+
for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
|
33 |
+
img_id = annot['image_id']
|
34 |
+
img_name = a['images'][img_id]['name']
|
35 |
+
img_label_name = img_name[:-3] + "txt"
|
36 |
+
|
37 |
+
cls = annot['category_id'] # instance class id
|
38 |
+
x_center, y_center, width, height = annot['bbox']
|
39 |
+
x_center = (x_center + width / 2) / 1920.0 # offset and scale
|
40 |
+
y_center = (y_center + height / 2) / 1200.0 # offset and scale
|
41 |
+
width /= 1920.0 # scale
|
42 |
+
height /= 1200.0 # scale
|
43 |
+
|
44 |
+
img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
|
45 |
+
if not img_dir.exists():
|
46 |
+
img_dir.mkdir(parents=True, exist_ok=True)
|
47 |
+
|
48 |
+
k = str(img_dir / img_label_name)
|
49 |
+
if k not in labels:
|
50 |
+
labels[k] = []
|
51 |
+
labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
|
52 |
+
|
53 |
+
for k in labels:
|
54 |
+
with open(k, "w") as f:
|
55 |
+
f.writelines(labels[k])
|
56 |
+
|
57 |
+
|
58 |
+
# Download
|
59 |
+
dir = Path('../datasets/Argoverse') # dataset root dir
|
60 |
+
urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
|
61 |
+
download(urls, dir=dir, delete=False)
|
62 |
+
|
63 |
+
# Convert
|
64 |
+
annotations_dir = 'Argoverse-HD/annotations/'
|
65 |
+
(dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
|
66 |
+
for d in "train.json", "val.json":
|
67 |
+
argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
|
yolov5/data/GlobalWheat2020.yaml
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan
|
3 |
+
# Example usage: python train.py --data GlobalWheat2020.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── GlobalWheat2020 ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/GlobalWheat2020 # dataset root dir
|
12 |
+
train: # train images (relative to 'path') 3422 images
|
13 |
+
- images/arvalis_1
|
14 |
+
- images/arvalis_2
|
15 |
+
- images/arvalis_3
|
16 |
+
- images/ethz_1
|
17 |
+
- images/rres_1
|
18 |
+
- images/inrae_1
|
19 |
+
- images/usask_1
|
20 |
+
val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
|
21 |
+
- images/ethz_1
|
22 |
+
test: # test images (optional) 1276 images
|
23 |
+
- images/utokyo_1
|
24 |
+
- images/utokyo_2
|
25 |
+
- images/nau_1
|
26 |
+
- images/uq_1
|
27 |
+
|
28 |
+
# Classes
|
29 |
+
nc: 1 # number of classes
|
30 |
+
names: ['wheat_head'] # class names
|
31 |
+
|
32 |
+
|
33 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
34 |
+
download: |
|
35 |
+
from utils.general import download, Path
|
36 |
+
|
37 |
+
# Download
|
38 |
+
dir = Path(yaml['path']) # dataset root dir
|
39 |
+
urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
|
40 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
|
41 |
+
download(urls, dir=dir)
|
42 |
+
|
43 |
+
# Make Directories
|
44 |
+
for p in 'annotations', 'images', 'labels':
|
45 |
+
(dir / p).mkdir(parents=True, exist_ok=True)
|
46 |
+
|
47 |
+
# Move
|
48 |
+
for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
|
49 |
+
'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
|
50 |
+
(dir / p).rename(dir / 'images' / p) # move to /images
|
51 |
+
f = (dir / p).with_suffix('.json') # json file
|
52 |
+
if f.exists():
|
53 |
+
f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
|
yolov5/data/Objects365.yaml
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Objects365 dataset https://www.objects365.org/ by Megvii
|
3 |
+
# Example usage: python train.py --data Objects365.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── Objects365 ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/Objects365 # dataset root dir
|
12 |
+
train: images/train # train images (relative to 'path') 1742289 images
|
13 |
+
val: images/val # val images (relative to 'path') 80000 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 365 # number of classes
|
18 |
+
names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup',
|
19 |
+
'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book',
|
20 |
+
'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag',
|
21 |
+
'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV',
|
22 |
+
'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle',
|
23 |
+
'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird',
|
24 |
+
'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck',
|
25 |
+
'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning',
|
26 |
+
'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife',
|
27 |
+
'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock',
|
28 |
+
'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish',
|
29 |
+
'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan',
|
30 |
+
'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard',
|
31 |
+
'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign',
|
32 |
+
'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat',
|
33 |
+
'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard',
|
34 |
+
'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry',
|
35 |
+
'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks',
|
36 |
+
'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors',
|
37 |
+
'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape',
|
38 |
+
'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck',
|
39 |
+
'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette',
|
40 |
+
'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket',
|
41 |
+
'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine',
|
42 |
+
'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine',
|
43 |
+
'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon',
|
44 |
+
'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse',
|
45 |
+
'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball',
|
46 |
+
'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin',
|
47 |
+
'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts',
|
48 |
+
'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit',
|
49 |
+
'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD',
|
50 |
+
'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder',
|
51 |
+
'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips',
|
52 |
+
'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab',
|
53 |
+
'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal',
|
54 |
+
'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart',
|
55 |
+
'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French',
|
56 |
+
'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell',
|
57 |
+
'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil',
|
58 |
+
'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis']
|
59 |
+
|
60 |
+
|
61 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
62 |
+
download: |
|
63 |
+
from pycocotools.coco import COCO
|
64 |
+
from tqdm import tqdm
|
65 |
+
|
66 |
+
from utils.general import Path, download, np, xyxy2xywhn
|
67 |
+
|
68 |
+
# Make Directories
|
69 |
+
dir = Path(yaml['path']) # dataset root dir
|
70 |
+
for p in 'images', 'labels':
|
71 |
+
(dir / p).mkdir(parents=True, exist_ok=True)
|
72 |
+
for q in 'train', 'val':
|
73 |
+
(dir / p / q).mkdir(parents=True, exist_ok=True)
|
74 |
+
|
75 |
+
# Train, Val Splits
|
76 |
+
for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:
|
77 |
+
print(f"Processing {split} in {patches} patches ...")
|
78 |
+
images, labels = dir / 'images' / split, dir / 'labels' / split
|
79 |
+
|
80 |
+
# Download
|
81 |
+
url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/"
|
82 |
+
if split == 'train':
|
83 |
+
download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json
|
84 |
+
download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8)
|
85 |
+
elif split == 'val':
|
86 |
+
download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json
|
87 |
+
download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8)
|
88 |
+
download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8)
|
89 |
+
|
90 |
+
# Move
|
91 |
+
for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):
|
92 |
+
f.rename(images / f.name) # move to /images/{split}
|
93 |
+
|
94 |
+
# Labels
|
95 |
+
coco = COCO(dir / f'zhiyuan_objv2_{split}.json')
|
96 |
+
names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
|
97 |
+
for cid, cat in enumerate(names):
|
98 |
+
catIds = coco.getCatIds(catNms=[cat])
|
99 |
+
imgIds = coco.getImgIds(catIds=catIds)
|
100 |
+
for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
|
101 |
+
width, height = im["width"], im["height"]
|
102 |
+
path = Path(im["file_name"]) # image filename
|
103 |
+
try:
|
104 |
+
with open(labels / path.with_suffix('.txt').name, 'a') as file:
|
105 |
+
annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
|
106 |
+
for a in coco.loadAnns(annIds):
|
107 |
+
x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
|
108 |
+
xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4)
|
109 |
+
x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped
|
110 |
+
file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n")
|
111 |
+
except Exception as e:
|
112 |
+
print(e)
|
yolov5/data/SKU-110K.yaml
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail
|
3 |
+
# Example usage: python train.py --data SKU-110K.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── SKU-110K ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/SKU-110K # dataset root dir
|
12 |
+
train: train.txt # train images (relative to 'path') 8219 images
|
13 |
+
val: val.txt # val images (relative to 'path') 588 images
|
14 |
+
test: test.txt # test images (optional) 2936 images
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 1 # number of classes
|
18 |
+
names: ['object'] # class names
|
19 |
+
|
20 |
+
|
21 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
22 |
+
download: |
|
23 |
+
import shutil
|
24 |
+
from tqdm import tqdm
|
25 |
+
from utils.general import np, pd, Path, download, xyxy2xywh
|
26 |
+
|
27 |
+
# Download
|
28 |
+
dir = Path(yaml['path']) # dataset root dir
|
29 |
+
parent = Path(dir.parent) # download dir
|
30 |
+
urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
|
31 |
+
download(urls, dir=parent, delete=False)
|
32 |
+
|
33 |
+
# Rename directories
|
34 |
+
if dir.exists():
|
35 |
+
shutil.rmtree(dir)
|
36 |
+
(parent / 'SKU110K_fixed').rename(dir) # rename dir
|
37 |
+
(dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
|
38 |
+
|
39 |
+
# Convert labels
|
40 |
+
names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
|
41 |
+
for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
|
42 |
+
x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
|
43 |
+
images, unique_images = x[:, 0], np.unique(x[:, 0])
|
44 |
+
with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
|
45 |
+
f.writelines(f'./images/{s}\n' for s in unique_images)
|
46 |
+
for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
|
47 |
+
cls = 0 # single-class dataset
|
48 |
+
with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
|
49 |
+
for r in x[images == im]:
|
50 |
+
w, h = r[6], r[7] # image width, height
|
51 |
+
xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
|
52 |
+
f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
|
yolov5/data/VOC.yaml
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford
|
3 |
+
# Example usage: python train.py --data VOC.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── VOC ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/VOC
|
12 |
+
train: # train images (relative to 'path') 16551 images
|
13 |
+
- images/train2012
|
14 |
+
- images/train2007
|
15 |
+
- images/val2012
|
16 |
+
- images/val2007
|
17 |
+
val: # val images (relative to 'path') 4952 images
|
18 |
+
- images/test2007
|
19 |
+
test: # test images (optional)
|
20 |
+
- images/test2007
|
21 |
+
|
22 |
+
# Classes
|
23 |
+
nc: 20 # number of classes
|
24 |
+
names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
|
25 |
+
'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names
|
26 |
+
|
27 |
+
|
28 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
29 |
+
download: |
|
30 |
+
import xml.etree.ElementTree as ET
|
31 |
+
|
32 |
+
from tqdm import tqdm
|
33 |
+
from utils.general import download, Path
|
34 |
+
|
35 |
+
|
36 |
+
def convert_label(path, lb_path, year, image_id):
|
37 |
+
def convert_box(size, box):
|
38 |
+
dw, dh = 1. / size[0], 1. / size[1]
|
39 |
+
x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
|
40 |
+
return x * dw, y * dh, w * dw, h * dh
|
41 |
+
|
42 |
+
in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
|
43 |
+
out_file = open(lb_path, 'w')
|
44 |
+
tree = ET.parse(in_file)
|
45 |
+
root = tree.getroot()
|
46 |
+
size = root.find('size')
|
47 |
+
w = int(size.find('width').text)
|
48 |
+
h = int(size.find('height').text)
|
49 |
+
|
50 |
+
for obj in root.iter('object'):
|
51 |
+
cls = obj.find('name').text
|
52 |
+
if cls in yaml['names'] and not int(obj.find('difficult').text) == 1:
|
53 |
+
xmlbox = obj.find('bndbox')
|
54 |
+
bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
|
55 |
+
cls_id = yaml['names'].index(cls) # class id
|
56 |
+
out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
|
57 |
+
|
58 |
+
|
59 |
+
# Download
|
60 |
+
dir = Path(yaml['path']) # dataset root dir
|
61 |
+
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
62 |
+
urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
|
63 |
+
url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
|
64 |
+
url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
|
65 |
+
download(urls, dir=dir / 'images', delete=False)
|
66 |
+
|
67 |
+
# Convert
|
68 |
+
path = dir / f'images/VOCdevkit'
|
69 |
+
for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
|
70 |
+
imgs_path = dir / 'images' / f'{image_set}{year}'
|
71 |
+
lbs_path = dir / 'labels' / f'{image_set}{year}'
|
72 |
+
imgs_path.mkdir(exist_ok=True, parents=True)
|
73 |
+
lbs_path.mkdir(exist_ok=True, parents=True)
|
74 |
+
|
75 |
+
image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split()
|
76 |
+
for id in tqdm(image_ids, desc=f'{image_set}{year}'):
|
77 |
+
f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
|
78 |
+
lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
|
79 |
+
f.rename(imgs_path / f.name) # move image
|
80 |
+
convert_label(path, lb_path, year, id) # convert labels to YOLO format
|
yolov5/data/VisDrone.yaml
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University
|
3 |
+
# Example usage: python train.py --data VisDrone.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── VisDrone ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/VisDrone # dataset root dir
|
12 |
+
train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
|
13 |
+
val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
|
14 |
+
test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 10 # number of classes
|
18 |
+
names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor']
|
19 |
+
|
20 |
+
|
21 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
22 |
+
download: |
|
23 |
+
from utils.general import download, os, Path
|
24 |
+
|
25 |
+
def visdrone2yolo(dir):
|
26 |
+
from PIL import Image
|
27 |
+
from tqdm import tqdm
|
28 |
+
|
29 |
+
def convert_box(size, box):
|
30 |
+
# Convert VisDrone box to YOLO xywh box
|
31 |
+
dw = 1. / size[0]
|
32 |
+
dh = 1. / size[1]
|
33 |
+
return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
|
34 |
+
|
35 |
+
(dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
|
36 |
+
pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
|
37 |
+
for f in pbar:
|
38 |
+
img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
|
39 |
+
lines = []
|
40 |
+
with open(f, 'r') as file: # read annotation.txt
|
41 |
+
for row in [x.split(',') for x in file.read().strip().splitlines()]:
|
42 |
+
if row[4] == '0': # VisDrone 'ignored regions' class 0
|
43 |
+
continue
|
44 |
+
cls = int(row[5]) - 1
|
45 |
+
box = convert_box(img_size, tuple(map(int, row[:4])))
|
46 |
+
lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
|
47 |
+
with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
|
48 |
+
fl.writelines(lines) # write label.txt
|
49 |
+
|
50 |
+
|
51 |
+
# Download
|
52 |
+
dir = Path(yaml['path']) # dataset root dir
|
53 |
+
urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
|
54 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
|
55 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
|
56 |
+
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
|
57 |
+
download(urls, dir=dir)
|
58 |
+
|
59 |
+
# Convert
|
60 |
+
for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
|
61 |
+
visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
|
yolov5/data/coco.yaml
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# COCO 2017 dataset http://cocodataset.org by Microsoft
|
3 |
+
# Example usage: python train.py --data coco.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── coco ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/coco # dataset root dir
|
12 |
+
train: train2017.txt # train images (relative to 'path') 118287 images
|
13 |
+
val: val2017.txt # val images (relative to 'path') 5000 images
|
14 |
+
test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 80 # number of classes
|
18 |
+
names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
|
19 |
+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
|
20 |
+
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
|
21 |
+
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
|
22 |
+
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
|
23 |
+
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
|
24 |
+
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
|
25 |
+
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
|
26 |
+
'hair drier', 'toothbrush'] # class names
|
27 |
+
|
28 |
+
|
29 |
+
# Download script/URL (optional)
|
30 |
+
download: |
|
31 |
+
from utils.general import download, Path
|
32 |
+
|
33 |
+
# Download labels
|
34 |
+
segments = False # segment or box labels
|
35 |
+
dir = Path(yaml['path']) # dataset root dir
|
36 |
+
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
37 |
+
urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
|
38 |
+
download(urls, dir=dir.parent)
|
39 |
+
|
40 |
+
# Download data
|
41 |
+
urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
|
42 |
+
'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
|
43 |
+
'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
|
44 |
+
download(urls, dir=dir / 'images', threads=3)
|
yolov5/data/coco128.yaml
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics
|
3 |
+
# Example usage: python train.py --data coco128.yaml
|
4 |
+
# parent
|
5 |
+
# ├── yolov5
|
6 |
+
# └── datasets
|
7 |
+
# └── coco128 ← downloads here
|
8 |
+
|
9 |
+
|
10 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
11 |
+
path: ../datasets/coco128 # dataset root dir
|
12 |
+
train: images/train2017 # train images (relative to 'path') 128 images
|
13 |
+
val: images/train2017 # val images (relative to 'path') 128 images
|
14 |
+
test: # test images (optional)
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 80 # number of classes
|
18 |
+
names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
|
19 |
+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
|
20 |
+
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
|
21 |
+
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
|
22 |
+
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
|
23 |
+
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
|
24 |
+
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
|
25 |
+
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
|
26 |
+
'hair drier', 'toothbrush'] # class names
|
27 |
+
|
28 |
+
|
29 |
+
# Download script/URL (optional)
|
30 |
+
download: https://ultralytics.com/assets/coco128.zip
|
yolov5/data/hyps/hyp.finetune.yaml
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for VOC finetuning
|
3 |
+
# python train.py --batch 64 --weights yolov5m.pt --data VOC.yaml --img 512 --epochs 50
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
# Hyperparameter Evolution Results
|
7 |
+
# Generations: 306
|
8 |
+
# P R mAP.5 mAP.5:.95 box obj cls
|
9 |
+
# Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146
|
10 |
+
|
11 |
+
lr0: 0.0032
|
12 |
+
lrf: 0.12
|
13 |
+
momentum: 0.843
|
14 |
+
weight_decay: 0.00036
|
15 |
+
warmup_epochs: 2.0
|
16 |
+
warmup_momentum: 0.5
|
17 |
+
warmup_bias_lr: 0.05
|
18 |
+
box: 0.0296
|
19 |
+
cls: 0.243
|
20 |
+
cls_pw: 0.631
|
21 |
+
obj: 0.301
|
22 |
+
obj_pw: 0.911
|
23 |
+
iou_t: 0.2
|
24 |
+
anchor_t: 2.91
|
25 |
+
# anchors: 3.63
|
26 |
+
fl_gamma: 0.0
|
27 |
+
hsv_h: 0.0138
|
28 |
+
hsv_s: 0.664
|
29 |
+
hsv_v: 0.464
|
30 |
+
degrees: 0.373
|
31 |
+
translate: 0.245
|
32 |
+
scale: 0.898
|
33 |
+
shear: 0.602
|
34 |
+
perspective: 0.0
|
35 |
+
flipud: 0.00856
|
36 |
+
fliplr: 0.5
|
37 |
+
mosaic: 1.0
|
38 |
+
mixup: 0.243
|
39 |
+
copy_paste: 0.0
|
yolov5/data/hyps/hyp.finetune_objects365.yaml
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
lr0: 0.00258
|
4 |
+
lrf: 0.17
|
5 |
+
momentum: 0.779
|
6 |
+
weight_decay: 0.00058
|
7 |
+
warmup_epochs: 1.33
|
8 |
+
warmup_momentum: 0.86
|
9 |
+
warmup_bias_lr: 0.0711
|
10 |
+
box: 0.0539
|
11 |
+
cls: 0.299
|
12 |
+
cls_pw: 0.825
|
13 |
+
obj: 0.632
|
14 |
+
obj_pw: 1.0
|
15 |
+
iou_t: 0.2
|
16 |
+
anchor_t: 3.44
|
17 |
+
anchors: 3.2
|
18 |
+
fl_gamma: 0.0
|
19 |
+
hsv_h: 0.0188
|
20 |
+
hsv_s: 0.704
|
21 |
+
hsv_v: 0.36
|
22 |
+
degrees: 0.0
|
23 |
+
translate: 0.0902
|
24 |
+
scale: 0.491
|
25 |
+
shear: 0.0
|
26 |
+
perspective: 0.0
|
27 |
+
flipud: 0.0
|
28 |
+
fliplr: 0.5
|
29 |
+
mosaic: 1.0
|
30 |
+
mixup: 0.0
|
31 |
+
copy_paste: 0.0
|
yolov5/data/hyps/hyp.scratch-high.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for high-augmentation COCO training from scratch
|
3 |
+
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.3 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 0.7 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.9 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.1 # image mixup (probability)
|
34 |
+
copy_paste: 0.1 # segment copy-paste (probability)
|
yolov5/data/hyps/hyp.scratch-low.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for low-augmentation COCO training from scratch
|
3 |
+
# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.5 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 1.0 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.5 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.0 # image mixup (probability)
|
34 |
+
copy_paste: 0.0 # segment copy-paste (probability)
|
yolov5/data/hyps/hyp.scratch-med.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for medium-augmentation COCO training from scratch
|
3 |
+
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.3 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 0.7 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.9 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.1 # image mixup (probability)
|
34 |
+
copy_paste: 0.0 # segment copy-paste (probability)
|
yolov5/data/hyps/hyp.scratch.yaml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Hyperparameters for COCO training from scratch
|
3 |
+
# python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
|
4 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
5 |
+
|
6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
7 |
+
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
8 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
9 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
10 |
+
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
11 |
+
warmup_momentum: 0.8 # warmup initial momentum
|
12 |
+
warmup_bias_lr: 0.1 # warmup initial bias lr
|
13 |
+
box: 0.05 # box loss gain
|
14 |
+
cls: 0.5 # cls loss gain
|
15 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
16 |
+
obj: 1.0 # obj loss gain (scale with pixels)
|
17 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
18 |
+
iou_t: 0.20 # IoU training threshold
|
19 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
20 |
+
# anchors: 3 # anchors per output layer (0 to ignore)
|
21 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
22 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
23 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
24 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
25 |
+
degrees: 0.0 # image rotation (+/- deg)
|
26 |
+
translate: 0.1 # image translation (+/- fraction)
|
27 |
+
scale: 0.5 # image scale (+/- gain)
|
28 |
+
shear: 0.0 # image shear (+/- deg)
|
29 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
30 |
+
flipud: 0.0 # image flip up-down (probability)
|
31 |
+
fliplr: 0.5 # image flip left-right (probability)
|
32 |
+
mosaic: 1.0 # image mosaic (probability)
|
33 |
+
mixup: 0.0 # image mixup (probability)
|
34 |
+
copy_paste: 0.0 # segment copy-paste (probability)
|
yolov5/data/images/bus.jpg
ADDED
yolov5/data/images/zidane.jpg
ADDED
yolov5/data/scripts/download_weights.sh
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
3 |
+
# Download latest models from https://github.com/ultralytics/yolov5/releases
|
4 |
+
# Example usage: bash path/to/download_weights.sh
|
5 |
+
# parent
|
6 |
+
# └── yolov5
|
7 |
+
# ├── yolov5s.pt ← downloads here
|
8 |
+
# ├── yolov5m.pt
|
9 |
+
# └── ...
|
10 |
+
|
11 |
+
python - <<EOF
|
12 |
+
from utils.downloads import attempt_download
|
13 |
+
|
14 |
+
models = ['n', 's', 'm', 'l', 'x']
|
15 |
+
models.extend([x + '6' for x in models]) # add P6 models
|
16 |
+
|
17 |
+
for x in models:
|
18 |
+
attempt_download(f'yolov5{x}.pt')
|
19 |
+
|
20 |
+
EOF
|
yolov5/data/scripts/get_coco.sh
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
3 |
+
# Download COCO 2017 dataset http://cocodataset.org
|
4 |
+
# Example usage: bash data/scripts/get_coco.sh
|
5 |
+
# parent
|
6 |
+
# ├── yolov5
|
7 |
+
# └── datasets
|
8 |
+
# └── coco ← downloads here
|
9 |
+
|
10 |
+
# Download/unzip labels
|
11 |
+
d='../datasets' # unzip directory
|
12 |
+
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
13 |
+
f='coco2017labels.zip' # or 'coco2017labels-segments.zip', 68 MB
|
14 |
+
echo 'Downloading' $url$f ' ...'
|
15 |
+
curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &
|
16 |
+
|
17 |
+
# Download/unzip images
|
18 |
+
d='../datasets/coco/images' # unzip directory
|
19 |
+
url=http://images.cocodataset.org/zips/
|
20 |
+
f1='train2017.zip' # 19G, 118k images
|
21 |
+
f2='val2017.zip' # 1G, 5k images
|
22 |
+
f3='test2017.zip' # 7G, 41k images (optional)
|
23 |
+
for f in $f1 $f2; do
|
24 |
+
echo 'Downloading' $url$f '...'
|
25 |
+
curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &
|
26 |
+
done
|
27 |
+
wait # finish background tasks
|
yolov5/data/scripts/get_coco128.sh
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
3 |
+
# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
|
4 |
+
# Example usage: bash data/scripts/get_coco128.sh
|
5 |
+
# parent
|
6 |
+
# ├── yolov5
|
7 |
+
# └── datasets
|
8 |
+
# └── coco128 ← downloads here
|
9 |
+
|
10 |
+
# Download/unzip images and labels
|
11 |
+
d='../datasets' # unzip directory
|
12 |
+
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
13 |
+
f='coco128.zip' # or 'coco128-segments.zip', 68 MB
|
14 |
+
echo 'Downloading' $url$f ' ...'
|
15 |
+
curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &
|
16 |
+
|
17 |
+
wait # finish background tasks
|
yolov5/data/xView.yaml
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# DIUx xView 2018 Challenge https://challenge.xviewdataset.org by U.S. National Geospatial-Intelligence Agency (NGA)
|
3 |
+
# -------- DOWNLOAD DATA MANUALLY and jar xf val_images.zip to 'datasets/xView' before running train command! --------
|
4 |
+
# Example usage: python train.py --data xView.yaml
|
5 |
+
# parent
|
6 |
+
# ├── yolov5
|
7 |
+
# └── datasets
|
8 |
+
# └── xView ← downloads here
|
9 |
+
|
10 |
+
|
11 |
+
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
12 |
+
path: ../datasets/xView # dataset root dir
|
13 |
+
train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images
|
14 |
+
val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images
|
15 |
+
|
16 |
+
# Classes
|
17 |
+
nc: 60 # number of classes
|
18 |
+
names: ['Fixed-wing Aircraft', 'Small Aircraft', 'Cargo Plane', 'Helicopter', 'Passenger Vehicle', 'Small Car', 'Bus',
|
19 |
+
'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck w/Box', 'Truck Tractor', 'Trailer',
|
20 |
+
'Truck w/Flatbed', 'Truck w/Liquid', 'Crane Truck', 'Railway Vehicle', 'Passenger Car', 'Cargo Car',
|
21 |
+
'Flat Car', 'Tank car', 'Locomotive', 'Maritime Vessel', 'Motorboat', 'Sailboat', 'Tugboat', 'Barge',
|
22 |
+
'Fishing Vessel', 'Ferry', 'Yacht', 'Container Ship', 'Oil Tanker', 'Engineering Vehicle', 'Tower crane',
|
23 |
+
'Container Crane', 'Reach Stacker', 'Straddle Carrier', 'Mobile Crane', 'Dump Truck', 'Haul Truck',
|
24 |
+
'Scraper/Tractor', 'Front loader/Bulldozer', 'Excavator', 'Cement Mixer', 'Ground Grader', 'Hut/Tent', 'Shed',
|
25 |
+
'Building', 'Aircraft Hangar', 'Damaged Building', 'Facility', 'Construction Site', 'Vehicle Lot', 'Helipad',
|
26 |
+
'Storage Tank', 'Shipping container lot', 'Shipping Container', 'Pylon', 'Tower'] # class names
|
27 |
+
|
28 |
+
|
29 |
+
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
30 |
+
download: |
|
31 |
+
import json
|
32 |
+
import os
|
33 |
+
from pathlib import Path
|
34 |
+
|
35 |
+
import numpy as np
|
36 |
+
from PIL import Image
|
37 |
+
from tqdm import tqdm
|
38 |
+
|
39 |
+
from utils.datasets import autosplit
|
40 |
+
from utils.general import download, xyxy2xywhn
|
41 |
+
|
42 |
+
|
43 |
+
def convert_labels(fname=Path('xView/xView_train.geojson')):
|
44 |
+
# Convert xView geoJSON labels to YOLO format
|
45 |
+
path = fname.parent
|
46 |
+
with open(fname) as f:
|
47 |
+
print(f'Loading {fname}...')
|
48 |
+
data = json.load(f)
|
49 |
+
|
50 |
+
# Make dirs
|
51 |
+
labels = Path(path / 'labels' / 'train')
|
52 |
+
os.system(f'rm -rf {labels}')
|
53 |
+
labels.mkdir(parents=True, exist_ok=True)
|
54 |
+
|
55 |
+
# xView classes 11-94 to 0-59
|
56 |
+
xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11,
|
57 |
+
12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,
|
58 |
+
29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,
|
59 |
+
47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]
|
60 |
+
|
61 |
+
shapes = {}
|
62 |
+
for feature in tqdm(data['features'], desc=f'Converting {fname}'):
|
63 |
+
p = feature['properties']
|
64 |
+
if p['bounds_imcoords']:
|
65 |
+
id = p['image_id']
|
66 |
+
file = path / 'train_images' / id
|
67 |
+
if file.exists(): # 1395.tif missing
|
68 |
+
try:
|
69 |
+
box = np.array([int(num) for num in p['bounds_imcoords'].split(",")])
|
70 |
+
assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'
|
71 |
+
cls = p['type_id']
|
72 |
+
cls = xview_class2index[int(cls)] # xView class to 0-60
|
73 |
+
assert 59 >= cls >= 0, f'incorrect class index {cls}'
|
74 |
+
|
75 |
+
# Write YOLO label
|
76 |
+
if id not in shapes:
|
77 |
+
shapes[id] = Image.open(file).size
|
78 |
+
box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)
|
79 |
+
with open((labels / id).with_suffix('.txt'), 'a') as f:
|
80 |
+
f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt
|
81 |
+
except Exception as e:
|
82 |
+
print(f'WARNING: skipping one label for {file}: {e}')
|
83 |
+
|
84 |
+
|
85 |
+
# Download manually from https://challenge.xviewdataset.org
|
86 |
+
dir = Path(yaml['path']) # dataset root dir
|
87 |
+
# urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels
|
88 |
+
# 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images
|
89 |
+
# 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels)
|
90 |
+
# download(urls, dir=dir, delete=False)
|
91 |
+
|
92 |
+
# Convert labels
|
93 |
+
convert_labels(dir / 'xView_train.geojson')
|
94 |
+
|
95 |
+
# Move images
|
96 |
+
images = Path(dir / 'images')
|
97 |
+
images.mkdir(parents=True, exist_ok=True)
|
98 |
+
Path(dir / 'train_images').rename(dir / 'images' / 'train')
|
99 |
+
Path(dir / 'val_images').rename(dir / 'images' / 'val')
|
100 |
+
|
101 |
+
# Split
|
102 |
+
autosplit(dir / 'images' / 'train')
|
yolov5/detect.py
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
from pathlib import Path
|
6 |
+
import cv2
|
7 |
+
|
8 |
+
FILE = Path(__file__).resolve()
|
9 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
10 |
+
if str(ROOT) not in sys.path:
|
11 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
12 |
+
|
13 |
+
|
14 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
15 |
+
|
16 |
+
import torch
|
17 |
+
from yolov5.utils.torch_utils import select_device, time_sync
|
18 |
+
from yolov5.utils.plots import Annotator, colors, save_one_box
|
19 |
+
from yolov5.utils.general import (check_img_size,
|
20 |
+
increment_path, non_max_suppression, scale_coords, xyxy2xywh)
|
21 |
+
from yolov5.utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages
|
22 |
+
from yolov5.models.common import DetectMultiBackend
|
23 |
+
|
24 |
+
def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s)
|
25 |
+
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
|
26 |
+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
27 |
+
imgsz=(640, 640), # inference size (height, width)
|
28 |
+
conf_thres=0.25, # confidence threshold
|
29 |
+
iou_thres=0.45, # NMS IOU threshold
|
30 |
+
max_det=1000, # maximum detections per image
|
31 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
32 |
+
save_img = False,
|
33 |
+
view_img=False, # show results
|
34 |
+
save_txt=False, # save results to *.txt
|
35 |
+
save_conf=False, # save confidences in --save-txt labels
|
36 |
+
save_crop=False, # save cropped prediction boxes
|
37 |
+
nosave=False, # do not save images/videos
|
38 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
39 |
+
agnostic_nms=False, # class-agnostic NMS
|
40 |
+
augment=False, # augmented inference
|
41 |
+
visualize=False, # visualize features
|
42 |
+
update=False, # update all models
|
43 |
+
project=ROOT / 'runs/detect', # save results to project/name
|
44 |
+
name='exp', # save results to project/name
|
45 |
+
exist_ok=False, # existing project/name ok, do not increment
|
46 |
+
line_thickness=3, # bounding box thickness (pixels)
|
47 |
+
hide_labels=False, # hide labels
|
48 |
+
hide_conf=False, # hide confidences
|
49 |
+
half=False, # use FP16 half-precision inference
|
50 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
51 |
+
):
|
52 |
+
|
53 |
+
import torch
|
54 |
+
from utils.torch_utils import select_device, time_sync
|
55 |
+
from utils.plots import Annotator, colors, save_one_box
|
56 |
+
from utils.general import (check_img_size,
|
57 |
+
increment_path, non_max_suppression, scale_coords, xyxy2xywh)
|
58 |
+
from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages
|
59 |
+
from models.common import DetectMultiBackend
|
60 |
+
source = str(source)
|
61 |
+
|
62 |
+
save_dir = None
|
63 |
+
save_path = None
|
64 |
+
# save_img = not nosave and not source.endswith('.txt') # save inference images
|
65 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
66 |
+
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
67 |
+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
68 |
+
|
69 |
+
# Directories
|
70 |
+
if project is not None:
|
71 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
72 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
73 |
+
|
74 |
+
# Load model
|
75 |
+
device = select_device(device)
|
76 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)
|
77 |
+
stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
|
78 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
79 |
+
|
80 |
+
# Half
|
81 |
+
half &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16 supported on limited backends with CUDA
|
82 |
+
if pt or jit:
|
83 |
+
model.model.half() if half else model.model.float()
|
84 |
+
|
85 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
|
86 |
+
bs = 1 # batch_size
|
87 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
88 |
+
|
89 |
+
# Run inference
|
90 |
+
model.warmup(imgsz=(1, 3, *imgsz), half=half) # warmup
|
91 |
+
dt, seen = [0.0, 0.0, 0.0], 0
|
92 |
+
|
93 |
+
#with tqdm(dataset) as pbar:
|
94 |
+
# pbar.set_description("Document Image Analysis")
|
95 |
+
for path, im, im0s, vid_cap, s in dataset:
|
96 |
+
#print(path)
|
97 |
+
t1 = time_sync()
|
98 |
+
im = torch.from_numpy(im).to(device)
|
99 |
+
im = im.half() if half else im.float() # uint8 to fp16/32
|
100 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
101 |
+
if len(im.shape) == 3:
|
102 |
+
im = im[None] # expand for batch dim
|
103 |
+
t2 = time_sync()
|
104 |
+
dt[0] += t2 - t1
|
105 |
+
|
106 |
+
# Inference
|
107 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
108 |
+
pred = model(im, augment=augment, visualize=visualize)
|
109 |
+
t3 = time_sync()
|
110 |
+
dt[1] += t3 - t2
|
111 |
+
|
112 |
+
# NMS
|
113 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
114 |
+
dt[2] += time_sync() - t3
|
115 |
+
|
116 |
+
# Second-stage classifier (optional)
|
117 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
118 |
+
|
119 |
+
# Process predictions
|
120 |
+
preds = []
|
121 |
+
for i, det in enumerate(pred): # per image
|
122 |
+
seen += 1
|
123 |
+
if webcam: # batch_size >= 1
|
124 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
125 |
+
s += f'{i}: '
|
126 |
+
else:
|
127 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
|
128 |
+
|
129 |
+
p = Path(p) # to Path
|
130 |
+
if save_dir is not None:
|
131 |
+
save_path = str(save_dir / p.name) # im.jpg
|
132 |
+
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
|
133 |
+
s += '%gx%g ' % im.shape[2:] # print string
|
134 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
135 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
136 |
+
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
137 |
+
if len(det):
|
138 |
+
# Rescale boxes from img_size to im0 size
|
139 |
+
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
|
140 |
+
|
141 |
+
# Print results
|
142 |
+
for c in det[:, -1].unique():
|
143 |
+
n = (det[:, -1] == c).sum() # detections per class
|
144 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
145 |
+
|
146 |
+
# Write results
|
147 |
+
if save_txt:
|
148 |
+
with open(txt_path + '.txt', 'w') as f:
|
149 |
+
for *xyxy, conf, cls in reversed(det):
|
150 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
151 |
+
preds.append({"class": str(int(cls)), "xmin": int(xyxy[0]), "ymin": int(xyxy[1]), "xmax": int(xyxy[2]),"ymax": int(xyxy[3]), "conf": float(conf)})
|
152 |
+
if save_txt: # Write to file
|
153 |
+
line = (int(cls), *xywh, conf) if save_conf else (cls, *xywh) # label format
|
154 |
+
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
155 |
+
|
156 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
157 |
+
c = int(cls) # integer class
|
158 |
+
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
|
159 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
160 |
+
if save_crop:
|
161 |
+
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
|
162 |
+
else:
|
163 |
+
for *xyxy, conf, cls in reversed(det):
|
164 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
165 |
+
preds.append({"class": str(int(cls)), "xmin": int(xyxy[0]), "ymin": int(xyxy[1]), "xmax": int(xyxy[2]),"ymax": int(xyxy[3]), "conf": float(conf)})
|
166 |
+
|
167 |
+
# Print time (inference-only)
|
168 |
+
# LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
|
169 |
+
|
170 |
+
# Stream results
|
171 |
+
if save_img:
|
172 |
+
im0 = annotator.result()
|
173 |
+
if view_img:
|
174 |
+
cv2.imshow(str(p), im0)
|
175 |
+
cv2.waitKey(1) # 1 millisecond
|
176 |
+
|
177 |
+
# Save results (image with detections)
|
178 |
+
if save_img:
|
179 |
+
if dataset.mode == 'image':
|
180 |
+
cv2.imwrite(save_path, im0)
|
181 |
+
else: # 'video' or 'stream'
|
182 |
+
if vid_path[i] != save_path: # new video
|
183 |
+
vid_path[i] = save_path
|
184 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
185 |
+
vid_writer[i].release() # release previous video writer
|
186 |
+
if vid_cap: # video
|
187 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
188 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
189 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
190 |
+
else: # stream
|
191 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
192 |
+
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
|
193 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
194 |
+
vid_writer[i].write(im0)
|
195 |
+
yield preds, save_path
|
196 |
+
# Print results
|
197 |
+
#t = tuple(x / seen * 1E3 for x in dt) # speeds per image
|
198 |
+
#LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
|
199 |
+
""" if save_txt or save_img:
|
200 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
201 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
202 |
+
if update:
|
203 |
+
strip_optimizer(weights) # update model (to fix SourceChangeWarning) """
|
204 |
+
|
205 |
+
|
206 |
+
def load_yolo_model(weights, device="cpu", imgsz=[1280, 1280]):
|
207 |
+
# Load model
|
208 |
+
device = select_device(device)
|
209 |
+
model = DetectMultiBackend(weights, device=device, dnn=False, data=ROOT / 'data/coco128.yaml')
|
210 |
+
stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
|
211 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
212 |
+
|
213 |
+
half = False
|
214 |
+
# Half
|
215 |
+
half &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16 supported on limited backends with CUDA
|
216 |
+
if pt or jit:
|
217 |
+
model.model.half() if half else model.model.float()
|
218 |
+
model.warmup(imgsz=(1, 3, *imgsz), half=half)
|
219 |
+
|
220 |
+
return model, stride, names, pt, jit, onnx, engine
|
221 |
+
|
222 |
+
|
223 |
+
def predict(model, # model.pt path(s)
|
224 |
+
stride, names, pt, jit, onnx, engine,
|
225 |
+
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
|
226 |
+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
227 |
+
imgsz=(640, 640), # inference size (height, width)
|
228 |
+
conf_thres=0.5, # confidence threshold
|
229 |
+
iou_thres=0.45, # NMS IOU threshold
|
230 |
+
max_det=1000, # maximum detections per image
|
231 |
+
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
232 |
+
save_img = False,
|
233 |
+
view_img=False, # show results
|
234 |
+
save_txt=False, # save results to *.txt
|
235 |
+
save_conf=False, # save confidences in --save-txt labels
|
236 |
+
save_crop=False, # save cropped prediction boxes
|
237 |
+
nosave=False, # do not save images/videos
|
238 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
239 |
+
agnostic_nms=False, # class-agnostic NMS
|
240 |
+
augment=False, # augmented inference
|
241 |
+
visualize=False, # visualize features
|
242 |
+
update=False, # update all models
|
243 |
+
project=ROOT / 'runs/detect', # save results to project/name
|
244 |
+
name='exp', # save results to project/name
|
245 |
+
exist_ok=False, # existing project/name ok, do not increment
|
246 |
+
line_thickness=3, # bounding box thickness (pixels)
|
247 |
+
hide_labels=False, # hide labels
|
248 |
+
hide_conf=False, # hide confidences
|
249 |
+
half=False, # use FP16 half-precision inference
|
250 |
+
dnn=False, # use OpenCV DNN for ONNX inference
|
251 |
+
|
252 |
+
):
|
253 |
+
|
254 |
+
|
255 |
+
source = str(source)
|
256 |
+
|
257 |
+
save_dir = None
|
258 |
+
save_path = None
|
259 |
+
# save_img = not nosave and not source.endswith('.txt') # save inference images
|
260 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
261 |
+
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
262 |
+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
263 |
+
|
264 |
+
# Directories
|
265 |
+
if project is not None:
|
266 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
267 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
268 |
+
|
269 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
|
270 |
+
#bs = 1 # batch_size
|
271 |
+
#vid_path, vid_writer = [None] * bs, [None] * bs
|
272 |
+
|
273 |
+
# Run inference
|
274 |
+
|
275 |
+
dt, seen = [0.0, 0.0, 0.0], 0
|
276 |
+
|
277 |
+
#with tqdm(dataset) as pbar:
|
278 |
+
# pbar.set_description("Document Image Analysis")
|
279 |
+
for path, im, im0s, vid_cap, s in dataset:
|
280 |
+
#print(path)
|
281 |
+
t1 = time_sync()
|
282 |
+
im = torch.from_numpy(im).to(device)
|
283 |
+
im = im.half() if half else im.float() # uint8 to fp16/32
|
284 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
285 |
+
if len(im.shape) == 3:
|
286 |
+
im = im[None] # expand for batch dim
|
287 |
+
t2 = time_sync()
|
288 |
+
dt[0] += t2 - t1
|
289 |
+
|
290 |
+
# Inference
|
291 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
292 |
+
pred = model(im, augment=augment, visualize=visualize)
|
293 |
+
t3 = time_sync()
|
294 |
+
dt[1] += t3 - t2
|
295 |
+
|
296 |
+
# NMS
|
297 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
298 |
+
dt[2] += time_sync() - t3
|
299 |
+
|
300 |
+
# Second-stage classifier (optional)
|
301 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
302 |
+
|
303 |
+
# Process predictions
|
304 |
+
preds = []
|
305 |
+
for i, det in enumerate(pred): # per image
|
306 |
+
seen += 1
|
307 |
+
if webcam: # batch_size >= 1
|
308 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
309 |
+
s += f'{i}: '
|
310 |
+
else:
|
311 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
|
312 |
+
|
313 |
+
p = Path(p) # to Path
|
314 |
+
|
315 |
+
#s += '%gx%g ' % im.shape[2:] # print string
|
316 |
+
# gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
317 |
+
#imc = im0.copy() if save_crop else im0 # for save_crop
|
318 |
+
#annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
319 |
+
if len(det):
|
320 |
+
# Rescale boxes from img_size to im0 size
|
321 |
+
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
|
322 |
+
|
323 |
+
# Print results
|
324 |
+
""" for c in det[:, -1].unique():
|
325 |
+
n = (det[:, -1] == c).sum() # detections per class
|
326 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string """
|
327 |
+
|
328 |
+
for *xyxy, conf, cls in reversed(det):
|
329 |
+
# xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
330 |
+
preds.append({"class": str(int(cls)), "xmin": int(xyxy[0]), "ymin": int(xyxy[1]), "xmax": int(xyxy[2]),"ymax": int(xyxy[3]), "conf": float(conf)})
|
331 |
+
|
332 |
+
yield preds, save_path
|
yolov5/export.py
ADDED
@@ -0,0 +1,564 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import platform
|
5 |
+
import subprocess
|
6 |
+
import sys
|
7 |
+
import time
|
8 |
+
import warnings
|
9 |
+
from pathlib import Path
|
10 |
+
|
11 |
+
import pandas as pd
|
12 |
+
import torch
|
13 |
+
import yaml
|
14 |
+
from torch.utils.mobile_optimizer import optimize_for_mobile
|
15 |
+
|
16 |
+
FILE = Path(__file__).resolve()
|
17 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
18 |
+
if str(ROOT) not in sys.path:
|
19 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
20 |
+
if platform.system() != 'Windows':
|
21 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
22 |
+
|
23 |
+
from models.experimental import attempt_load
|
24 |
+
from models.yolo import Detect
|
25 |
+
from utils.datasets import LoadImages
|
26 |
+
from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
|
27 |
+
file_size, print_args, url2file)
|
28 |
+
from utils.torch_utils import select_device
|
29 |
+
|
30 |
+
|
31 |
+
def export_formats():
|
32 |
+
# YOLOv5 export formats
|
33 |
+
x = [
|
34 |
+
['PyTorch', '-', '.pt', True, True],
|
35 |
+
['TorchScript', 'torchscript', '.torchscript', True, True],
|
36 |
+
['ONNX', 'onnx', '.onnx', True, True],
|
37 |
+
['OpenVINO', 'openvino', '_openvino_model', True, False],
|
38 |
+
['TensorRT', 'engine', '.engine', False, True],
|
39 |
+
['CoreML', 'coreml', '.mlmodel', True, False],
|
40 |
+
['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
|
41 |
+
['TensorFlow GraphDef', 'pb', '.pb', True, True],
|
42 |
+
['TensorFlow Lite', 'tflite', '.tflite', True, False],
|
43 |
+
['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
|
44 |
+
['TensorFlow.js', 'tfjs', '_web_model', False, False],]
|
45 |
+
return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
|
46 |
+
|
47 |
+
|
48 |
+
def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
|
49 |
+
# YOLOv5 TorchScript model export
|
50 |
+
try:
|
51 |
+
LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
|
52 |
+
f = file.with_suffix('.torchscript')
|
53 |
+
|
54 |
+
ts = torch.jit.trace(model, im, strict=False)
|
55 |
+
d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
|
56 |
+
extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
|
57 |
+
if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
|
58 |
+
optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
|
59 |
+
else:
|
60 |
+
ts.save(str(f), _extra_files=extra_files)
|
61 |
+
|
62 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
63 |
+
return f
|
64 |
+
except Exception as e:
|
65 |
+
LOGGER.info(f'{prefix} export failure: {e}')
|
66 |
+
|
67 |
+
|
68 |
+
def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
|
69 |
+
# YOLOv5 ONNX export
|
70 |
+
try:
|
71 |
+
check_requirements(('onnx',))
|
72 |
+
import onnx
|
73 |
+
|
74 |
+
LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
|
75 |
+
f = file.with_suffix('.onnx')
|
76 |
+
|
77 |
+
torch.onnx.export(
|
78 |
+
model.cpu() if dynamic else model, # --dynamic only compatible with cpu
|
79 |
+
im.cpu() if dynamic else im,
|
80 |
+
f,
|
81 |
+
verbose=False,
|
82 |
+
opset_version=opset,
|
83 |
+
training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
|
84 |
+
do_constant_folding=not train,
|
85 |
+
input_names=['images'],
|
86 |
+
output_names=['output'],
|
87 |
+
dynamic_axes={
|
88 |
+
'images': {
|
89 |
+
0: 'batch',
|
90 |
+
2: 'height',
|
91 |
+
3: 'width'}, # shape(1,3,640,640)
|
92 |
+
'output': {
|
93 |
+
0: 'batch',
|
94 |
+
1: 'anchors'} # shape(1,25200,85)
|
95 |
+
} if dynamic else None)
|
96 |
+
|
97 |
+
# Checks
|
98 |
+
model_onnx = onnx.load(f) # load onnx model
|
99 |
+
onnx.checker.check_model(model_onnx) # check onnx model
|
100 |
+
|
101 |
+
# Metadata
|
102 |
+
d = {'stride': int(max(model.stride)), 'names': model.names}
|
103 |
+
for k, v in d.items():
|
104 |
+
meta = model_onnx.metadata_props.add()
|
105 |
+
meta.key, meta.value = k, str(v)
|
106 |
+
onnx.save(model_onnx, f)
|
107 |
+
|
108 |
+
# Simplify
|
109 |
+
if simplify:
|
110 |
+
try:
|
111 |
+
check_requirements(('onnx-simplifier',))
|
112 |
+
import onnxsim
|
113 |
+
|
114 |
+
LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
115 |
+
model_onnx, check = onnxsim.simplify(model_onnx,
|
116 |
+
dynamic_input_shape=dynamic,
|
117 |
+
input_shapes={'images': list(im.shape)} if dynamic else None)
|
118 |
+
assert check, 'assert check failed'
|
119 |
+
onnx.save(model_onnx, f)
|
120 |
+
except Exception as e:
|
121 |
+
LOGGER.info(f'{prefix} simplifier failure: {e}')
|
122 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
123 |
+
return f
|
124 |
+
except Exception as e:
|
125 |
+
LOGGER.info(f'{prefix} export failure: {e}')
|
126 |
+
|
127 |
+
|
128 |
+
def export_openvino(model, file, half, prefix=colorstr('OpenVINO:')):
|
129 |
+
# YOLOv5 OpenVINO export
|
130 |
+
try:
|
131 |
+
check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
132 |
+
import openvino.inference_engine as ie
|
133 |
+
|
134 |
+
LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
|
135 |
+
f = str(file).replace('.pt', f'_openvino_model{os.sep}')
|
136 |
+
|
137 |
+
cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
|
138 |
+
subprocess.check_output(cmd.split()) # export
|
139 |
+
with open(Path(f) / file.with_suffix('.yaml').name, 'w') as g:
|
140 |
+
yaml.dump({'stride': int(max(model.stride)), 'names': model.names}, g) # add metadata.yaml
|
141 |
+
|
142 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
143 |
+
return f
|
144 |
+
except Exception as e:
|
145 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
146 |
+
|
147 |
+
|
148 |
+
def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
|
149 |
+
# YOLOv5 CoreML export
|
150 |
+
try:
|
151 |
+
check_requirements(('coremltools',))
|
152 |
+
import coremltools as ct
|
153 |
+
|
154 |
+
LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
|
155 |
+
f = file.with_suffix('.mlmodel')
|
156 |
+
|
157 |
+
ts = torch.jit.trace(model, im, strict=False) # TorchScript model
|
158 |
+
ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
|
159 |
+
bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
|
160 |
+
if bits < 32:
|
161 |
+
if platform.system() == 'Darwin': # quantization only supported on macOS
|
162 |
+
with warnings.catch_warnings():
|
163 |
+
warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
|
164 |
+
ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
|
165 |
+
else:
|
166 |
+
print(f'{prefix} quantization only supported on macOS, skipping...')
|
167 |
+
ct_model.save(f)
|
168 |
+
|
169 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
170 |
+
return ct_model, f
|
171 |
+
except Exception as e:
|
172 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
173 |
+
return None, None
|
174 |
+
|
175 |
+
|
176 |
+
def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
|
177 |
+
# YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
|
178 |
+
try:
|
179 |
+
assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
|
180 |
+
try:
|
181 |
+
import tensorrt as trt
|
182 |
+
except Exception:
|
183 |
+
if platform.system() == 'Linux':
|
184 |
+
check_requirements(('nvidia-tensorrt',), cmds=('-U --index-url https://pypi.ngc.nvidia.com',))
|
185 |
+
import tensorrt as trt
|
186 |
+
|
187 |
+
if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
|
188 |
+
grid = model.model[-1].anchor_grid
|
189 |
+
model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
|
190 |
+
export_onnx(model, im, file, 12, train, False, simplify) # opset 12
|
191 |
+
model.model[-1].anchor_grid = grid
|
192 |
+
else: # TensorRT >= 8
|
193 |
+
check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
|
194 |
+
export_onnx(model, im, file, 13, train, False, simplify) # opset 13
|
195 |
+
onnx = file.with_suffix('.onnx')
|
196 |
+
|
197 |
+
LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
|
198 |
+
assert onnx.exists(), f'failed to export ONNX file: {onnx}'
|
199 |
+
f = file.with_suffix('.engine') # TensorRT engine file
|
200 |
+
logger = trt.Logger(trt.Logger.INFO)
|
201 |
+
if verbose:
|
202 |
+
logger.min_severity = trt.Logger.Severity.VERBOSE
|
203 |
+
|
204 |
+
builder = trt.Builder(logger)
|
205 |
+
config = builder.create_builder_config()
|
206 |
+
config.max_workspace_size = workspace * 1 << 30
|
207 |
+
# config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
|
208 |
+
|
209 |
+
flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
|
210 |
+
network = builder.create_network(flag)
|
211 |
+
parser = trt.OnnxParser(network, logger)
|
212 |
+
if not parser.parse_from_file(str(onnx)):
|
213 |
+
raise RuntimeError(f'failed to load ONNX file: {onnx}')
|
214 |
+
|
215 |
+
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
216 |
+
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
217 |
+
LOGGER.info(f'{prefix} Network Description:')
|
218 |
+
for inp in inputs:
|
219 |
+
LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
|
220 |
+
for out in outputs:
|
221 |
+
LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
|
222 |
+
|
223 |
+
LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}')
|
224 |
+
if builder.platform_has_fast_fp16 and half:
|
225 |
+
config.set_flag(trt.BuilderFlag.FP16)
|
226 |
+
with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
|
227 |
+
t.write(engine.serialize())
|
228 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
229 |
+
return f
|
230 |
+
except Exception as e:
|
231 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
232 |
+
|
233 |
+
|
234 |
+
def export_saved_model(model,
|
235 |
+
im,
|
236 |
+
file,
|
237 |
+
dynamic,
|
238 |
+
tf_nms=False,
|
239 |
+
agnostic_nms=False,
|
240 |
+
topk_per_class=100,
|
241 |
+
topk_all=100,
|
242 |
+
iou_thres=0.45,
|
243 |
+
conf_thres=0.25,
|
244 |
+
keras=False,
|
245 |
+
prefix=colorstr('TensorFlow SavedModel:')):
|
246 |
+
# YOLOv5 TensorFlow SavedModel export
|
247 |
+
try:
|
248 |
+
import tensorflow as tf
|
249 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
250 |
+
|
251 |
+
from models.tf import TFDetect, TFModel
|
252 |
+
|
253 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
254 |
+
f = str(file).replace('.pt', '_saved_model')
|
255 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
256 |
+
|
257 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
258 |
+
im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
|
259 |
+
_ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
260 |
+
inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
|
261 |
+
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
262 |
+
keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
|
263 |
+
keras_model.trainable = False
|
264 |
+
keras_model.summary()
|
265 |
+
if keras:
|
266 |
+
keras_model.save(f, save_format='tf')
|
267 |
+
else:
|
268 |
+
spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
|
269 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
270 |
+
m = m.get_concrete_function(spec)
|
271 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
272 |
+
tfm = tf.Module()
|
273 |
+
tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
|
274 |
+
tfm.__call__(im)
|
275 |
+
tf.saved_model.save(tfm,
|
276 |
+
f,
|
277 |
+
options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
|
278 |
+
if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
|
279 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
280 |
+
return keras_model, f
|
281 |
+
except Exception as e:
|
282 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
283 |
+
return None, None
|
284 |
+
|
285 |
+
|
286 |
+
def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
|
287 |
+
# YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
|
288 |
+
try:
|
289 |
+
import tensorflow as tf
|
290 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
291 |
+
|
292 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
293 |
+
f = file.with_suffix('.pb')
|
294 |
+
|
295 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
296 |
+
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
|
297 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
298 |
+
frozen_func.graph.as_graph_def()
|
299 |
+
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
|
300 |
+
|
301 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
302 |
+
return f
|
303 |
+
except Exception as e:
|
304 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
305 |
+
|
306 |
+
|
307 |
+
def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
|
308 |
+
# YOLOv5 TensorFlow Lite export
|
309 |
+
try:
|
310 |
+
import tensorflow as tf
|
311 |
+
|
312 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
313 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
314 |
+
f = str(file).replace('.pt', '-fp16.tflite')
|
315 |
+
|
316 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
|
317 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
|
318 |
+
converter.target_spec.supported_types = [tf.float16]
|
319 |
+
converter.optimizations = [tf.lite.Optimize.DEFAULT]
|
320 |
+
if int8:
|
321 |
+
from models.tf import representative_dataset_gen
|
322 |
+
dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
|
323 |
+
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
|
324 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
325 |
+
converter.target_spec.supported_types = []
|
326 |
+
converter.inference_input_type = tf.uint8 # or tf.int8
|
327 |
+
converter.inference_output_type = tf.uint8 # or tf.int8
|
328 |
+
converter.experimental_new_quantizer = True
|
329 |
+
f = str(file).replace('.pt', '-int8.tflite')
|
330 |
+
if nms or agnostic_nms:
|
331 |
+
converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
|
332 |
+
|
333 |
+
tflite_model = converter.convert()
|
334 |
+
open(f, "wb").write(tflite_model)
|
335 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
336 |
+
return f
|
337 |
+
except Exception as e:
|
338 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
339 |
+
|
340 |
+
|
341 |
+
def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
|
342 |
+
# YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
|
343 |
+
try:
|
344 |
+
cmd = 'edgetpu_compiler --version'
|
345 |
+
help_url = 'https://coral.ai/docs/edgetpu/compiler/'
|
346 |
+
assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
|
347 |
+
if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
|
348 |
+
LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
|
349 |
+
sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
|
350 |
+
for c in (
|
351 |
+
'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
|
352 |
+
'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
|
353 |
+
'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
|
354 |
+
subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
|
355 |
+
ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
|
356 |
+
|
357 |
+
LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
|
358 |
+
f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
|
359 |
+
f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
|
360 |
+
|
361 |
+
cmd = f"edgetpu_compiler -s -o {file.parent} {f_tfl}"
|
362 |
+
subprocess.run(cmd.split(), check=True)
|
363 |
+
|
364 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
365 |
+
return f
|
366 |
+
except Exception as e:
|
367 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
368 |
+
|
369 |
+
|
370 |
+
def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
|
371 |
+
# YOLOv5 TensorFlow.js export
|
372 |
+
try:
|
373 |
+
check_requirements(('tensorflowjs',))
|
374 |
+
import re
|
375 |
+
|
376 |
+
import tensorflowjs as tfjs
|
377 |
+
|
378 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
|
379 |
+
f = str(file).replace('.pt', '_web_model') # js dir
|
380 |
+
f_pb = file.with_suffix('.pb') # *.pb path
|
381 |
+
f_json = f'{f}/model.json' # *.json path
|
382 |
+
|
383 |
+
cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
|
384 |
+
f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
|
385 |
+
subprocess.run(cmd.split())
|
386 |
+
|
387 |
+
with open(f_json) as j:
|
388 |
+
json = j.read()
|
389 |
+
with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
|
390 |
+
subst = re.sub(
|
391 |
+
r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
|
392 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
393 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
394 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
|
395 |
+
r'"Identity_1": {"name": "Identity_1"}, '
|
396 |
+
r'"Identity_2": {"name": "Identity_2"}, '
|
397 |
+
r'"Identity_3": {"name": "Identity_3"}}}', json)
|
398 |
+
j.write(subst)
|
399 |
+
|
400 |
+
LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
401 |
+
return f
|
402 |
+
except Exception as e:
|
403 |
+
LOGGER.info(f'\n{prefix} export failure: {e}')
|
404 |
+
|
405 |
+
|
406 |
+
@torch.no_grad()
|
407 |
+
def run(
|
408 |
+
data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
|
409 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
410 |
+
imgsz=(640, 640), # image (height, width)
|
411 |
+
batch_size=1, # batch size
|
412 |
+
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
413 |
+
include=('torchscript', 'onnx'), # include formats
|
414 |
+
half=False, # FP16 half-precision export
|
415 |
+
inplace=False, # set YOLOv5 Detect() inplace=True
|
416 |
+
train=False, # model.train() mode
|
417 |
+
keras=False, # use Keras
|
418 |
+
optimize=False, # TorchScript: optimize for mobile
|
419 |
+
int8=False, # CoreML/TF INT8 quantization
|
420 |
+
dynamic=False, # ONNX/TF: dynamic axes
|
421 |
+
simplify=False, # ONNX: simplify model
|
422 |
+
opset=12, # ONNX: opset version
|
423 |
+
verbose=False, # TensorRT: verbose log
|
424 |
+
workspace=4, # TensorRT: workspace size (GB)
|
425 |
+
nms=False, # TF: add NMS to model
|
426 |
+
agnostic_nms=False, # TF: add agnostic NMS to model
|
427 |
+
topk_per_class=100, # TF.js NMS: topk per class to keep
|
428 |
+
topk_all=100, # TF.js NMS: topk for all classes to keep
|
429 |
+
iou_thres=0.45, # TF.js NMS: IoU threshold
|
430 |
+
conf_thres=0.25, # TF.js NMS: confidence threshold
|
431 |
+
):
|
432 |
+
t = time.time()
|
433 |
+
include = [x.lower() for x in include] # to lowercase
|
434 |
+
fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
|
435 |
+
flags = [x in include for x in fmts]
|
436 |
+
assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
|
437 |
+
jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
|
438 |
+
file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
|
439 |
+
|
440 |
+
# Load PyTorch model
|
441 |
+
device = select_device(device)
|
442 |
+
if half:
|
443 |
+
assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
|
444 |
+
assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
|
445 |
+
model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
|
446 |
+
nc, names = model.nc, model.names # number of classes, class names
|
447 |
+
|
448 |
+
# Checks
|
449 |
+
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
|
450 |
+
assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
|
451 |
+
|
452 |
+
# Input
|
453 |
+
gs = int(max(model.stride)) # grid size (max stride)
|
454 |
+
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
|
455 |
+
im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
|
456 |
+
|
457 |
+
# Update model
|
458 |
+
model.train() if train else model.eval() # training mode = no Detect() layer grid construction
|
459 |
+
for k, m in model.named_modules():
|
460 |
+
if isinstance(m, Detect):
|
461 |
+
m.inplace = inplace
|
462 |
+
m.onnx_dynamic = dynamic
|
463 |
+
m.export = True
|
464 |
+
|
465 |
+
for _ in range(2):
|
466 |
+
y = model(im) # dry runs
|
467 |
+
if half and not coreml:
|
468 |
+
im, model = im.half(), model.half() # to FP16
|
469 |
+
shape = tuple(y[0].shape) # model output shape
|
470 |
+
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
|
471 |
+
|
472 |
+
# Exports
|
473 |
+
f = [''] * 10 # exported filenames
|
474 |
+
warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
|
475 |
+
if jit:
|
476 |
+
f[0] = export_torchscript(model, im, file, optimize)
|
477 |
+
if engine: # TensorRT required before ONNX
|
478 |
+
f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
|
479 |
+
if onnx or xml: # OpenVINO requires ONNX
|
480 |
+
f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
|
481 |
+
if xml: # OpenVINO
|
482 |
+
f[3] = export_openvino(model, file, half)
|
483 |
+
if coreml:
|
484 |
+
_, f[4] = export_coreml(model, im, file, int8, half)
|
485 |
+
|
486 |
+
# TensorFlow Exports
|
487 |
+
if any((saved_model, pb, tflite, edgetpu, tfjs)):
|
488 |
+
if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
|
489 |
+
check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
|
490 |
+
assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
|
491 |
+
model, f[5] = export_saved_model(model.cpu(),
|
492 |
+
im,
|
493 |
+
file,
|
494 |
+
dynamic,
|
495 |
+
tf_nms=nms or agnostic_nms or tfjs,
|
496 |
+
agnostic_nms=agnostic_nms or tfjs,
|
497 |
+
topk_per_class=topk_per_class,
|
498 |
+
topk_all=topk_all,
|
499 |
+
iou_thres=iou_thres,
|
500 |
+
conf_thres=conf_thres,
|
501 |
+
keras=keras)
|
502 |
+
if pb or tfjs: # pb prerequisite to tfjs
|
503 |
+
f[6] = export_pb(model, file)
|
504 |
+
if tflite or edgetpu:
|
505 |
+
f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
|
506 |
+
if edgetpu:
|
507 |
+
f[8] = export_edgetpu(file)
|
508 |
+
if tfjs:
|
509 |
+
f[9] = export_tfjs(file)
|
510 |
+
|
511 |
+
# Finish
|
512 |
+
f = [str(x) for x in f if x] # filter out '' and None
|
513 |
+
if any(f):
|
514 |
+
h = '--half' if half else '' # --half FP16 inference arg
|
515 |
+
LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
|
516 |
+
f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
|
517 |
+
f"\nDetect: python detect.py --weights {f[-1]} {h}"
|
518 |
+
f"\nValidate: python val.py --weights {f[-1]} {h}"
|
519 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
|
520 |
+
f"\nVisualize: https://netron.app")
|
521 |
+
return f # return list of exported files/dirs
|
522 |
+
|
523 |
+
|
524 |
+
def parse_opt():
|
525 |
+
parser = argparse.ArgumentParser()
|
526 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
527 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
|
528 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
|
529 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
530 |
+
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
531 |
+
parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
|
532 |
+
parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
|
533 |
+
parser.add_argument('--train', action='store_true', help='model.train() mode')
|
534 |
+
parser.add_argument('--keras', action='store_true', help='TF: use Keras')
|
535 |
+
parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
|
536 |
+
parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
|
537 |
+
parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
|
538 |
+
parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
|
539 |
+
parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
|
540 |
+
parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
|
541 |
+
parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
|
542 |
+
parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
|
543 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
|
544 |
+
parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
|
545 |
+
parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
|
546 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
|
547 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
|
548 |
+
parser.add_argument('--include',
|
549 |
+
nargs='+',
|
550 |
+
default=['torchscript', 'onnx'],
|
551 |
+
help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
|
552 |
+
opt = parser.parse_args()
|
553 |
+
print_args(vars(opt))
|
554 |
+
return opt
|
555 |
+
|
556 |
+
|
557 |
+
def main(opt):
|
558 |
+
for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
|
559 |
+
run(**vars(opt))
|
560 |
+
|
561 |
+
|
562 |
+
if __name__ == "__main__":
|
563 |
+
opt = parse_opt()
|
564 |
+
main(opt)
|
yolov5/models/__init__.py
ADDED
File without changes
|
yolov5/models/common.c
ADDED
The diff for this file is too large to render.
See raw diff
|
|
yolov5/models/common.py
ADDED
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Common modules
|
4 |
+
"""
|
5 |
+
|
6 |
+
import math
|
7 |
+
import warnings
|
8 |
+
from copy import copy
|
9 |
+
from pathlib import Path
|
10 |
+
|
11 |
+
import numpy as np
|
12 |
+
import pandas as pd
|
13 |
+
import requests
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
from PIL import Image
|
17 |
+
from torch.cuda import amp
|
18 |
+
|
19 |
+
from utils.datasets import exif_transpose, letterbox
|
20 |
+
from utils.general import (LOGGER, colorstr, increment_path,
|
21 |
+
make_divisible, non_max_suppression, scale_coords, xywh2xyxy, xyxy2xywh)
|
22 |
+
from utils.plots import Annotator, colors, save_one_box
|
23 |
+
from utils.torch_utils import copy_attr, time_sync
|
24 |
+
|
25 |
+
|
26 |
+
def autopad(k, p=None): # kernel, padding
|
27 |
+
# Pad to 'same'
|
28 |
+
if p is None:
|
29 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
30 |
+
return p
|
31 |
+
|
32 |
+
|
33 |
+
class Conv(nn.Module):
|
34 |
+
# Standard convolution
|
35 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
36 |
+
super().__init__()
|
37 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
|
38 |
+
self.bn = nn.BatchNorm2d(c2)
|
39 |
+
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
|
40 |
+
|
41 |
+
def forward(self, x):
|
42 |
+
return self.act(self.bn(self.conv(x)))
|
43 |
+
|
44 |
+
def forward_fuse(self, x):
|
45 |
+
return self.act(self.conv(x))
|
46 |
+
|
47 |
+
|
48 |
+
class DWConv(Conv):
|
49 |
+
# Depth-wise convolution class
|
50 |
+
def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
51 |
+
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
|
52 |
+
|
53 |
+
|
54 |
+
class TransformerLayer(nn.Module):
|
55 |
+
# Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
|
56 |
+
def __init__(self, c, num_heads):
|
57 |
+
super().__init__()
|
58 |
+
self.q = nn.Linear(c, c, bias=False)
|
59 |
+
self.k = nn.Linear(c, c, bias=False)
|
60 |
+
self.v = nn.Linear(c, c, bias=False)
|
61 |
+
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
|
62 |
+
self.fc1 = nn.Linear(c, c, bias=False)
|
63 |
+
self.fc2 = nn.Linear(c, c, bias=False)
|
64 |
+
|
65 |
+
def forward(self, x):
|
66 |
+
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
|
67 |
+
x = self.fc2(self.fc1(x)) + x
|
68 |
+
return x
|
69 |
+
|
70 |
+
|
71 |
+
class TransformerBlock(nn.Module):
|
72 |
+
# Vision Transformer https://arxiv.org/abs/2010.11929
|
73 |
+
def __init__(self, c1, c2, num_heads, num_layers):
|
74 |
+
super().__init__()
|
75 |
+
self.conv = None
|
76 |
+
if c1 != c2:
|
77 |
+
self.conv = Conv(c1, c2)
|
78 |
+
self.linear = nn.Linear(c2, c2) # learnable position embedding
|
79 |
+
self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
|
80 |
+
self.c2 = c2
|
81 |
+
|
82 |
+
def forward(self, x):
|
83 |
+
if self.conv is not None:
|
84 |
+
x = self.conv(x)
|
85 |
+
b, _, w, h = x.shape
|
86 |
+
p = x.flatten(2).permute(2, 0, 1)
|
87 |
+
return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
|
88 |
+
|
89 |
+
|
90 |
+
class Bottleneck(nn.Module):
|
91 |
+
# Standard bottleneck
|
92 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
93 |
+
super().__init__()
|
94 |
+
c_ = int(c2 * e) # hidden channels
|
95 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
96 |
+
self.cv2 = Conv(c_, c2, 3, 1, g=g)
|
97 |
+
self.add = shortcut and c1 == c2
|
98 |
+
|
99 |
+
def forward(self, x):
|
100 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
101 |
+
|
102 |
+
|
103 |
+
class BottleneckCSP(nn.Module):
|
104 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
105 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
106 |
+
super().__init__()
|
107 |
+
c_ = int(c2 * e) # hidden channels
|
108 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
109 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
110 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
111 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
112 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
113 |
+
self.act = nn.SiLU()
|
114 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
115 |
+
|
116 |
+
def forward(self, x):
|
117 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
118 |
+
y2 = self.cv2(x)
|
119 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
|
120 |
+
|
121 |
+
|
122 |
+
class C3(nn.Module):
|
123 |
+
# CSP Bottleneck with 3 convolutions
|
124 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
125 |
+
super().__init__()
|
126 |
+
c_ = int(c2 * e) # hidden channels
|
127 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
128 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
129 |
+
self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
|
130 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
131 |
+
# self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
|
132 |
+
|
133 |
+
def forward(self, x):
|
134 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
|
135 |
+
|
136 |
+
|
137 |
+
class C3TR(C3):
|
138 |
+
# C3 module with TransformerBlock()
|
139 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
140 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
141 |
+
c_ = int(c2 * e)
|
142 |
+
self.m = TransformerBlock(c_, c_, 4, n)
|
143 |
+
|
144 |
+
|
145 |
+
class C3SPP(C3):
|
146 |
+
# C3 module with SPP()
|
147 |
+
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
|
148 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
149 |
+
c_ = int(c2 * e)
|
150 |
+
self.m = SPP(c_, c_, k)
|
151 |
+
|
152 |
+
|
153 |
+
class C3Ghost(C3):
|
154 |
+
# C3 module with GhostBottleneck()
|
155 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
156 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
157 |
+
c_ = int(c2 * e) # hidden channels
|
158 |
+
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
|
159 |
+
|
160 |
+
|
161 |
+
class SPP(nn.Module):
|
162 |
+
# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
|
163 |
+
def __init__(self, c1, c2, k=(5, 9, 13)):
|
164 |
+
super().__init__()
|
165 |
+
c_ = c1 // 2 # hidden channels
|
166 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
167 |
+
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
168 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
169 |
+
|
170 |
+
def forward(self, x):
|
171 |
+
x = self.cv1(x)
|
172 |
+
with warnings.catch_warnings():
|
173 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
174 |
+
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
175 |
+
|
176 |
+
|
177 |
+
class SPPF(nn.Module):
|
178 |
+
# Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
|
179 |
+
def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
|
180 |
+
super().__init__()
|
181 |
+
c_ = c1 // 2 # hidden channels
|
182 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
183 |
+
self.cv2 = Conv(c_ * 4, c2, 1, 1)
|
184 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
|
185 |
+
|
186 |
+
def forward(self, x):
|
187 |
+
x = self.cv1(x)
|
188 |
+
with warnings.catch_warnings():
|
189 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
190 |
+
y1 = self.m(x)
|
191 |
+
y2 = self.m(y1)
|
192 |
+
return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
|
193 |
+
|
194 |
+
|
195 |
+
class Focus(nn.Module):
|
196 |
+
# Focus wh information into c-space
|
197 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
198 |
+
super().__init__()
|
199 |
+
self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
|
200 |
+
# self.contract = Contract(gain=2)
|
201 |
+
|
202 |
+
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
|
203 |
+
return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
|
204 |
+
# return self.conv(self.contract(x))
|
205 |
+
|
206 |
+
|
207 |
+
class GhostConv(nn.Module):
|
208 |
+
# Ghost Convolution https://github.com/huawei-noah/ghostnet
|
209 |
+
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
|
210 |
+
super().__init__()
|
211 |
+
c_ = c2 // 2 # hidden channels
|
212 |
+
self.cv1 = Conv(c1, c_, k, s, None, g, act)
|
213 |
+
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
|
214 |
+
|
215 |
+
def forward(self, x):
|
216 |
+
y = self.cv1(x)
|
217 |
+
return torch.cat([y, self.cv2(y)], 1)
|
218 |
+
|
219 |
+
|
220 |
+
class GhostBottleneck(nn.Module):
|
221 |
+
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
|
222 |
+
def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
|
223 |
+
super().__init__()
|
224 |
+
c_ = c2 // 2
|
225 |
+
self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
|
226 |
+
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
|
227 |
+
GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
|
228 |
+
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
|
229 |
+
Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
|
230 |
+
|
231 |
+
def forward(self, x):
|
232 |
+
return self.conv(x) + self.shortcut(x)
|
233 |
+
|
234 |
+
|
235 |
+
class Contract(nn.Module):
|
236 |
+
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
|
237 |
+
def __init__(self, gain=2):
|
238 |
+
super().__init__()
|
239 |
+
self.gain = gain
|
240 |
+
|
241 |
+
def forward(self, x):
|
242 |
+
b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
|
243 |
+
s = self.gain
|
244 |
+
x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
|
245 |
+
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
|
246 |
+
return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
|
247 |
+
|
248 |
+
|
249 |
+
class Expand(nn.Module):
|
250 |
+
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
|
251 |
+
def __init__(self, gain=2):
|
252 |
+
super().__init__()
|
253 |
+
self.gain = gain
|
254 |
+
|
255 |
+
def forward(self, x):
|
256 |
+
b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
|
257 |
+
s = self.gain
|
258 |
+
x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
|
259 |
+
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
|
260 |
+
return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
|
261 |
+
|
262 |
+
|
263 |
+
class Concat(nn.Module):
|
264 |
+
# Concatenate a list of tensors along dimension
|
265 |
+
def __init__(self, dimension=1):
|
266 |
+
super().__init__()
|
267 |
+
self.d = dimension
|
268 |
+
|
269 |
+
def forward(self, x):
|
270 |
+
return torch.cat(x, self.d)
|
271 |
+
|
272 |
+
|
273 |
+
class DetectMultiBackend(nn.Module):
|
274 |
+
# YOLOv5 MultiBackend class for python inference on various backends
|
275 |
+
def __init__(self, weights='yolov5s.pt', device=None, dnn=False, data=None):
|
276 |
+
# Usage:
|
277 |
+
# PyTorch: weights = *.pt
|
278 |
+
# TorchScript: *.torchscript
|
279 |
+
# CoreML: *.mlmodel
|
280 |
+
# OpenVINO: *.xml
|
281 |
+
# TensorFlow: *_saved_model
|
282 |
+
# TensorFlow: *.pb
|
283 |
+
# TensorFlow Lite: *.tflite
|
284 |
+
# TensorFlow Edge TPU: *_edgetpu.tflite
|
285 |
+
# ONNX Runtime: *.onnx
|
286 |
+
# OpenCV DNN: *.onnx with dnn=True
|
287 |
+
# TensorRT: *.engine
|
288 |
+
from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
|
289 |
+
|
290 |
+
super().__init__()
|
291 |
+
w = str(weights[0] if isinstance(weights, list) else weights)
|
292 |
+
suffix = Path(w).suffix.lower()
|
293 |
+
suffixes = ['.pt', '.torchscript', '.onnx', '.engine', '.tflite', '.pb', '', '.mlmodel', '.xml']
|
294 |
+
pt, jit, onnx, engine, tflite, pb, saved_model, coreml, xml = (suffix == x for x in suffixes) # backends
|
295 |
+
|
296 |
+
model = attempt_load(weights if isinstance(weights, list) else w, map_location=device)
|
297 |
+
stride = max(int(model.stride.max()), 32) # model stride
|
298 |
+
names = model.module.names if hasattr(model, 'module') else model.names # get class names
|
299 |
+
self.model = model # explicitly assign for to(), cpu(), cuda(), half()
|
300 |
+
|
301 |
+
self.__dict__.update(locals()) # assign all variables to self
|
302 |
+
|
303 |
+
def forward(self, im, augment=False, visualize=False, val=False):
|
304 |
+
# YOLOv5 MultiBackend inference
|
305 |
+
b, ch, h, w = im.shape # batch, channel, height, width
|
306 |
+
if self.pt or self.jit: # PyTorch
|
307 |
+
y = self.model(im) if self.jit else self.model(im, augment=augment, visualize=visualize)
|
308 |
+
return y if val else y[0]
|
309 |
+
elif self.dnn: # ONNX OpenCV DNN
|
310 |
+
im = im.cpu().numpy() # torch to numpy
|
311 |
+
self.net.setInput(im)
|
312 |
+
y = self.net.forward()
|
313 |
+
elif self.onnx: # ONNX Runtime
|
314 |
+
im = im.cpu().numpy() # torch to numpy
|
315 |
+
y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0]
|
316 |
+
elif self.xml: # OpenVINO
|
317 |
+
im = im.cpu().numpy() # FP32
|
318 |
+
desc = self.ie.TensorDesc(precision='FP32', dims=im.shape, layout='NCHW') # Tensor Description
|
319 |
+
request = self.executable_network.requests[0] # inference request
|
320 |
+
request.set_blob(blob_name='images', blob=self.ie.Blob(desc, im)) # name=next(iter(request.input_blobs))
|
321 |
+
request.infer()
|
322 |
+
y = request.output_blobs['output'].buffer # name=next(iter(request.output_blobs))
|
323 |
+
elif self.engine: # TensorRT
|
324 |
+
assert im.shape == self.bindings['images'].shape, (im.shape, self.bindings['images'].shape)
|
325 |
+
self.binding_addrs['images'] = int(im.data_ptr())
|
326 |
+
self.context.execute_v2(list(self.binding_addrs.values()))
|
327 |
+
y = self.bindings['output'].data
|
328 |
+
elif self.coreml: # CoreML
|
329 |
+
im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
|
330 |
+
im = Image.fromarray((im[0] * 255).astype('uint8'))
|
331 |
+
# im = im.resize((192, 320), Image.ANTIALIAS)
|
332 |
+
y = self.model.predict({'image': im}) # coordinates are xywh normalized
|
333 |
+
if 'confidence' in y:
|
334 |
+
box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
|
335 |
+
conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
|
336 |
+
y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
|
337 |
+
else:
|
338 |
+
y = y[list(y)[-1]] # last output
|
339 |
+
else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
|
340 |
+
im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
|
341 |
+
if self.saved_model: # SavedModel
|
342 |
+
y = self.model(im, training=False).numpy()
|
343 |
+
elif self.pb: # GraphDef
|
344 |
+
y = self.frozen_func(x=self.tf.constant(im)).numpy()
|
345 |
+
elif self.tflite: # Lite
|
346 |
+
input, output = self.input_details[0], self.output_details[0]
|
347 |
+
int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
|
348 |
+
if int8:
|
349 |
+
scale, zero_point = input['quantization']
|
350 |
+
im = (im / scale + zero_point).astype(np.uint8) # de-scale
|
351 |
+
self.interpreter.set_tensor(input['index'], im)
|
352 |
+
self.interpreter.invoke()
|
353 |
+
y = self.interpreter.get_tensor(output['index'])
|
354 |
+
if int8:
|
355 |
+
scale, zero_point = output['quantization']
|
356 |
+
y = (y.astype(np.float32) - zero_point) * scale # re-scale
|
357 |
+
y[..., 0] *= w # x
|
358 |
+
y[..., 1] *= h # y
|
359 |
+
y[..., 2] *= w # w
|
360 |
+
y[..., 3] *= h # h
|
361 |
+
|
362 |
+
y = torch.tensor(y) if isinstance(y, np.ndarray) else y
|
363 |
+
return (y, []) if val else y
|
364 |
+
|
365 |
+
def warmup(self, imgsz=(1, 3, 640, 640), half=False):
|
366 |
+
# Warmup model by running inference once
|
367 |
+
if self.pt or self.jit or self.onnx or self.engine: # warmup types
|
368 |
+
if isinstance(self.device, torch.device) and self.device.type != 'cpu': # only warmup GPU models
|
369 |
+
im = torch.zeros(*imgsz).to(self.device).type(torch.half if half else torch.float) # input image
|
370 |
+
self.forward(im) # warmup
|
371 |
+
|
372 |
+
|
373 |
+
class AutoShape(nn.Module):
|
374 |
+
# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
|
375 |
+
conf = 0.25 # NMS confidence threshold
|
376 |
+
iou = 0.45 # NMS IoU threshold
|
377 |
+
agnostic = False # NMS class-agnostic
|
378 |
+
multi_label = False # NMS multiple labels per box
|
379 |
+
classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
|
380 |
+
max_det = 1000 # maximum number of detections per image
|
381 |
+
amp = False # Automatic Mixed Precision (AMP) inference
|
382 |
+
|
383 |
+
def __init__(self, model):
|
384 |
+
super().__init__()
|
385 |
+
LOGGER.info('Adding AutoShape... ')
|
386 |
+
copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
|
387 |
+
self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
|
388 |
+
self.pt = not self.dmb or model.pt # PyTorch model
|
389 |
+
self.model = model.eval()
|
390 |
+
|
391 |
+
def _apply(self, fn):
|
392 |
+
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
|
393 |
+
self = super()._apply(fn)
|
394 |
+
if self.pt:
|
395 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
396 |
+
m.stride = fn(m.stride)
|
397 |
+
m.grid = list(map(fn, m.grid))
|
398 |
+
if isinstance(m.anchor_grid, list):
|
399 |
+
m.anchor_grid = list(map(fn, m.anchor_grid))
|
400 |
+
return self
|
401 |
+
|
402 |
+
@torch.no_grad()
|
403 |
+
def forward(self, imgs, size=640, augment=False, profile=False):
|
404 |
+
# Inference from various sources. For height=640, width=1280, RGB images example inputs are:
|
405 |
+
# file: imgs = 'data/images/zidane.jpg' # str or PosixPath
|
406 |
+
# URI: = 'https://ultralytics.com/images/zidane.jpg'
|
407 |
+
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
|
408 |
+
# PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
|
409 |
+
# numpy: = np.zeros((640,1280,3)) # HWC
|
410 |
+
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
|
411 |
+
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
|
412 |
+
|
413 |
+
t = [time_sync()]
|
414 |
+
p = next(self.model.parameters()) if self.pt else torch.zeros(1) # for device and type
|
415 |
+
autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
|
416 |
+
if isinstance(imgs, torch.Tensor): # torch
|
417 |
+
with amp.autocast(enabled=autocast):
|
418 |
+
return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
|
419 |
+
|
420 |
+
# Pre-process
|
421 |
+
n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
|
422 |
+
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
|
423 |
+
for i, im in enumerate(imgs):
|
424 |
+
f = f'image{i}' # filename
|
425 |
+
if isinstance(im, (str, Path)): # filename or uri
|
426 |
+
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
|
427 |
+
im = np.asarray(exif_transpose(im))
|
428 |
+
elif isinstance(im, Image.Image): # PIL Image
|
429 |
+
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
|
430 |
+
files.append(Path(f).with_suffix('.jpg').name)
|
431 |
+
if im.shape[0] < 5: # image in CHW
|
432 |
+
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
|
433 |
+
im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
|
434 |
+
s = im.shape[:2] # HWC
|
435 |
+
shape0.append(s) # image shape
|
436 |
+
g = (size / max(s)) # gain
|
437 |
+
shape1.append([y * g for y in s])
|
438 |
+
imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
|
439 |
+
shape1 = [make_divisible(x, self.stride) for x in np.stack(shape1, 0).max(0)] # inference shape
|
440 |
+
x = [letterbox(im, new_shape=shape1 if self.pt else size, auto=False)[0] for im in imgs] # pad
|
441 |
+
x = np.stack(x, 0) if n > 1 else x[0][None] # stack
|
442 |
+
x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
|
443 |
+
x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
|
444 |
+
t.append(time_sync())
|
445 |
+
|
446 |
+
with amp.autocast(enabled=autocast):
|
447 |
+
# Inference
|
448 |
+
y = self.model(x, augment, profile) # forward
|
449 |
+
t.append(time_sync())
|
450 |
+
|
451 |
+
# Post-process
|
452 |
+
y = non_max_suppression(y if self.dmb else y[0], self.conf, iou_thres=self.iou, classes=self.classes,
|
453 |
+
agnostic=self.agnostic, multi_label=self.multi_label, max_det=self.max_det) # NMS
|
454 |
+
for i in range(n):
|
455 |
+
scale_coords(shape1, y[i][:, :4], shape0[i])
|
456 |
+
|
457 |
+
t.append(time_sync())
|
458 |
+
return Detections(imgs, y, files, t, self.names, x.shape)
|
459 |
+
|
460 |
+
|
461 |
+
class Detections:
|
462 |
+
# YOLOv5 detections class for inference results
|
463 |
+
def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None):
|
464 |
+
super().__init__()
|
465 |
+
d = pred[0].device # device
|
466 |
+
gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations
|
467 |
+
self.imgs = imgs # list of images as numpy arrays
|
468 |
+
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
|
469 |
+
self.names = names # class names
|
470 |
+
self.files = files # image filenames
|
471 |
+
self.times = times # profiling times
|
472 |
+
self.xyxy = pred # xyxy pixels
|
473 |
+
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
|
474 |
+
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
|
475 |
+
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
|
476 |
+
self.n = len(self.pred) # number of images (batch size)
|
477 |
+
self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
|
478 |
+
self.s = shape # inference BCHW shape
|
479 |
+
|
480 |
+
def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
|
481 |
+
crops = []
|
482 |
+
for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
|
483 |
+
s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
|
484 |
+
if pred.shape[0]:
|
485 |
+
for c in pred[:, -1].unique():
|
486 |
+
n = (pred[:, -1] == c).sum() # detections per class
|
487 |
+
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
|
488 |
+
if show or save or render or crop:
|
489 |
+
annotator = Annotator(im, example=str(self.names))
|
490 |
+
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
|
491 |
+
label = f'{self.names[int(cls)]} {conf:.2f}'
|
492 |
+
if crop:
|
493 |
+
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
|
494 |
+
crops.append({'box': box, 'conf': conf, 'cls': cls, 'label': label,
|
495 |
+
'im': save_one_box(box, im, file=file, save=save)})
|
496 |
+
else: # all others
|
497 |
+
annotator.box_label(box, label, color=colors(cls))
|
498 |
+
im = annotator.im
|
499 |
+
else:
|
500 |
+
s += '(no detections)'
|
501 |
+
|
502 |
+
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
|
503 |
+
if pprint:
|
504 |
+
LOGGER.info(s.rstrip(', '))
|
505 |
+
if show:
|
506 |
+
im.show(self.files[i]) # show
|
507 |
+
if save:
|
508 |
+
f = self.files[i]
|
509 |
+
im.save(save_dir / f) # save
|
510 |
+
if i == self.n - 1:
|
511 |
+
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
|
512 |
+
if render:
|
513 |
+
self.imgs[i] = np.asarray(im)
|
514 |
+
if crop:
|
515 |
+
if save:
|
516 |
+
LOGGER.info(f'Saved results to {save_dir}\n')
|
517 |
+
return crops
|
518 |
+
|
519 |
+
def print(self):
|
520 |
+
self.display(pprint=True) # print results
|
521 |
+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
|
522 |
+
self.t)
|
523 |
+
|
524 |
+
def show(self):
|
525 |
+
self.display(show=True) # show results
|
526 |
+
|
527 |
+
def save(self, save_dir='runs/detect/exp'):
|
528 |
+
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
|
529 |
+
self.display(save=True, save_dir=save_dir) # save results
|
530 |
+
|
531 |
+
def crop(self, save=True, save_dir='runs/detect/exp'):
|
532 |
+
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
|
533 |
+
return self.display(crop=True, save=save, save_dir=save_dir) # crop results
|
534 |
+
|
535 |
+
def render(self):
|
536 |
+
self.display(render=True) # render results
|
537 |
+
return self.imgs
|
538 |
+
|
539 |
+
def pandas(self):
|
540 |
+
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
|
541 |
+
new = copy(self) # return copy
|
542 |
+
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
|
543 |
+
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
|
544 |
+
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
|
545 |
+
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
|
546 |
+
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
|
547 |
+
return new
|
548 |
+
|
549 |
+
def tolist(self):
|
550 |
+
# return a list of Detections objects, i.e. 'for result in results.tolist():'
|
551 |
+
r = range(self.n) # iterable
|
552 |
+
x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
|
553 |
+
# for d in x:
|
554 |
+
# for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
|
555 |
+
# setattr(d, k, getattr(d, k)[0]) # pop out of list
|
556 |
+
return x
|
557 |
+
|
558 |
+
def __len__(self):
|
559 |
+
return self.n
|
560 |
+
|
561 |
+
|
562 |
+
class Classify(nn.Module):
|
563 |
+
# Classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
564 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
|
565 |
+
super().__init__()
|
566 |
+
self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
|
567 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
|
568 |
+
self.flat = nn.Flatten()
|
569 |
+
|
570 |
+
def forward(self, x):
|
571 |
+
z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
|
572 |
+
return self.flat(self.conv(z)) # flatten to x(b,c2)
|
yolov5/models/experimental.c
ADDED
The diff for this file is too large to render.
See raw diff
|
|
yolov5/models/experimental.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Experimental modules
|
4 |
+
"""
|
5 |
+
import math
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
|
11 |
+
from .common import Conv
|
12 |
+
from utils.downloads import attempt_download
|
13 |
+
|
14 |
+
|
15 |
+
class CrossConv(nn.Module):
|
16 |
+
# Cross Convolution Downsample
|
17 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
|
18 |
+
# ch_in, ch_out, kernel, stride, groups, expansion, shortcut
|
19 |
+
super().__init__()
|
20 |
+
c_ = int(c2 * e) # hidden channels
|
21 |
+
self.cv1 = Conv(c1, c_, (1, k), (1, s))
|
22 |
+
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
|
23 |
+
self.add = shortcut and c1 == c2
|
24 |
+
|
25 |
+
def forward(self, x):
|
26 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
27 |
+
|
28 |
+
|
29 |
+
class Sum(nn.Module):
|
30 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
31 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
32 |
+
super().__init__()
|
33 |
+
self.weight = weight # apply weights boolean
|
34 |
+
self.iter = range(n - 1) # iter object
|
35 |
+
if weight:
|
36 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
37 |
+
|
38 |
+
def forward(self, x):
|
39 |
+
y = x[0] # no weight
|
40 |
+
if self.weight:
|
41 |
+
w = torch.sigmoid(self.w) * 2
|
42 |
+
for i in self.iter:
|
43 |
+
y = y + x[i + 1] * w[i]
|
44 |
+
else:
|
45 |
+
for i in self.iter:
|
46 |
+
y = y + x[i + 1]
|
47 |
+
return y
|
48 |
+
|
49 |
+
|
50 |
+
class MixConv2d(nn.Module):
|
51 |
+
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
52 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
53 |
+
super().__init__()
|
54 |
+
n = len(k) # number of convolutions
|
55 |
+
if equal_ch: # equal c_ per group
|
56 |
+
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
57 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
58 |
+
else: # equal weight.numel() per group
|
59 |
+
b = [c2] + [0] * n
|
60 |
+
a = np.eye(n + 1, n, k=-1)
|
61 |
+
a -= np.roll(a, 1, axis=1)
|
62 |
+
a *= np.array(k) ** 2
|
63 |
+
a[0] = 1
|
64 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
65 |
+
|
66 |
+
self.m = nn.ModuleList(
|
67 |
+
[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
68 |
+
self.bn = nn.BatchNorm2d(c2)
|
69 |
+
self.act = nn.SiLU()
|
70 |
+
|
71 |
+
def forward(self, x):
|
72 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
73 |
+
|
74 |
+
|
75 |
+
class Ensemble(nn.ModuleList):
|
76 |
+
# Ensemble of models
|
77 |
+
def __init__(self):
|
78 |
+
super().__init__()
|
79 |
+
|
80 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
81 |
+
y = []
|
82 |
+
for module in self:
|
83 |
+
y.append(module(x, augment, profile, visualize)[0])
|
84 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
85 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
86 |
+
y = torch.cat(y, 1) # nms ensemble
|
87 |
+
return y, None # inference, train output
|
88 |
+
|
89 |
+
|
90 |
+
def attempt_load(weights, map_location=None, inplace=True, fuse=True):
|
91 |
+
from models.yolo import Detect, Model
|
92 |
+
|
93 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
94 |
+
model = Ensemble()
|
95 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
96 |
+
ckpt = torch.load(attempt_download(w), map_location=map_location) # load
|
97 |
+
if fuse:
|
98 |
+
model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
|
99 |
+
else:
|
100 |
+
model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse
|
101 |
+
|
102 |
+
# Compatibility updates
|
103 |
+
for m in model.modules():
|
104 |
+
if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
|
105 |
+
m.inplace = inplace # pytorch 1.7.0 compatibility
|
106 |
+
if type(m) is Detect:
|
107 |
+
if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
|
108 |
+
delattr(m, 'anchor_grid')
|
109 |
+
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
110 |
+
elif type(m) is Conv:
|
111 |
+
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
|
112 |
+
|
113 |
+
if len(model) == 1:
|
114 |
+
return model[-1] # return model
|
115 |
+
else:
|
116 |
+
print(f'Ensemble created with {weights}\n')
|
117 |
+
for k in ['names']:
|
118 |
+
setattr(model, k, getattr(model[-1], k))
|
119 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
120 |
+
return model # return ensemble
|
yolov5/models/hub/anchors.yaml
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
# Default anchors for COCO data
|
3 |
+
|
4 |
+
|
5 |
+
# P5 -------------------------------------------------------------------------------------------------------------------
|
6 |
+
# P5-640:
|
7 |
+
anchors_p5_640:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
|
13 |
+
# P6 -------------------------------------------------------------------------------------------------------------------
|
14 |
+
# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
|
15 |
+
anchors_p6_640:
|
16 |
+
- [9,11, 21,19, 17,41] # P3/8
|
17 |
+
- [43,32, 39,70, 86,64] # P4/16
|
18 |
+
- [65,131, 134,130, 120,265] # P5/32
|
19 |
+
- [282,180, 247,354, 512,387] # P6/64
|
20 |
+
|
21 |
+
# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
|
22 |
+
anchors_p6_1280:
|
23 |
+
- [19,27, 44,40, 38,94] # P3/8
|
24 |
+
- [96,68, 86,152, 180,137] # P4/16
|
25 |
+
- [140,301, 303,264, 238,542] # P5/32
|
26 |
+
- [436,615, 739,380, 925,792] # P6/64
|
27 |
+
|
28 |
+
# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
|
29 |
+
anchors_p6_1920:
|
30 |
+
- [28,41, 67,59, 57,141] # P3/8
|
31 |
+
- [144,103, 129,227, 270,205] # P4/16
|
32 |
+
- [209,452, 455,396, 358,812] # P5/32
|
33 |
+
- [653,922, 1109,570, 1387,1187] # P6/64
|
34 |
+
|
35 |
+
|
36 |
+
# P7 -------------------------------------------------------------------------------------------------------------------
|
37 |
+
# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
|
38 |
+
anchors_p7_640:
|
39 |
+
- [11,11, 13,30, 29,20] # P3/8
|
40 |
+
- [30,46, 61,38, 39,92] # P4/16
|
41 |
+
- [78,80, 146,66, 79,163] # P5/32
|
42 |
+
- [149,150, 321,143, 157,303] # P6/64
|
43 |
+
- [257,402, 359,290, 524,372] # P7/128
|
44 |
+
|
45 |
+
# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
|
46 |
+
anchors_p7_1280:
|
47 |
+
- [19,22, 54,36, 32,77] # P3/8
|
48 |
+
- [70,83, 138,71, 75,173] # P4/16
|
49 |
+
- [165,159, 148,334, 375,151] # P5/32
|
50 |
+
- [334,317, 251,626, 499,474] # P6/64
|
51 |
+
- [750,326, 534,814, 1079,818] # P7/128
|
52 |
+
|
53 |
+
# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
|
54 |
+
anchors_p7_1920:
|
55 |
+
- [29,34, 81,55, 47,115] # P3/8
|
56 |
+
- [105,124, 207,107, 113,259] # P4/16
|
57 |
+
- [247,238, 222,500, 563,227] # P5/32
|
58 |
+
- [501,476, 376,939, 749,711] # P6/64
|
59 |
+
- [1126,489, 801,1222, 1618,1227] # P7/128
|
yolov5/models/hub/yolov3-spp.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
# darknet53 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
16 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
17 |
+
[-1, 1, Bottleneck, [64]],
|
18 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
19 |
+
[-1, 2, Bottleneck, [128]],
|
20 |
+
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
21 |
+
[-1, 8, Bottleneck, [256]],
|
22 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
23 |
+
[-1, 8, Bottleneck, [512]],
|
24 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
25 |
+
[-1, 4, Bottleneck, [1024]], # 10
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv3-SPP head
|
29 |
+
head:
|
30 |
+
[[-1, 1, Bottleneck, [1024, False]],
|
31 |
+
[-1, 1, SPP, [512, [5, 9, 13]]],
|
32 |
+
[-1, 1, Conv, [1024, 3, 1]],
|
33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
34 |
+
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
35 |
+
|
36 |
+
[-2, 1, Conv, [256, 1, 1]],
|
37 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
38 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
39 |
+
[-1, 1, Bottleneck, [512, False]],
|
40 |
+
[-1, 1, Bottleneck, [512, False]],
|
41 |
+
[-1, 1, Conv, [256, 1, 1]],
|
42 |
+
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
43 |
+
|
44 |
+
[-2, 1, Conv, [128, 1, 1]],
|
45 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
46 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
47 |
+
[-1, 1, Bottleneck, [256, False]],
|
48 |
+
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
49 |
+
|
50 |
+
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
51 |
+
]
|
yolov5/models/hub/yolov3-tiny.yaml
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,14, 23,27, 37,58] # P4/16
|
9 |
+
- [81,82, 135,169, 344,319] # P5/32
|
10 |
+
|
11 |
+
# YOLOv3-tiny backbone
|
12 |
+
backbone:
|
13 |
+
# [from, number, module, args]
|
14 |
+
[[-1, 1, Conv, [16, 3, 1]], # 0
|
15 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
|
16 |
+
[-1, 1, Conv, [32, 3, 1]],
|
17 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
|
18 |
+
[-1, 1, Conv, [64, 3, 1]],
|
19 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
|
20 |
+
[-1, 1, Conv, [128, 3, 1]],
|
21 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
|
22 |
+
[-1, 1, Conv, [256, 3, 1]],
|
23 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
|
24 |
+
[-1, 1, Conv, [512, 3, 1]],
|
25 |
+
[-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
|
26 |
+
[-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
|
27 |
+
]
|
28 |
+
|
29 |
+
# YOLOv3-tiny head
|
30 |
+
head:
|
31 |
+
[[-1, 1, Conv, [1024, 3, 1]],
|
32 |
+
[-1, 1, Conv, [256, 1, 1]],
|
33 |
+
[-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
|
34 |
+
|
35 |
+
[-2, 1, Conv, [128, 1, 1]],
|
36 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
37 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
38 |
+
[-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
|
39 |
+
|
40 |
+
[[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
|
41 |
+
]
|
yolov5/models/hub/yolov3.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
# darknet53 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
16 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
17 |
+
[-1, 1, Bottleneck, [64]],
|
18 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
19 |
+
[-1, 2, Bottleneck, [128]],
|
20 |
+
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
21 |
+
[-1, 8, Bottleneck, [256]],
|
22 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
23 |
+
[-1, 8, Bottleneck, [512]],
|
24 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
25 |
+
[-1, 4, Bottleneck, [1024]], # 10
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv3 head
|
29 |
+
head:
|
30 |
+
[[-1, 1, Bottleneck, [1024, False]],
|
31 |
+
[-1, 1, Conv, [512, [1, 1]]],
|
32 |
+
[-1, 1, Conv, [1024, 3, 1]],
|
33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
34 |
+
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
35 |
+
|
36 |
+
[-2, 1, Conv, [256, 1, 1]],
|
37 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
38 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
39 |
+
[-1, 1, Bottleneck, [512, False]],
|
40 |
+
[-1, 1, Bottleneck, [512, False]],
|
41 |
+
[-1, 1, Conv, [256, 1, 1]],
|
42 |
+
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
43 |
+
|
44 |
+
[-2, 1, Conv, [128, 1, 1]],
|
45 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
46 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
47 |
+
[-1, 1, Bottleneck, [256, False]],
|
48 |
+
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
49 |
+
|
50 |
+
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
51 |
+
]
|
yolov5/models/hub/yolov5-bifpn.yaml
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
# YOLOv5 v6.0 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
17 |
+
[-1, 3, C3, [128]],
|
18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
19 |
+
[-1, 6, C3, [256]],
|
20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
21 |
+
[-1, 9, C3, [512]],
|
22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
23 |
+
[-1, 3, C3, [1024]],
|
24 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
25 |
+
]
|
26 |
+
|
27 |
+
# YOLOv5 v6.0 BiFPN head
|
28 |
+
head:
|
29 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
32 |
+
[-1, 3, C3, [512, False]], # 13
|
33 |
+
|
34 |
+
[-1, 1, Conv, [256, 1, 1]],
|
35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
37 |
+
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
38 |
+
|
39 |
+
[-1, 1, Conv, [256, 3, 2]],
|
40 |
+
[[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change
|
41 |
+
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
42 |
+
|
43 |
+
[-1, 1, Conv, [512, 3, 2]],
|
44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
45 |
+
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
46 |
+
|
47 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
48 |
+
]
|