Spaces:
Sleeping
Sleeping
shriarul5273
commited on
Commit
·
3959175
1
Parent(s):
ab1437a
initial commit
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- .github/workflows/huggingface.yml +25 -0
- __pycache__/export.cpython-38.pyc +0 -0
- app.py +176 -0
- data/coco.yaml +116 -0
- data/coco128.yaml +101 -0
- data/images/bus.jpg +0 -0
- data/images/zidane.jpg +0 -0
- data/time.csv +2 -0
- data/video/input_0.mp4 +3 -0
- data/video/input_1.mp4 +3 -0
- export.py +652 -0
- models/__init__.py +0 -0
- models/__pycache__/__init__.cpython-310.pyc +0 -0
- models/__pycache__/__init__.cpython-38.pyc +0 -0
- models/__pycache__/common.cpython-310.pyc +0 -0
- models/__pycache__/common.cpython-38.pyc +0 -0
- models/__pycache__/experimental.cpython-38.pyc +0 -0
- models/__pycache__/yolo.cpython-38.pyc +0 -0
- models/common.py +860 -0
- models/experimental.py +111 -0
- models/hub/anchors.yaml +59 -0
- models/hub/yolov3-spp.yaml +51 -0
- models/hub/yolov3-tiny.yaml +41 -0
- models/hub/yolov3.yaml +51 -0
- models/hub/yolov5-bifpn.yaml +48 -0
- models/hub/yolov5-fpn.yaml +42 -0
- models/hub/yolov5-p2.yaml +54 -0
- models/hub/yolov5-p34.yaml +41 -0
- models/hub/yolov5-p6.yaml +56 -0
- models/hub/yolov5-p7.yaml +67 -0
- models/hub/yolov5-panet.yaml +48 -0
- models/hub/yolov5l6.yaml +60 -0
- models/hub/yolov5m6.yaml +60 -0
- models/hub/yolov5n6.yaml +60 -0
- models/hub/yolov5s-LeakyReLU.yaml +49 -0
- models/hub/yolov5s-ghost.yaml +48 -0
- models/hub/yolov5s-transformer.yaml +48 -0
- models/hub/yolov5s6.yaml +60 -0
- models/hub/yolov5x6.yaml +60 -0
- models/segment/yolov5l-seg.yaml +48 -0
- models/segment/yolov5m-seg.yaml +48 -0
- models/segment/yolov5n-seg.yaml +48 -0
- models/segment/yolov5s-seg.yaml +48 -0
- models/segment/yolov5x-seg.yaml +48 -0
- models/tf.py +608 -0
- models/yolo.py +391 -0
- models/yolov5l.yaml +48 -0
- models/yolov5m.yaml +48 -0
- models/yolov5n.yaml +48 -0
.gitattributes
CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/huggingface.yml
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Deploy to Hugging Face Spaces
|
2 |
+
on:
|
3 |
+
push:
|
4 |
+
branches: [main]
|
5 |
+
|
6 |
+
# to run this workflow manually from the Actions tab
|
7 |
+
workflow_dispatch:
|
8 |
+
|
9 |
+
jobs:
|
10 |
+
sync-to-hub:
|
11 |
+
runs-on: ubuntu-latest
|
12 |
+
steps:
|
13 |
+
- uses: actions/checkout@v3
|
14 |
+
with:
|
15 |
+
fetch-depth: 0
|
16 |
+
- name: Add remote
|
17 |
+
env:
|
18 |
+
HF: ${{secrets.HF_TOKEN }}
|
19 |
+
HF_USER: ${{secrets.HF_USER }}
|
20 |
+
run: git remote add space https://$HF_USER:[email protected]/spaces/$HF_USER/Yolov5
|
21 |
+
- name: Push to hub
|
22 |
+
env:
|
23 |
+
HF: ${{ secrets.HF_TOKEN}}
|
24 |
+
HF_USER: ${{secrets.HF_USER }}
|
25 |
+
run: git push --force https://$HF_USER:[email protected]/spaces/$HF_USER/Yolov5
|
__pycache__/export.cpython-38.pyc
ADDED
Binary file (25.1 kB). View file
|
|
app.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from models.common import DetectMultiBackend
|
3 |
+
from utils.general import (check_img_size, cv2,
|
4 |
+
non_max_suppression, scale_boxes)
|
5 |
+
from utils.plots import Annotator, colors
|
6 |
+
import numpy as np
|
7 |
+
import gradio as gr
|
8 |
+
import pandas as pd
|
9 |
+
|
10 |
+
data = 'data/coco128.yaml'
|
11 |
+
|
12 |
+
|
13 |
+
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleup=True, stride=32):
|
14 |
+
# Resize and pad image while meeting stride-multiple constraints
|
15 |
+
shape = im.shape[:2] # current shape [height, width]
|
16 |
+
if isinstance(new_shape, int):
|
17 |
+
new_shape = (new_shape, new_shape)
|
18 |
+
|
19 |
+
# Scale ratio (new / old)
|
20 |
+
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
21 |
+
if not scaleup: # only scale down, do not scale up (for better val mAP)
|
22 |
+
r = min(r, 1.0)
|
23 |
+
|
24 |
+
# Compute padding
|
25 |
+
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
|
26 |
+
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
|
27 |
+
|
28 |
+
if auto: # minimum rectangle
|
29 |
+
dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
|
30 |
+
|
31 |
+
dw /= 2 # divide padding into 2 sides
|
32 |
+
dh /= 2
|
33 |
+
|
34 |
+
if shape[::-1] != new_unpad: # resize
|
35 |
+
im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
|
36 |
+
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
|
37 |
+
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
|
38 |
+
im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
|
39 |
+
return im, r, (dw, dh)
|
40 |
+
|
41 |
+
names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
|
42 |
+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
|
43 |
+
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
|
44 |
+
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
|
45 |
+
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
|
46 |
+
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
|
47 |
+
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
|
48 |
+
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
|
49 |
+
'hair drier', 'toothbrush']
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
def detect(im,model,device,iou_threshold=0.45,confidence_threshold=0.25):
|
55 |
+
im = np.array(im)
|
56 |
+
imgsz=(640, 640) # inference size (pixels)
|
57 |
+
data = 'data/coco128.yaml' # data.yaml path
|
58 |
+
# Load model
|
59 |
+
stride, names, pt = model.stride, model.names, model.pt
|
60 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
61 |
+
|
62 |
+
# Run inference
|
63 |
+
# model.warmup(imgsz=(1)) # warmup
|
64 |
+
|
65 |
+
imgs = im.copy() # for NMS
|
66 |
+
|
67 |
+
image, ratio, dwdh = letterbox(im, auto=False)
|
68 |
+
print(image.shape)
|
69 |
+
image = image.transpose((2, 0, 1))
|
70 |
+
img = torch.from_numpy(image).to(device)
|
71 |
+
img = img.float() # uint8 to fp16/32
|
72 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
73 |
+
if img.ndimension() == 3:
|
74 |
+
img = img.unsqueeze(0)
|
75 |
+
|
76 |
+
# Inference
|
77 |
+
pred = model(img, augment=False)
|
78 |
+
|
79 |
+
# NMS
|
80 |
+
pred = non_max_suppression(pred, confidence_threshold, iou_threshold, None, False, max_det=10)
|
81 |
+
|
82 |
+
|
83 |
+
for i, det in enumerate(pred): # detections per image
|
84 |
+
if len(det):
|
85 |
+
# Rescale boxes from img_size to im0 size
|
86 |
+
det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], imgs.shape).round()
|
87 |
+
|
88 |
+
annotator = Annotator(imgs, line_width=3, example=str(names))
|
89 |
+
hide_labels = False
|
90 |
+
hide_conf = False
|
91 |
+
# Write results
|
92 |
+
for *xyxy, conf, cls in reversed(det):
|
93 |
+
c = int(cls) # integer class
|
94 |
+
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
|
95 |
+
print(xyxy,label)
|
96 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
97 |
+
|
98 |
+
return imgs
|
99 |
+
|
100 |
+
|
101 |
+
def inference(img,model_link,iou_threshold,confidence_threshold):
|
102 |
+
print(model_link)
|
103 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
104 |
+
# Load model
|
105 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
106 |
+
model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
|
107 |
+
return detect(img,model,device,iou_threshold,confidence_threshold)
|
108 |
+
|
109 |
+
|
110 |
+
def inference2(video,model_link,iou_threshold,confidence_threshold):
|
111 |
+
print(model_link)
|
112 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
113 |
+
# Load model
|
114 |
+
model = DetectMultiBackend('weights/'+str(model_link)+'.pt', device=device, dnn=False, data=data, fp16=False)
|
115 |
+
frames = cv2.VideoCapture(video)
|
116 |
+
fps = frames.get(cv2.CAP_PROP_FPS)
|
117 |
+
image_size = (int(frames.get(cv2.CAP_PROP_FRAME_WIDTH)),int(frames.get(cv2.CAP_PROP_FRAME_HEIGHT)))
|
118 |
+
finalVideo = cv2.VideoWriter('output.mp4',cv2.VideoWriter_fourcc(*'VP90'), fps, image_size)
|
119 |
+
p = 1
|
120 |
+
while frames.isOpened():
|
121 |
+
ret,frame = frames.read()
|
122 |
+
if not ret:
|
123 |
+
break
|
124 |
+
frame = detect(frame,model,device,iou_threshold,confidence_threshold)
|
125 |
+
finalVideo.write(frame)
|
126 |
+
frames.release()
|
127 |
+
finalVideo.release()
|
128 |
+
return 'output.mp4'
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
examples_images = ['data/images/bus.jpg',
|
133 |
+
'data/images/zidane.jpg',]
|
134 |
+
examples_videos = ['data/video/input_0.mp4',
|
135 |
+
'data/video/input_1.mp4']
|
136 |
+
|
137 |
+
models = ['yolov5n','yolov5s','yolov5m','yolov5l','yolov5x']
|
138 |
+
|
139 |
+
with gr.Blocks() as demo:
|
140 |
+
csv = pd.read_csv('data/time.csv')
|
141 |
+
csv['id'] = csv['id'] + 1
|
142 |
+
csv.to_csv('data/time.csv',index=False)
|
143 |
+
gr.Markdown("## YOLOv5 Inference")
|
144 |
+
with gr.Tab("Image"):
|
145 |
+
gr.Markdown("## YOLOv5 Inference on Image")
|
146 |
+
with gr.Row():
|
147 |
+
image_input = gr.Image(type='pil', label="Input Image", source="upload")
|
148 |
+
image_output = gr.Image(type='pil', label="Output Image", source="upload")
|
149 |
+
image_drop = gr.Dropdown(choices=models,value=models[0])
|
150 |
+
image_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
|
151 |
+
image_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
|
152 |
+
gr.Examples(examples=examples_images,inputs=image_input,outputs=image_output)
|
153 |
+
text_button = gr.Button("Detect")
|
154 |
+
with gr.Tab("Video"):
|
155 |
+
gr.Markdown("## YOLOv5 Inference on Video")
|
156 |
+
with gr.Row():
|
157 |
+
video_input = gr.Video(type='pil', label="Input Image", source="upload")
|
158 |
+
video_output = gr.Video(type="pil", label="Output Image",format="mp4")
|
159 |
+
video_drop = gr.Dropdown(choices=models,value=models[0])
|
160 |
+
video_iou_threshold = gr.Slider(label="IOU Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.45)
|
161 |
+
video_conf_threshold = gr.Slider(label="Confidence Threshold",interactive=True, minimum=0.0, maximum=1.0, value=0.25)
|
162 |
+
gr.Examples(examples=examples_videos,inputs=video_input,outputs=video_output)
|
163 |
+
video_button = gr.Button("Detect")
|
164 |
+
|
165 |
+
with gr.Tab("Webcam Video"):
|
166 |
+
gr.Markdown("## YOLOv5 Inference on Webcam Video")
|
167 |
+
gr.Markdown("Coming Soon")
|
168 |
+
|
169 |
+
text_button.click(inference, inputs=[image_input,image_drop,
|
170 |
+
image_iou_threshold,image_conf_threshold],
|
171 |
+
outputs=image_output)
|
172 |
+
video_button.click(inference2, inputs=[video_input,video_drop,
|
173 |
+
video_iou_threshold,video_conf_threshold],
|
174 |
+
outputs=video_output)
|
175 |
+
|
176 |
+
demo.launch()
|
data/coco.yaml
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 (20.1 GB)
|
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 |
+
names:
|
18 |
+
0: person
|
19 |
+
1: bicycle
|
20 |
+
2: car
|
21 |
+
3: motorcycle
|
22 |
+
4: airplane
|
23 |
+
5: bus
|
24 |
+
6: train
|
25 |
+
7: truck
|
26 |
+
8: boat
|
27 |
+
9: traffic light
|
28 |
+
10: fire hydrant
|
29 |
+
11: stop sign
|
30 |
+
12: parking meter
|
31 |
+
13: bench
|
32 |
+
14: bird
|
33 |
+
15: cat
|
34 |
+
16: dog
|
35 |
+
17: horse
|
36 |
+
18: sheep
|
37 |
+
19: cow
|
38 |
+
20: elephant
|
39 |
+
21: bear
|
40 |
+
22: zebra
|
41 |
+
23: giraffe
|
42 |
+
24: backpack
|
43 |
+
25: umbrella
|
44 |
+
26: handbag
|
45 |
+
27: tie
|
46 |
+
28: suitcase
|
47 |
+
29: frisbee
|
48 |
+
30: skis
|
49 |
+
31: snowboard
|
50 |
+
32: sports ball
|
51 |
+
33: kite
|
52 |
+
34: baseball bat
|
53 |
+
35: baseball glove
|
54 |
+
36: skateboard
|
55 |
+
37: surfboard
|
56 |
+
38: tennis racket
|
57 |
+
39: bottle
|
58 |
+
40: wine glass
|
59 |
+
41: cup
|
60 |
+
42: fork
|
61 |
+
43: knife
|
62 |
+
44: spoon
|
63 |
+
45: bowl
|
64 |
+
46: banana
|
65 |
+
47: apple
|
66 |
+
48: sandwich
|
67 |
+
49: orange
|
68 |
+
50: broccoli
|
69 |
+
51: carrot
|
70 |
+
52: hot dog
|
71 |
+
53: pizza
|
72 |
+
54: donut
|
73 |
+
55: cake
|
74 |
+
56: chair
|
75 |
+
57: couch
|
76 |
+
58: potted plant
|
77 |
+
59: bed
|
78 |
+
60: dining table
|
79 |
+
61: toilet
|
80 |
+
62: tv
|
81 |
+
63: laptop
|
82 |
+
64: mouse
|
83 |
+
65: remote
|
84 |
+
66: keyboard
|
85 |
+
67: cell phone
|
86 |
+
68: microwave
|
87 |
+
69: oven
|
88 |
+
70: toaster
|
89 |
+
71: sink
|
90 |
+
72: refrigerator
|
91 |
+
73: book
|
92 |
+
74: clock
|
93 |
+
75: vase
|
94 |
+
76: scissors
|
95 |
+
77: teddy bear
|
96 |
+
78: hair drier
|
97 |
+
79: toothbrush
|
98 |
+
|
99 |
+
|
100 |
+
# Download script/URL (optional)
|
101 |
+
download: |
|
102 |
+
from utils.general import download, Path
|
103 |
+
|
104 |
+
|
105 |
+
# Download labels
|
106 |
+
segments = False # segment or box labels
|
107 |
+
dir = Path(yaml['path']) # dataset root dir
|
108 |
+
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
109 |
+
urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
|
110 |
+
download(urls, dir=dir.parent)
|
111 |
+
|
112 |
+
# Download data
|
113 |
+
urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
|
114 |
+
'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
|
115 |
+
'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
|
116 |
+
download(urls, dir=dir / 'images', threads=3)
|
data/coco128.yaml
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 (7 MB)
|
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 |
+
names:
|
18 |
+
0: person
|
19 |
+
1: bicycle
|
20 |
+
2: car
|
21 |
+
3: motorcycle
|
22 |
+
4: airplane
|
23 |
+
5: bus
|
24 |
+
6: train
|
25 |
+
7: truck
|
26 |
+
8: boat
|
27 |
+
9: traffic light
|
28 |
+
10: fire hydrant
|
29 |
+
11: stop sign
|
30 |
+
12: parking meter
|
31 |
+
13: bench
|
32 |
+
14: bird
|
33 |
+
15: cat
|
34 |
+
16: dog
|
35 |
+
17: horse
|
36 |
+
18: sheep
|
37 |
+
19: cow
|
38 |
+
20: elephant
|
39 |
+
21: bear
|
40 |
+
22: zebra
|
41 |
+
23: giraffe
|
42 |
+
24: backpack
|
43 |
+
25: umbrella
|
44 |
+
26: handbag
|
45 |
+
27: tie
|
46 |
+
28: suitcase
|
47 |
+
29: frisbee
|
48 |
+
30: skis
|
49 |
+
31: snowboard
|
50 |
+
32: sports ball
|
51 |
+
33: kite
|
52 |
+
34: baseball bat
|
53 |
+
35: baseball glove
|
54 |
+
36: skateboard
|
55 |
+
37: surfboard
|
56 |
+
38: tennis racket
|
57 |
+
39: bottle
|
58 |
+
40: wine glass
|
59 |
+
41: cup
|
60 |
+
42: fork
|
61 |
+
43: knife
|
62 |
+
44: spoon
|
63 |
+
45: bowl
|
64 |
+
46: banana
|
65 |
+
47: apple
|
66 |
+
48: sandwich
|
67 |
+
49: orange
|
68 |
+
50: broccoli
|
69 |
+
51: carrot
|
70 |
+
52: hot dog
|
71 |
+
53: pizza
|
72 |
+
54: donut
|
73 |
+
55: cake
|
74 |
+
56: chair
|
75 |
+
57: couch
|
76 |
+
58: potted plant
|
77 |
+
59: bed
|
78 |
+
60: dining table
|
79 |
+
61: toilet
|
80 |
+
62: tv
|
81 |
+
63: laptop
|
82 |
+
64: mouse
|
83 |
+
65: remote
|
84 |
+
66: keyboard
|
85 |
+
67: cell phone
|
86 |
+
68: microwave
|
87 |
+
69: oven
|
88 |
+
70: toaster
|
89 |
+
71: sink
|
90 |
+
72: refrigerator
|
91 |
+
73: book
|
92 |
+
74: clock
|
93 |
+
75: vase
|
94 |
+
76: scissors
|
95 |
+
77: teddy bear
|
96 |
+
78: hair drier
|
97 |
+
79: toothbrush
|
98 |
+
|
99 |
+
|
100 |
+
# Download script/URL (optional)
|
101 |
+
download: https://ultralytics.com/assets/coco128.zip
|
data/images/bus.jpg
ADDED
data/images/zidane.jpg
ADDED
data/time.csv
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
id
|
2 |
+
2
|
data/video/input_0.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0305b8ba574b0b26c8d21b70dbd80aacbba13e813a99f5c4675982063ebd18a3
|
3 |
+
size 1103987
|
data/video/input_1.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:103c54e60a7abf381741b4bcc5e696f5d200fc2a4ff259cc779bbd511dc2dae1
|
3 |
+
size 1792081
|
export.py
ADDED
@@ -0,0 +1,652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
|
4 |
+
|
5 |
+
Format | `export.py --include` | Model
|
6 |
+
--- | --- | ---
|
7 |
+
PyTorch | - | yolov5s.pt
|
8 |
+
TorchScript | `torchscript` | yolov5s.torchscript
|
9 |
+
ONNX | `onnx` | yolov5s.onnx
|
10 |
+
OpenVINO | `openvino` | yolov5s_openvino_model/
|
11 |
+
TensorRT | `engine` | yolov5s.engine
|
12 |
+
CoreML | `coreml` | yolov5s.mlmodel
|
13 |
+
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
|
14 |
+
TensorFlow GraphDef | `pb` | yolov5s.pb
|
15 |
+
TensorFlow Lite | `tflite` | yolov5s.tflite
|
16 |
+
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
|
17 |
+
TensorFlow.js | `tfjs` | yolov5s_web_model/
|
18 |
+
PaddlePaddle | `paddle` | yolov5s_paddle_model/
|
19 |
+
|
20 |
+
Requirements:
|
21 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
|
22 |
+
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
|
23 |
+
|
24 |
+
Usage:
|
25 |
+
$ python export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
|
26 |
+
|
27 |
+
Inference:
|
28 |
+
$ python detect.py --weights yolov5s.pt # PyTorch
|
29 |
+
yolov5s.torchscript # TorchScript
|
30 |
+
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
31 |
+
yolov5s_openvino_model # OpenVINO
|
32 |
+
yolov5s.engine # TensorRT
|
33 |
+
yolov5s.mlmodel # CoreML (macOS-only)
|
34 |
+
yolov5s_saved_model # TensorFlow SavedModel
|
35 |
+
yolov5s.pb # TensorFlow GraphDef
|
36 |
+
yolov5s.tflite # TensorFlow Lite
|
37 |
+
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
38 |
+
yolov5s_paddle_model # PaddlePaddle
|
39 |
+
|
40 |
+
TensorFlow.js:
|
41 |
+
$ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
|
42 |
+
$ npm install
|
43 |
+
$ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
|
44 |
+
$ npm start
|
45 |
+
"""
|
46 |
+
|
47 |
+
import argparse
|
48 |
+
import contextlib
|
49 |
+
import json
|
50 |
+
import os
|
51 |
+
import platform
|
52 |
+
import re
|
53 |
+
import subprocess
|
54 |
+
import sys
|
55 |
+
import time
|
56 |
+
import warnings
|
57 |
+
from pathlib import Path
|
58 |
+
|
59 |
+
import pandas as pd
|
60 |
+
import torch
|
61 |
+
from torch.utils.mobile_optimizer import optimize_for_mobile
|
62 |
+
|
63 |
+
FILE = Path(__file__).resolve()
|
64 |
+
ROOT = FILE.parents[0] # YOLOv5 root directory
|
65 |
+
if str(ROOT) not in sys.path:
|
66 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
67 |
+
if platform.system() != 'Windows':
|
68 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
69 |
+
|
70 |
+
from models.experimental import attempt_load
|
71 |
+
from models.yolo import ClassificationModel, Detect, DetectionModel, SegmentationModel
|
72 |
+
from utils.dataloaders import LoadImages
|
73 |
+
from utils.general import (LOGGER, Profile, check_dataset, check_img_size, check_requirements, check_version,
|
74 |
+
check_yaml, colorstr, file_size, get_default_args, print_args, url2file, yaml_save)
|
75 |
+
from utils.torch_utils import select_device, smart_inference_mode
|
76 |
+
|
77 |
+
MACOS = platform.system() == 'Darwin' # macOS environment
|
78 |
+
|
79 |
+
|
80 |
+
def export_formats():
|
81 |
+
# YOLOv5 export formats
|
82 |
+
x = [
|
83 |
+
['PyTorch', '-', '.pt', True, True],
|
84 |
+
['TorchScript', 'torchscript', '.torchscript', True, True],
|
85 |
+
['ONNX', 'onnx', '.onnx', True, True],
|
86 |
+
['OpenVINO', 'openvino', '_openvino_model', True, False],
|
87 |
+
['TensorRT', 'engine', '.engine', False, True],
|
88 |
+
['CoreML', 'coreml', '.mlmodel', True, False],
|
89 |
+
['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
|
90 |
+
['TensorFlow GraphDef', 'pb', '.pb', True, True],
|
91 |
+
['TensorFlow Lite', 'tflite', '.tflite', True, False],
|
92 |
+
['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
|
93 |
+
['TensorFlow.js', 'tfjs', '_web_model', False, False],
|
94 |
+
['PaddlePaddle', 'paddle', '_paddle_model', True, True],]
|
95 |
+
return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
|
96 |
+
|
97 |
+
|
98 |
+
def try_export(inner_func):
|
99 |
+
# YOLOv5 export decorator, i..e @try_export
|
100 |
+
inner_args = get_default_args(inner_func)
|
101 |
+
|
102 |
+
def outer_func(*args, **kwargs):
|
103 |
+
prefix = inner_args['prefix']
|
104 |
+
try:
|
105 |
+
with Profile() as dt:
|
106 |
+
f, model = inner_func(*args, **kwargs)
|
107 |
+
LOGGER.info(f'{prefix} export success ✅ {dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)')
|
108 |
+
return f, model
|
109 |
+
except Exception as e:
|
110 |
+
LOGGER.info(f'{prefix} export failure ❌ {dt.t:.1f}s: {e}')
|
111 |
+
return None, None
|
112 |
+
|
113 |
+
return outer_func
|
114 |
+
|
115 |
+
|
116 |
+
@try_export
|
117 |
+
def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
|
118 |
+
# YOLOv5 TorchScript model export
|
119 |
+
LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
|
120 |
+
f = file.with_suffix('.torchscript')
|
121 |
+
|
122 |
+
ts = torch.jit.trace(model, im, strict=False)
|
123 |
+
d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
|
124 |
+
extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
|
125 |
+
if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
|
126 |
+
optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
|
127 |
+
else:
|
128 |
+
ts.save(str(f), _extra_files=extra_files)
|
129 |
+
return f, None
|
130 |
+
|
131 |
+
|
132 |
+
@try_export
|
133 |
+
def export_onnx(model, im, file, opset, dynamic, simplify, prefix=colorstr('ONNX:')):
|
134 |
+
# YOLOv5 ONNX export
|
135 |
+
check_requirements('onnx')
|
136 |
+
import onnx
|
137 |
+
|
138 |
+
LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
|
139 |
+
f = file.with_suffix('.onnx')
|
140 |
+
|
141 |
+
output_names = ['output0', 'output1'] if isinstance(model, SegmentationModel) else ['output0']
|
142 |
+
if dynamic:
|
143 |
+
dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}} # shape(1,3,640,640)
|
144 |
+
if isinstance(model, SegmentationModel):
|
145 |
+
dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
|
146 |
+
dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'} # shape(1,32,160,160)
|
147 |
+
elif isinstance(model, DetectionModel):
|
148 |
+
dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
|
149 |
+
|
150 |
+
torch.onnx.export(
|
151 |
+
model.cpu() if dynamic else model, # --dynamic only compatible with cpu
|
152 |
+
im.cpu() if dynamic else im,
|
153 |
+
f,
|
154 |
+
verbose=False,
|
155 |
+
opset_version=opset,
|
156 |
+
do_constant_folding=True,
|
157 |
+
input_names=['images'],
|
158 |
+
output_names=output_names,
|
159 |
+
dynamic_axes=dynamic or None)
|
160 |
+
|
161 |
+
# Checks
|
162 |
+
model_onnx = onnx.load(f) # load onnx model
|
163 |
+
onnx.checker.check_model(model_onnx) # check onnx model
|
164 |
+
|
165 |
+
# Metadata
|
166 |
+
d = {'stride': int(max(model.stride)), 'names': model.names}
|
167 |
+
for k, v in d.items():
|
168 |
+
meta = model_onnx.metadata_props.add()
|
169 |
+
meta.key, meta.value = k, str(v)
|
170 |
+
onnx.save(model_onnx, f)
|
171 |
+
|
172 |
+
# Simplify
|
173 |
+
if simplify:
|
174 |
+
try:
|
175 |
+
cuda = torch.cuda.is_available()
|
176 |
+
check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1'))
|
177 |
+
import onnxsim
|
178 |
+
|
179 |
+
LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
180 |
+
model_onnx, check = onnxsim.simplify(model_onnx)
|
181 |
+
assert check, 'assert check failed'
|
182 |
+
onnx.save(model_onnx, f)
|
183 |
+
except Exception as e:
|
184 |
+
LOGGER.info(f'{prefix} simplifier failure: {e}')
|
185 |
+
return f, model_onnx
|
186 |
+
|
187 |
+
|
188 |
+
@try_export
|
189 |
+
def export_openvino(file, metadata, half, prefix=colorstr('OpenVINO:')):
|
190 |
+
# YOLOv5 OpenVINO export
|
191 |
+
check_requirements('openvino-dev') # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
192 |
+
import openvino.inference_engine as ie
|
193 |
+
|
194 |
+
LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
|
195 |
+
f = str(file).replace('.pt', f'_openvino_model{os.sep}')
|
196 |
+
|
197 |
+
cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
|
198 |
+
subprocess.run(cmd.split(), check=True, env=os.environ) # export
|
199 |
+
yaml_save(Path(f) / file.with_suffix('.yaml').name, metadata) # add metadata.yaml
|
200 |
+
return f, None
|
201 |
+
|
202 |
+
|
203 |
+
@try_export
|
204 |
+
def export_paddle(model, im, file, metadata, prefix=colorstr('PaddlePaddle:')):
|
205 |
+
# YOLOv5 Paddle export
|
206 |
+
check_requirements(('paddlepaddle', 'x2paddle'))
|
207 |
+
import x2paddle
|
208 |
+
from x2paddle.convert import pytorch2paddle
|
209 |
+
|
210 |
+
LOGGER.info(f'\n{prefix} starting export with X2Paddle {x2paddle.__version__}...')
|
211 |
+
f = str(file).replace('.pt', f'_paddle_model{os.sep}')
|
212 |
+
|
213 |
+
pytorch2paddle(module=model, save_dir=f, jit_type='trace', input_examples=[im]) # export
|
214 |
+
yaml_save(Path(f) / file.with_suffix('.yaml').name, metadata) # add metadata.yaml
|
215 |
+
return f, None
|
216 |
+
|
217 |
+
|
218 |
+
@try_export
|
219 |
+
def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
|
220 |
+
# YOLOv5 CoreML export
|
221 |
+
check_requirements('coremltools')
|
222 |
+
import coremltools as ct
|
223 |
+
|
224 |
+
LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
|
225 |
+
f = file.with_suffix('.mlmodel')
|
226 |
+
|
227 |
+
ts = torch.jit.trace(model, im, strict=False) # TorchScript model
|
228 |
+
ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
|
229 |
+
bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
|
230 |
+
if bits < 32:
|
231 |
+
if MACOS: # quantization only supported on macOS
|
232 |
+
with warnings.catch_warnings():
|
233 |
+
warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
|
234 |
+
ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
|
235 |
+
else:
|
236 |
+
print(f'{prefix} quantization only supported on macOS, skipping...')
|
237 |
+
ct_model.save(f)
|
238 |
+
return f, ct_model
|
239 |
+
|
240 |
+
|
241 |
+
@try_export
|
242 |
+
def export_engine(model, im, file, half, dynamic, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
|
243 |
+
# YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
|
244 |
+
assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
|
245 |
+
try:
|
246 |
+
import tensorrt as trt
|
247 |
+
except Exception:
|
248 |
+
if platform.system() == 'Linux':
|
249 |
+
check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')
|
250 |
+
import tensorrt as trt
|
251 |
+
|
252 |
+
if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
|
253 |
+
grid = model.model[-1].anchor_grid
|
254 |
+
model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
|
255 |
+
export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
|
256 |
+
model.model[-1].anchor_grid = grid
|
257 |
+
else: # TensorRT >= 8
|
258 |
+
check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
|
259 |
+
export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
|
260 |
+
onnx = file.with_suffix('.onnx')
|
261 |
+
|
262 |
+
LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
|
263 |
+
assert onnx.exists(), f'failed to export ONNX file: {onnx}'
|
264 |
+
f = file.with_suffix('.engine') # TensorRT engine file
|
265 |
+
logger = trt.Logger(trt.Logger.INFO)
|
266 |
+
if verbose:
|
267 |
+
logger.min_severity = trt.Logger.Severity.VERBOSE
|
268 |
+
|
269 |
+
builder = trt.Builder(logger)
|
270 |
+
config = builder.create_builder_config()
|
271 |
+
config.max_workspace_size = workspace * 1 << 30
|
272 |
+
# config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
|
273 |
+
|
274 |
+
flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
|
275 |
+
network = builder.create_network(flag)
|
276 |
+
parser = trt.OnnxParser(network, logger)
|
277 |
+
if not parser.parse_from_file(str(onnx)):
|
278 |
+
raise RuntimeError(f'failed to load ONNX file: {onnx}')
|
279 |
+
|
280 |
+
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
281 |
+
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
282 |
+
for inp in inputs:
|
283 |
+
LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
|
284 |
+
for out in outputs:
|
285 |
+
LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
|
286 |
+
|
287 |
+
if dynamic:
|
288 |
+
if im.shape[0] <= 1:
|
289 |
+
LOGGER.warning(f"{prefix} WARNING ⚠️ --dynamic model requires maximum --batch-size argument")
|
290 |
+
profile = builder.create_optimization_profile()
|
291 |
+
for inp in inputs:
|
292 |
+
profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape)
|
293 |
+
config.add_optimization_profile(profile)
|
294 |
+
|
295 |
+
LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine as {f}')
|
296 |
+
if builder.platform_has_fast_fp16 and half:
|
297 |
+
config.set_flag(trt.BuilderFlag.FP16)
|
298 |
+
with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
|
299 |
+
t.write(engine.serialize())
|
300 |
+
return f, None
|
301 |
+
|
302 |
+
|
303 |
+
@try_export
|
304 |
+
def export_saved_model(model,
|
305 |
+
im,
|
306 |
+
file,
|
307 |
+
dynamic,
|
308 |
+
tf_nms=False,
|
309 |
+
agnostic_nms=False,
|
310 |
+
topk_per_class=100,
|
311 |
+
topk_all=100,
|
312 |
+
iou_thres=0.45,
|
313 |
+
conf_thres=0.25,
|
314 |
+
keras=False,
|
315 |
+
prefix=colorstr('TensorFlow SavedModel:')):
|
316 |
+
# YOLOv5 TensorFlow SavedModel export
|
317 |
+
try:
|
318 |
+
import tensorflow as tf
|
319 |
+
except Exception:
|
320 |
+
check_requirements(f"tensorflow{'' if torch.cuda.is_available() else '-macos' if MACOS else '-cpu'}")
|
321 |
+
import tensorflow as tf
|
322 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
323 |
+
|
324 |
+
from models.tf import TFModel
|
325 |
+
|
326 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
327 |
+
f = str(file).replace('.pt', '_saved_model')
|
328 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
329 |
+
|
330 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
331 |
+
im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
|
332 |
+
_ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
333 |
+
inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
|
334 |
+
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
|
335 |
+
keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
|
336 |
+
keras_model.trainable = False
|
337 |
+
keras_model.summary()
|
338 |
+
if keras:
|
339 |
+
keras_model.save(f, save_format='tf')
|
340 |
+
else:
|
341 |
+
spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
|
342 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
343 |
+
m = m.get_concrete_function(spec)
|
344 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
345 |
+
tfm = tf.Module()
|
346 |
+
tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x), [spec])
|
347 |
+
tfm.__call__(im)
|
348 |
+
tf.saved_model.save(tfm,
|
349 |
+
f,
|
350 |
+
options=tf.saved_model.SaveOptions(experimental_custom_gradients=False) if check_version(
|
351 |
+
tf.__version__, '2.6') else tf.saved_model.SaveOptions())
|
352 |
+
return f, keras_model
|
353 |
+
|
354 |
+
|
355 |
+
@try_export
|
356 |
+
def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
|
357 |
+
# YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
|
358 |
+
import tensorflow as tf
|
359 |
+
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
|
360 |
+
|
361 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
362 |
+
f = file.with_suffix('.pb')
|
363 |
+
|
364 |
+
m = tf.function(lambda x: keras_model(x)) # full model
|
365 |
+
m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
|
366 |
+
frozen_func = convert_variables_to_constants_v2(m)
|
367 |
+
frozen_func.graph.as_graph_def()
|
368 |
+
tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
|
369 |
+
return f, None
|
370 |
+
|
371 |
+
|
372 |
+
@try_export
|
373 |
+
def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
|
374 |
+
# YOLOv5 TensorFlow Lite export
|
375 |
+
import tensorflow as tf
|
376 |
+
|
377 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
|
378 |
+
batch_size, ch, *imgsz = list(im.shape) # BCHW
|
379 |
+
f = str(file).replace('.pt', '-fp16.tflite')
|
380 |
+
|
381 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
|
382 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
|
383 |
+
converter.target_spec.supported_types = [tf.float16]
|
384 |
+
converter.optimizations = [tf.lite.Optimize.DEFAULT]
|
385 |
+
if int8:
|
386 |
+
from models.tf import representative_dataset_gen
|
387 |
+
dataset = LoadImages(check_dataset(check_yaml(data))['train'], img_size=imgsz, auto=False)
|
388 |
+
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
|
389 |
+
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
390 |
+
converter.target_spec.supported_types = []
|
391 |
+
converter.inference_input_type = tf.uint8 # or tf.int8
|
392 |
+
converter.inference_output_type = tf.uint8 # or tf.int8
|
393 |
+
converter.experimental_new_quantizer = True
|
394 |
+
f = str(file).replace('.pt', '-int8.tflite')
|
395 |
+
if nms or agnostic_nms:
|
396 |
+
converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
|
397 |
+
|
398 |
+
tflite_model = converter.convert()
|
399 |
+
open(f, "wb").write(tflite_model)
|
400 |
+
return f, None
|
401 |
+
|
402 |
+
|
403 |
+
@try_export
|
404 |
+
def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
|
405 |
+
# YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
|
406 |
+
cmd = 'edgetpu_compiler --version'
|
407 |
+
help_url = 'https://coral.ai/docs/edgetpu/compiler/'
|
408 |
+
assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
|
409 |
+
if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
|
410 |
+
LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
|
411 |
+
sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
|
412 |
+
for c in (
|
413 |
+
'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
|
414 |
+
'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
|
415 |
+
'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
|
416 |
+
subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
|
417 |
+
ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
|
418 |
+
|
419 |
+
LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
|
420 |
+
f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
|
421 |
+
f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
|
422 |
+
|
423 |
+
cmd = f"edgetpu_compiler -s -d -k 10 --out_dir {file.parent} {f_tfl}"
|
424 |
+
subprocess.run(cmd.split(), check=True)
|
425 |
+
return f, None
|
426 |
+
|
427 |
+
|
428 |
+
@try_export
|
429 |
+
def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
|
430 |
+
# YOLOv5 TensorFlow.js export
|
431 |
+
check_requirements('tensorflowjs')
|
432 |
+
import tensorflowjs as tfjs
|
433 |
+
|
434 |
+
LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
|
435 |
+
f = str(file).replace('.pt', '_web_model') # js dir
|
436 |
+
f_pb = file.with_suffix('.pb') # *.pb path
|
437 |
+
f_json = f'{f}/model.json' # *.json path
|
438 |
+
|
439 |
+
cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
|
440 |
+
f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
|
441 |
+
subprocess.run(cmd.split())
|
442 |
+
|
443 |
+
json = Path(f_json).read_text()
|
444 |
+
with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
|
445 |
+
subst = re.sub(
|
446 |
+
r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
|
447 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
448 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}, '
|
449 |
+
r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
|
450 |
+
r'"Identity_1": {"name": "Identity_1"}, '
|
451 |
+
r'"Identity_2": {"name": "Identity_2"}, '
|
452 |
+
r'"Identity_3": {"name": "Identity_3"}}}', json)
|
453 |
+
j.write(subst)
|
454 |
+
return f, None
|
455 |
+
|
456 |
+
|
457 |
+
def add_tflite_metadata(file, metadata, num_outputs):
|
458 |
+
# Add metadata to *.tflite models per https://www.tensorflow.org/lite/models/convert/metadata
|
459 |
+
with contextlib.suppress(ImportError):
|
460 |
+
# check_requirements('tflite_support')
|
461 |
+
from tflite_support import flatbuffers
|
462 |
+
from tflite_support import metadata as _metadata
|
463 |
+
from tflite_support import metadata_schema_py_generated as _metadata_fb
|
464 |
+
|
465 |
+
tmp_file = Path('/tmp/meta.txt')
|
466 |
+
with open(tmp_file, 'w') as meta_f:
|
467 |
+
meta_f.write(str(metadata))
|
468 |
+
|
469 |
+
model_meta = _metadata_fb.ModelMetadataT()
|
470 |
+
label_file = _metadata_fb.AssociatedFileT()
|
471 |
+
label_file.name = tmp_file.name
|
472 |
+
model_meta.associatedFiles = [label_file]
|
473 |
+
|
474 |
+
subgraph = _metadata_fb.SubGraphMetadataT()
|
475 |
+
subgraph.inputTensorMetadata = [_metadata_fb.TensorMetadataT()]
|
476 |
+
subgraph.outputTensorMetadata = [_metadata_fb.TensorMetadataT()] * num_outputs
|
477 |
+
model_meta.subgraphMetadata = [subgraph]
|
478 |
+
|
479 |
+
b = flatbuffers.Builder(0)
|
480 |
+
b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)
|
481 |
+
metadata_buf = b.Output()
|
482 |
+
|
483 |
+
populator = _metadata.MetadataPopulator.with_model_file(file)
|
484 |
+
populator.load_metadata_buffer(metadata_buf)
|
485 |
+
populator.load_associated_files([str(tmp_file)])
|
486 |
+
populator.populate()
|
487 |
+
tmp_file.unlink()
|
488 |
+
|
489 |
+
|
490 |
+
@smart_inference_mode()
|
491 |
+
def run(
|
492 |
+
data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
|
493 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
494 |
+
imgsz=(640, 640), # image (height, width)
|
495 |
+
batch_size=1, # batch size
|
496 |
+
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
497 |
+
include=('torchscript', 'onnx'), # include formats
|
498 |
+
half=False, # FP16 half-precision export
|
499 |
+
inplace=False, # set YOLOv5 Detect() inplace=True
|
500 |
+
keras=False, # use Keras
|
501 |
+
optimize=False, # TorchScript: optimize for mobile
|
502 |
+
int8=False, # CoreML/TF INT8 quantization
|
503 |
+
dynamic=False, # ONNX/TF/TensorRT: dynamic axes
|
504 |
+
simplify=False, # ONNX: simplify model
|
505 |
+
opset=12, # ONNX: opset version
|
506 |
+
verbose=False, # TensorRT: verbose log
|
507 |
+
workspace=4, # TensorRT: workspace size (GB)
|
508 |
+
nms=False, # TF: add NMS to model
|
509 |
+
agnostic_nms=False, # TF: add agnostic NMS to model
|
510 |
+
topk_per_class=100, # TF.js NMS: topk per class to keep
|
511 |
+
topk_all=100, # TF.js NMS: topk for all classes to keep
|
512 |
+
iou_thres=0.45, # TF.js NMS: IoU threshold
|
513 |
+
conf_thres=0.25, # TF.js NMS: confidence threshold
|
514 |
+
):
|
515 |
+
t = time.time()
|
516 |
+
include = [x.lower() for x in include] # to lowercase
|
517 |
+
fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
|
518 |
+
flags = [x in include for x in fmts]
|
519 |
+
assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
|
520 |
+
jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle = flags # export booleans
|
521 |
+
file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
|
522 |
+
|
523 |
+
# Load PyTorch model
|
524 |
+
device = select_device(device)
|
525 |
+
if half:
|
526 |
+
assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
|
527 |
+
assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
|
528 |
+
model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
|
529 |
+
|
530 |
+
# Checks
|
531 |
+
imgsz *= 2 if len(imgsz) == 1 else 1 # expand
|
532 |
+
if optimize:
|
533 |
+
assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'
|
534 |
+
|
535 |
+
# Input
|
536 |
+
gs = int(max(model.stride)) # grid size (max stride)
|
537 |
+
imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
|
538 |
+
im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
|
539 |
+
|
540 |
+
# Update model
|
541 |
+
model.eval()
|
542 |
+
for k, m in model.named_modules():
|
543 |
+
if isinstance(m, Detect):
|
544 |
+
m.inplace = inplace
|
545 |
+
m.dynamic = dynamic
|
546 |
+
m.export = True
|
547 |
+
|
548 |
+
for _ in range(2):
|
549 |
+
y = model(im) # dry runs
|
550 |
+
if half and not coreml:
|
551 |
+
im, model = im.half(), model.half() # to FP16
|
552 |
+
shape = tuple((y[0] if isinstance(y, tuple) else y).shape) # model output shape
|
553 |
+
metadata = {'stride': int(max(model.stride)), 'names': model.names} # model metadata
|
554 |
+
LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
|
555 |
+
|
556 |
+
# Exports
|
557 |
+
f = [''] * len(fmts) # exported filenames
|
558 |
+
warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
|
559 |
+
if jit: # TorchScript
|
560 |
+
f[0], _ = export_torchscript(model, im, file, optimize)
|
561 |
+
if engine: # TensorRT required before ONNX
|
562 |
+
f[1], _ = export_engine(model, im, file, half, dynamic, simplify, workspace, verbose)
|
563 |
+
if onnx or xml: # OpenVINO requires ONNX
|
564 |
+
f[2], _ = export_onnx(model, im, file, opset, dynamic, simplify)
|
565 |
+
if xml: # OpenVINO
|
566 |
+
f[3], _ = export_openvino(file, metadata, half)
|
567 |
+
if coreml: # CoreML
|
568 |
+
f[4], _ = export_coreml(model, im, file, int8, half)
|
569 |
+
if any((saved_model, pb, tflite, edgetpu, tfjs)): # TensorFlow formats
|
570 |
+
assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
|
571 |
+
assert not isinstance(model, ClassificationModel), 'ClassificationModel export to TF formats not yet supported.'
|
572 |
+
f[5], s_model = export_saved_model(model.cpu(),
|
573 |
+
im,
|
574 |
+
file,
|
575 |
+
dynamic,
|
576 |
+
tf_nms=nms or agnostic_nms or tfjs,
|
577 |
+
agnostic_nms=agnostic_nms or tfjs,
|
578 |
+
topk_per_class=topk_per_class,
|
579 |
+
topk_all=topk_all,
|
580 |
+
iou_thres=iou_thres,
|
581 |
+
conf_thres=conf_thres,
|
582 |
+
keras=keras)
|
583 |
+
if pb or tfjs: # pb prerequisite to tfjs
|
584 |
+
f[6], _ = export_pb(s_model, file)
|
585 |
+
if tflite or edgetpu:
|
586 |
+
f[7], _ = export_tflite(s_model, im, file, int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
|
587 |
+
if edgetpu:
|
588 |
+
f[8], _ = export_edgetpu(file)
|
589 |
+
add_tflite_metadata(f[8] or f[7], metadata, num_outputs=len(s_model.outputs))
|
590 |
+
if tfjs:
|
591 |
+
f[9], _ = export_tfjs(file)
|
592 |
+
if paddle: # PaddlePaddle
|
593 |
+
f[10], _ = export_paddle(model, im, file, metadata)
|
594 |
+
|
595 |
+
# Finish
|
596 |
+
f = [str(x) for x in f if x] # filter out '' and None
|
597 |
+
if any(f):
|
598 |
+
cls, det, seg = (isinstance(model, x) for x in (ClassificationModel, DetectionModel, SegmentationModel)) # type
|
599 |
+
dir = Path('segment' if seg else 'classify' if cls else '')
|
600 |
+
h = '--half' if half else '' # --half FP16 inference arg
|
601 |
+
s = "# WARNING ⚠️ ClassificationModel not yet supported for PyTorch Hub AutoShape inference" if cls else \
|
602 |
+
"# WARNING ⚠️ SegmentationModel not yet supported for PyTorch Hub AutoShape inference" if seg else ''
|
603 |
+
LOGGER.info(f'\nExport complete ({time.time() - t:.1f}s)'
|
604 |
+
f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
|
605 |
+
f"\nDetect: python {dir / ('detect.py' if det else 'predict.py')} --weights {f[-1]} {h}"
|
606 |
+
f"\nValidate: python {dir / 'val.py'} --weights {f[-1]} {h}"
|
607 |
+
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}') {s}"
|
608 |
+
f"\nVisualize: https://netron.app")
|
609 |
+
return f # return list of exported files/dirs
|
610 |
+
|
611 |
+
|
612 |
+
def parse_opt():
|
613 |
+
parser = argparse.ArgumentParser()
|
614 |
+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
|
615 |
+
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
|
616 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
|
617 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
618 |
+
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
619 |
+
parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
|
620 |
+
parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
|
621 |
+
parser.add_argument('--keras', action='store_true', help='TF: use Keras')
|
622 |
+
parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
|
623 |
+
parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
|
624 |
+
parser.add_argument('--dynamic', action='store_true', help='ONNX/TF/TensorRT: dynamic axes')
|
625 |
+
parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
|
626 |
+
parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
|
627 |
+
parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
|
628 |
+
parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
|
629 |
+
parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
|
630 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
|
631 |
+
parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
|
632 |
+
parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
|
633 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
|
634 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
|
635 |
+
parser.add_argument(
|
636 |
+
'--include',
|
637 |
+
nargs='+',
|
638 |
+
default=['torchscript'],
|
639 |
+
help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle')
|
640 |
+
opt = parser.parse_args()
|
641 |
+
print_args(vars(opt))
|
642 |
+
return opt
|
643 |
+
|
644 |
+
|
645 |
+
def main(opt):
|
646 |
+
for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
|
647 |
+
run(**vars(opt))
|
648 |
+
|
649 |
+
|
650 |
+
if __name__ == "__main__":
|
651 |
+
opt = parse_opt()
|
652 |
+
main(opt)
|
models/__init__.py
ADDED
File without changes
|
models/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (150 Bytes). View file
|
|
models/__pycache__/__init__.cpython-38.pyc
ADDED
Binary file (155 Bytes). View file
|
|
models/__pycache__/common.cpython-310.pyc
ADDED
Binary file (36.9 kB). View file
|
|
models/__pycache__/common.cpython-38.pyc
ADDED
Binary file (37.5 kB). View file
|
|
models/__pycache__/experimental.cpython-38.pyc
ADDED
Binary file (4.87 kB). View file
|
|
models/__pycache__/yolo.cpython-38.pyc
ADDED
Binary file (16.1 kB). View file
|
|
models/common.py
ADDED
@@ -0,0 +1,860 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
Common modules
|
4 |
+
"""
|
5 |
+
|
6 |
+
import ast
|
7 |
+
import contextlib
|
8 |
+
import json
|
9 |
+
import math
|
10 |
+
import platform
|
11 |
+
import warnings
|
12 |
+
import zipfile
|
13 |
+
from collections import OrderedDict, namedtuple
|
14 |
+
from copy import copy
|
15 |
+
from pathlib import Path
|
16 |
+
from urllib.parse import urlparse
|
17 |
+
|
18 |
+
import cv2
|
19 |
+
import numpy as np
|
20 |
+
import pandas as pd
|
21 |
+
import requests
|
22 |
+
import torch
|
23 |
+
import torch.nn as nn
|
24 |
+
from IPython.display import display
|
25 |
+
from PIL import Image
|
26 |
+
from torch.cuda import amp
|
27 |
+
|
28 |
+
from utils import TryExcept
|
29 |
+
from utils.dataloaders import exif_transpose, letterbox
|
30 |
+
from utils.general import (LOGGER, ROOT, Profile, check_requirements, check_suffix, check_version, colorstr,
|
31 |
+
increment_path, is_notebook, make_divisible, non_max_suppression, scale_boxes, xywh2xyxy,
|
32 |
+
xyxy2xywh, yaml_load)
|
33 |
+
from utils.plots import Annotator, colors, save_one_box
|
34 |
+
from utils.torch_utils import copy_attr, smart_inference_mode
|
35 |
+
|
36 |
+
|
37 |
+
def autopad(k, p=None, d=1): # kernel, padding, dilation
|
38 |
+
# Pad to 'same' shape outputs
|
39 |
+
if d > 1:
|
40 |
+
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
|
41 |
+
if p is None:
|
42 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
43 |
+
return p
|
44 |
+
|
45 |
+
|
46 |
+
class Conv(nn.Module):
|
47 |
+
# Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
|
48 |
+
default_act = nn.SiLU() # default activation
|
49 |
+
|
50 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
|
51 |
+
super().__init__()
|
52 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
|
53 |
+
self.bn = nn.BatchNorm2d(c2)
|
54 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
55 |
+
|
56 |
+
def forward(self, x):
|
57 |
+
return self.act(self.bn(self.conv(x)))
|
58 |
+
|
59 |
+
def forward_fuse(self, x):
|
60 |
+
return self.act(self.conv(x))
|
61 |
+
|
62 |
+
|
63 |
+
class DWConv(Conv):
|
64 |
+
# Depth-wise convolution
|
65 |
+
def __init__(self, c1, c2, k=1, s=1, d=1, act=True): # ch_in, ch_out, kernel, stride, dilation, activation
|
66 |
+
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
|
67 |
+
|
68 |
+
|
69 |
+
class DWConvTranspose2d(nn.ConvTranspose2d):
|
70 |
+
# Depth-wise transpose convolution
|
71 |
+
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
|
72 |
+
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
|
73 |
+
|
74 |
+
|
75 |
+
class TransformerLayer(nn.Module):
|
76 |
+
# Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
|
77 |
+
def __init__(self, c, num_heads):
|
78 |
+
super().__init__()
|
79 |
+
self.q = nn.Linear(c, c, bias=False)
|
80 |
+
self.k = nn.Linear(c, c, bias=False)
|
81 |
+
self.v = nn.Linear(c, c, bias=False)
|
82 |
+
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
|
83 |
+
self.fc1 = nn.Linear(c, c, bias=False)
|
84 |
+
self.fc2 = nn.Linear(c, c, bias=False)
|
85 |
+
|
86 |
+
def forward(self, x):
|
87 |
+
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
|
88 |
+
x = self.fc2(self.fc1(x)) + x
|
89 |
+
return x
|
90 |
+
|
91 |
+
|
92 |
+
class TransformerBlock(nn.Module):
|
93 |
+
# Vision Transformer https://arxiv.org/abs/2010.11929
|
94 |
+
def __init__(self, c1, c2, num_heads, num_layers):
|
95 |
+
super().__init__()
|
96 |
+
self.conv = None
|
97 |
+
if c1 != c2:
|
98 |
+
self.conv = Conv(c1, c2)
|
99 |
+
self.linear = nn.Linear(c2, c2) # learnable position embedding
|
100 |
+
self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
|
101 |
+
self.c2 = c2
|
102 |
+
|
103 |
+
def forward(self, x):
|
104 |
+
if self.conv is not None:
|
105 |
+
x = self.conv(x)
|
106 |
+
b, _, w, h = x.shape
|
107 |
+
p = x.flatten(2).permute(2, 0, 1)
|
108 |
+
return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
|
109 |
+
|
110 |
+
|
111 |
+
class Bottleneck(nn.Module):
|
112 |
+
# Standard bottleneck
|
113 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
114 |
+
super().__init__()
|
115 |
+
c_ = int(c2 * e) # hidden channels
|
116 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
117 |
+
self.cv2 = Conv(c_, c2, 3, 1, g=g)
|
118 |
+
self.add = shortcut and c1 == c2
|
119 |
+
|
120 |
+
def forward(self, x):
|
121 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
122 |
+
|
123 |
+
|
124 |
+
class BottleneckCSP(nn.Module):
|
125 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
126 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
127 |
+
super().__init__()
|
128 |
+
c_ = int(c2 * e) # hidden channels
|
129 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
130 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
131 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
132 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
133 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
134 |
+
self.act = nn.SiLU()
|
135 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
136 |
+
|
137 |
+
def forward(self, x):
|
138 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
139 |
+
y2 = self.cv2(x)
|
140 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
|
141 |
+
|
142 |
+
|
143 |
+
class CrossConv(nn.Module):
|
144 |
+
# Cross Convolution Downsample
|
145 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
|
146 |
+
# ch_in, ch_out, kernel, stride, groups, expansion, shortcut
|
147 |
+
super().__init__()
|
148 |
+
c_ = int(c2 * e) # hidden channels
|
149 |
+
self.cv1 = Conv(c1, c_, (1, k), (1, s))
|
150 |
+
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
|
151 |
+
self.add = shortcut and c1 == c2
|
152 |
+
|
153 |
+
def forward(self, x):
|
154 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
155 |
+
|
156 |
+
|
157 |
+
class C3(nn.Module):
|
158 |
+
# CSP Bottleneck with 3 convolutions
|
159 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
160 |
+
super().__init__()
|
161 |
+
c_ = int(c2 * e) # hidden channels
|
162 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
163 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
164 |
+
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
|
165 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
166 |
+
|
167 |
+
def forward(self, x):
|
168 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
169 |
+
|
170 |
+
|
171 |
+
class C3x(C3):
|
172 |
+
# C3 module with cross-convolutions
|
173 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
174 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
175 |
+
c_ = int(c2 * e)
|
176 |
+
self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
|
177 |
+
|
178 |
+
|
179 |
+
class C3TR(C3):
|
180 |
+
# C3 module with TransformerBlock()
|
181 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
182 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
183 |
+
c_ = int(c2 * e)
|
184 |
+
self.m = TransformerBlock(c_, c_, 4, n)
|
185 |
+
|
186 |
+
|
187 |
+
class C3SPP(C3):
|
188 |
+
# C3 module with SPP()
|
189 |
+
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
|
190 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
191 |
+
c_ = int(c2 * e)
|
192 |
+
self.m = SPP(c_, c_, k)
|
193 |
+
|
194 |
+
|
195 |
+
class C3Ghost(C3):
|
196 |
+
# C3 module with GhostBottleneck()
|
197 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
198 |
+
super().__init__(c1, c2, n, shortcut, g, e)
|
199 |
+
c_ = int(c2 * e) # hidden channels
|
200 |
+
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
|
201 |
+
|
202 |
+
|
203 |
+
class SPP(nn.Module):
|
204 |
+
# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
|
205 |
+
def __init__(self, c1, c2, k=(5, 9, 13)):
|
206 |
+
super().__init__()
|
207 |
+
c_ = c1 // 2 # hidden channels
|
208 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
209 |
+
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
210 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
211 |
+
|
212 |
+
def forward(self, x):
|
213 |
+
x = self.cv1(x)
|
214 |
+
with warnings.catch_warnings():
|
215 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
216 |
+
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
217 |
+
|
218 |
+
|
219 |
+
class SPPF(nn.Module):
|
220 |
+
# Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
|
221 |
+
def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
|
222 |
+
super().__init__()
|
223 |
+
c_ = c1 // 2 # hidden channels
|
224 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
225 |
+
self.cv2 = Conv(c_ * 4, c2, 1, 1)
|
226 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
|
227 |
+
|
228 |
+
def forward(self, x):
|
229 |
+
x = self.cv1(x)
|
230 |
+
with warnings.catch_warnings():
|
231 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
232 |
+
y1 = self.m(x)
|
233 |
+
y2 = self.m(y1)
|
234 |
+
return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
|
235 |
+
|
236 |
+
|
237 |
+
class Focus(nn.Module):
|
238 |
+
# Focus wh information into c-space
|
239 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
240 |
+
super().__init__()
|
241 |
+
self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
|
242 |
+
# self.contract = Contract(gain=2)
|
243 |
+
|
244 |
+
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
|
245 |
+
return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
|
246 |
+
# return self.conv(self.contract(x))
|
247 |
+
|
248 |
+
|
249 |
+
class GhostConv(nn.Module):
|
250 |
+
# Ghost Convolution https://github.com/huawei-noah/ghostnet
|
251 |
+
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
|
252 |
+
super().__init__()
|
253 |
+
c_ = c2 // 2 # hidden channels
|
254 |
+
self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
|
255 |
+
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
|
256 |
+
|
257 |
+
def forward(self, x):
|
258 |
+
y = self.cv1(x)
|
259 |
+
return torch.cat((y, self.cv2(y)), 1)
|
260 |
+
|
261 |
+
|
262 |
+
class GhostBottleneck(nn.Module):
|
263 |
+
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
|
264 |
+
def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
|
265 |
+
super().__init__()
|
266 |
+
c_ = c2 // 2
|
267 |
+
self.conv = nn.Sequential(
|
268 |
+
GhostConv(c1, c_, 1, 1), # pw
|
269 |
+
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
|
270 |
+
GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
|
271 |
+
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,
|
272 |
+
act=False)) if s == 2 else nn.Identity()
|
273 |
+
|
274 |
+
def forward(self, x):
|
275 |
+
return self.conv(x) + self.shortcut(x)
|
276 |
+
|
277 |
+
|
278 |
+
class Contract(nn.Module):
|
279 |
+
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
|
280 |
+
def __init__(self, gain=2):
|
281 |
+
super().__init__()
|
282 |
+
self.gain = gain
|
283 |
+
|
284 |
+
def forward(self, x):
|
285 |
+
b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
|
286 |
+
s = self.gain
|
287 |
+
x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
|
288 |
+
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
|
289 |
+
return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
|
290 |
+
|
291 |
+
|
292 |
+
class Expand(nn.Module):
|
293 |
+
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
|
294 |
+
def __init__(self, gain=2):
|
295 |
+
super().__init__()
|
296 |
+
self.gain = gain
|
297 |
+
|
298 |
+
def forward(self, x):
|
299 |
+
b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
|
300 |
+
s = self.gain
|
301 |
+
x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
|
302 |
+
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
|
303 |
+
return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
|
304 |
+
|
305 |
+
|
306 |
+
class Concat(nn.Module):
|
307 |
+
# Concatenate a list of tensors along dimension
|
308 |
+
def __init__(self, dimension=1):
|
309 |
+
super().__init__()
|
310 |
+
self.d = dimension
|
311 |
+
|
312 |
+
def forward(self, x):
|
313 |
+
return torch.cat(x, self.d)
|
314 |
+
|
315 |
+
|
316 |
+
class DetectMultiBackend(nn.Module):
|
317 |
+
# YOLOv5 MultiBackend class for python inference on various backends
|
318 |
+
def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):
|
319 |
+
# Usage:
|
320 |
+
# PyTorch: weights = *.pt
|
321 |
+
# TorchScript: *.torchscript
|
322 |
+
# ONNX Runtime: *.onnx
|
323 |
+
# ONNX OpenCV DNN: *.onnx --dnn
|
324 |
+
# OpenVINO: *_openvino_model
|
325 |
+
# CoreML: *.mlmodel
|
326 |
+
# TensorRT: *.engine
|
327 |
+
# TensorFlow SavedModel: *_saved_model
|
328 |
+
# TensorFlow GraphDef: *.pb
|
329 |
+
# TensorFlow Lite: *.tflite
|
330 |
+
# TensorFlow Edge TPU: *_edgetpu.tflite
|
331 |
+
# PaddlePaddle: *_paddle_model
|
332 |
+
from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
|
333 |
+
|
334 |
+
super().__init__()
|
335 |
+
w = str(weights[0] if isinstance(weights, list) else weights)
|
336 |
+
pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)
|
337 |
+
fp16 &= pt or jit or onnx or engine # FP16
|
338 |
+
nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)
|
339 |
+
stride = 32 # default stride
|
340 |
+
cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA
|
341 |
+
if not (pt or triton):
|
342 |
+
w = attempt_download(w) # download if not local
|
343 |
+
|
344 |
+
if pt: # PyTorch
|
345 |
+
model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
|
346 |
+
stride = max(int(model.stride.max()), 32) # model stride
|
347 |
+
names = model.module.names if hasattr(model, 'module') else model.names # get class names
|
348 |
+
model.half() if fp16 else model.float()
|
349 |
+
self.model = model # explicitly assign for to(), cpu(), cuda(), half()
|
350 |
+
elif jit: # TorchScript
|
351 |
+
LOGGER.info(f'Loading {w} for TorchScript inference...')
|
352 |
+
extra_files = {'config.txt': ''} # model metadata
|
353 |
+
model = torch.jit.load(w, _extra_files=extra_files, map_location=device)
|
354 |
+
model.half() if fp16 else model.float()
|
355 |
+
if extra_files['config.txt']: # load metadata dict
|
356 |
+
d = json.loads(extra_files['config.txt'],
|
357 |
+
object_hook=lambda d: {int(k) if k.isdigit() else k: v
|
358 |
+
for k, v in d.items()})
|
359 |
+
stride, names = int(d['stride']), d['names']
|
360 |
+
elif dnn: # ONNX OpenCV DNN
|
361 |
+
LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')
|
362 |
+
check_requirements('opencv-python>=4.5.4')
|
363 |
+
net = cv2.dnn.readNetFromONNX(w)
|
364 |
+
elif onnx: # ONNX Runtime
|
365 |
+
LOGGER.info(f'Loading {w} for ONNX Runtime inference...')
|
366 |
+
check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))
|
367 |
+
import onnxruntime
|
368 |
+
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
|
369 |
+
session = onnxruntime.InferenceSession(w, providers=providers)
|
370 |
+
output_names = [x.name for x in session.get_outputs()]
|
371 |
+
meta = session.get_modelmeta().custom_metadata_map # metadata
|
372 |
+
if 'stride' in meta:
|
373 |
+
stride, names = int(meta['stride']), eval(meta['names'])
|
374 |
+
elif xml: # OpenVINO
|
375 |
+
LOGGER.info(f'Loading {w} for OpenVINO inference...')
|
376 |
+
check_requirements('openvino') # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
377 |
+
from openvino.runtime import Core, Layout, get_batch
|
378 |
+
ie = Core()
|
379 |
+
if not Path(w).is_file(): # if not *.xml
|
380 |
+
w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir
|
381 |
+
network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin'))
|
382 |
+
if network.get_parameters()[0].get_layout().empty:
|
383 |
+
network.get_parameters()[0].set_layout(Layout("NCHW"))
|
384 |
+
batch_dim = get_batch(network)
|
385 |
+
if batch_dim.is_static:
|
386 |
+
batch_size = batch_dim.get_length()
|
387 |
+
executable_network = ie.compile_model(network, device_name="CPU") # device_name="MYRIAD" for Intel NCS2
|
388 |
+
stride, names = self._load_metadata(Path(w).with_suffix('.yaml')) # load metadata
|
389 |
+
elif engine: # TensorRT
|
390 |
+
LOGGER.info(f'Loading {w} for TensorRT inference...')
|
391 |
+
import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
|
392 |
+
check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
|
393 |
+
if device.type == 'cpu':
|
394 |
+
device = torch.device('cuda:0')
|
395 |
+
Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))
|
396 |
+
logger = trt.Logger(trt.Logger.INFO)
|
397 |
+
with open(w, 'rb') as f, trt.Runtime(logger) as runtime:
|
398 |
+
model = runtime.deserialize_cuda_engine(f.read())
|
399 |
+
context = model.create_execution_context()
|
400 |
+
bindings = OrderedDict()
|
401 |
+
output_names = []
|
402 |
+
fp16 = False # default updated below
|
403 |
+
dynamic = False
|
404 |
+
for i in range(model.num_bindings):
|
405 |
+
name = model.get_binding_name(i)
|
406 |
+
dtype = trt.nptype(model.get_binding_dtype(i))
|
407 |
+
if model.binding_is_input(i):
|
408 |
+
if -1 in tuple(model.get_binding_shape(i)): # dynamic
|
409 |
+
dynamic = True
|
410 |
+
context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))
|
411 |
+
if dtype == np.float16:
|
412 |
+
fp16 = True
|
413 |
+
else: # output
|
414 |
+
output_names.append(name)
|
415 |
+
shape = tuple(context.get_binding_shape(i))
|
416 |
+
im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)
|
417 |
+
bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))
|
418 |
+
binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
|
419 |
+
batch_size = bindings['images'].shape[0] # if dynamic, this is instead max batch size
|
420 |
+
elif coreml: # CoreML
|
421 |
+
LOGGER.info(f'Loading {w} for CoreML inference...')
|
422 |
+
import coremltools as ct
|
423 |
+
model = ct.models.MLModel(w)
|
424 |
+
elif saved_model: # TF SavedModel
|
425 |
+
LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')
|
426 |
+
import tensorflow as tf
|
427 |
+
keras = False # assume TF1 saved_model
|
428 |
+
model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
|
429 |
+
elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
|
430 |
+
LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')
|
431 |
+
import tensorflow as tf
|
432 |
+
|
433 |
+
def wrap_frozen_graph(gd, inputs, outputs):
|
434 |
+
x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
|
435 |
+
ge = x.graph.as_graph_element
|
436 |
+
return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
|
437 |
+
|
438 |
+
def gd_outputs(gd):
|
439 |
+
name_list, input_list = [], []
|
440 |
+
for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef
|
441 |
+
name_list.append(node.name)
|
442 |
+
input_list.extend(node.input)
|
443 |
+
return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))
|
444 |
+
|
445 |
+
gd = tf.Graph().as_graph_def() # TF GraphDef
|
446 |
+
with open(w, 'rb') as f:
|
447 |
+
gd.ParseFromString(f.read())
|
448 |
+
frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs=gd_outputs(gd))
|
449 |
+
elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
|
450 |
+
try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
|
451 |
+
from tflite_runtime.interpreter import Interpreter, load_delegate
|
452 |
+
except ImportError:
|
453 |
+
import tensorflow as tf
|
454 |
+
Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,
|
455 |
+
if edgetpu: # TF Edge TPU https://coral.ai/software/#edgetpu-runtime
|
456 |
+
LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')
|
457 |
+
delegate = {
|
458 |
+
'Linux': 'libedgetpu.so.1',
|
459 |
+
'Darwin': 'libedgetpu.1.dylib',
|
460 |
+
'Windows': 'edgetpu.dll'}[platform.system()]
|
461 |
+
interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
|
462 |
+
else: # TFLite
|
463 |
+
LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')
|
464 |
+
interpreter = Interpreter(model_path=w) # load TFLite model
|
465 |
+
interpreter.allocate_tensors() # allocate
|
466 |
+
input_details = interpreter.get_input_details() # inputs
|
467 |
+
output_details = interpreter.get_output_details() # outputs
|
468 |
+
# load metadata
|
469 |
+
with contextlib.suppress(zipfile.BadZipFile):
|
470 |
+
with zipfile.ZipFile(w, "r") as model:
|
471 |
+
meta_file = model.namelist()[0]
|
472 |
+
meta = ast.literal_eval(model.read(meta_file).decode("utf-8"))
|
473 |
+
stride, names = int(meta['stride']), meta['names']
|
474 |
+
elif tfjs: # TF.js
|
475 |
+
raise NotImplementedError('ERROR: YOLOv5 TF.js inference is not supported')
|
476 |
+
elif paddle: # PaddlePaddle
|
477 |
+
LOGGER.info(f'Loading {w} for PaddlePaddle inference...')
|
478 |
+
check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')
|
479 |
+
import paddle.inference as pdi
|
480 |
+
if not Path(w).is_file(): # if not *.pdmodel
|
481 |
+
w = next(Path(w).rglob('*.pdmodel')) # get *.pdmodel file from *_paddle_model dir
|
482 |
+
weights = Path(w).with_suffix('.pdiparams')
|
483 |
+
config = pdi.Config(str(w), str(weights))
|
484 |
+
if cuda:
|
485 |
+
config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)
|
486 |
+
predictor = pdi.create_predictor(config)
|
487 |
+
input_handle = predictor.get_input_handle(predictor.get_input_names()[0])
|
488 |
+
output_names = predictor.get_output_names()
|
489 |
+
elif triton: # NVIDIA Triton Inference Server
|
490 |
+
LOGGER.info(f'Using {w} as Triton Inference Server...')
|
491 |
+
check_requirements('tritonclient[all]')
|
492 |
+
from utils.triton import TritonRemoteModel
|
493 |
+
model = TritonRemoteModel(url=w)
|
494 |
+
nhwc = model.runtime.startswith("tensorflow")
|
495 |
+
else:
|
496 |
+
raise NotImplementedError(f'ERROR: {w} is not a supported format')
|
497 |
+
|
498 |
+
# class names
|
499 |
+
if 'names' not in locals():
|
500 |
+
names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}
|
501 |
+
if names[0] == 'n01440764' and len(names) == 1000: # ImageNet
|
502 |
+
names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names
|
503 |
+
|
504 |
+
self.__dict__.update(locals()) # assign all variables to self
|
505 |
+
|
506 |
+
def forward(self, im, augment=False, visualize=False):
|
507 |
+
# YOLOv5 MultiBackend inference
|
508 |
+
b, ch, h, w = im.shape # batch, channel, height, width
|
509 |
+
if self.fp16 and im.dtype != torch.float16:
|
510 |
+
im = im.half() # to FP16
|
511 |
+
if self.nhwc:
|
512 |
+
im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)
|
513 |
+
|
514 |
+
if self.pt: # PyTorch
|
515 |
+
y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
|
516 |
+
elif self.jit: # TorchScript
|
517 |
+
y = self.model(im)
|
518 |
+
elif self.dnn: # ONNX OpenCV DNN
|
519 |
+
im = im.cpu().numpy() # torch to numpy
|
520 |
+
self.net.setInput(im)
|
521 |
+
y = self.net.forward()
|
522 |
+
elif self.onnx: # ONNX Runtime
|
523 |
+
im = im.cpu().numpy() # torch to numpy
|
524 |
+
y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})
|
525 |
+
elif self.xml: # OpenVINO
|
526 |
+
im = im.cpu().numpy() # FP32
|
527 |
+
y = list(self.executable_network([im]).values())
|
528 |
+
elif self.engine: # TensorRT
|
529 |
+
if self.dynamic and im.shape != self.bindings['images'].shape:
|
530 |
+
i = self.model.get_binding_index('images')
|
531 |
+
self.context.set_binding_shape(i, im.shape) # reshape if dynamic
|
532 |
+
self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)
|
533 |
+
for name in self.output_names:
|
534 |
+
i = self.model.get_binding_index(name)
|
535 |
+
self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))
|
536 |
+
s = self.bindings['images'].shape
|
537 |
+
assert im.shape == s, f"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}"
|
538 |
+
self.binding_addrs['images'] = int(im.data_ptr())
|
539 |
+
self.context.execute_v2(list(self.binding_addrs.values()))
|
540 |
+
y = [self.bindings[x].data for x in sorted(self.output_names)]
|
541 |
+
elif self.coreml: # CoreML
|
542 |
+
im = im.cpu().numpy()
|
543 |
+
im = Image.fromarray((im[0] * 255).astype('uint8'))
|
544 |
+
# im = im.resize((192, 320), Image.ANTIALIAS)
|
545 |
+
y = self.model.predict({'image': im}) # coordinates are xywh normalized
|
546 |
+
if 'confidence' in y:
|
547 |
+
box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
|
548 |
+
conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
|
549 |
+
y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
|
550 |
+
else:
|
551 |
+
y = list(reversed(y.values())) # reversed for segmentation models (pred, proto)
|
552 |
+
elif self.paddle: # PaddlePaddle
|
553 |
+
im = im.cpu().numpy().astype(np.float32)
|
554 |
+
self.input_handle.copy_from_cpu(im)
|
555 |
+
self.predictor.run()
|
556 |
+
y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]
|
557 |
+
elif self.triton: # NVIDIA Triton Inference Server
|
558 |
+
y = self.model(im)
|
559 |
+
else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
|
560 |
+
im = im.cpu().numpy()
|
561 |
+
if self.saved_model: # SavedModel
|
562 |
+
y = self.model(im, training=False) if self.keras else self.model(im)
|
563 |
+
elif self.pb: # GraphDef
|
564 |
+
y = self.frozen_func(x=self.tf.constant(im))
|
565 |
+
else: # Lite or Edge TPU
|
566 |
+
input = self.input_details[0]
|
567 |
+
int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
|
568 |
+
if int8:
|
569 |
+
scale, zero_point = input['quantization']
|
570 |
+
im = (im / scale + zero_point).astype(np.uint8) # de-scale
|
571 |
+
self.interpreter.set_tensor(input['index'], im)
|
572 |
+
self.interpreter.invoke()
|
573 |
+
y = []
|
574 |
+
for output in self.output_details:
|
575 |
+
x = self.interpreter.get_tensor(output['index'])
|
576 |
+
if int8:
|
577 |
+
scale, zero_point = output['quantization']
|
578 |
+
x = (x.astype(np.float32) - zero_point) * scale # re-scale
|
579 |
+
y.append(x)
|
580 |
+
y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]
|
581 |
+
y[0][..., :4] *= [w, h, w, h] # xywh normalized to pixels
|
582 |
+
|
583 |
+
if isinstance(y, (list, tuple)):
|
584 |
+
return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]
|
585 |
+
else:
|
586 |
+
return self.from_numpy(y)
|
587 |
+
|
588 |
+
def from_numpy(self, x):
|
589 |
+
return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x
|
590 |
+
|
591 |
+
def warmup(self, imgsz=(1, 3, 640, 640)):
|
592 |
+
# Warmup model by running inference once
|
593 |
+
warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton
|
594 |
+
if any(warmup_types) and (self.device.type != 'cpu' or self.triton):
|
595 |
+
im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
|
596 |
+
for _ in range(2 if self.jit else 1): #
|
597 |
+
self.forward(im) # warmup
|
598 |
+
|
599 |
+
@staticmethod
|
600 |
+
def _model_type(p='path/to/model.pt'):
|
601 |
+
# Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx
|
602 |
+
# types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]
|
603 |
+
from export import export_formats
|
604 |
+
from utils.downloads import is_url
|
605 |
+
sf = list(export_formats().Suffix) # export suffixes
|
606 |
+
if not is_url(p, check=False):
|
607 |
+
check_suffix(p, sf) # checks
|
608 |
+
url = urlparse(p) # if url may be Triton inference server
|
609 |
+
types = [s in Path(p).name for s in sf]
|
610 |
+
types[8] &= not types[9] # tflite &= not edgetpu
|
611 |
+
triton = not any(types) and all([any(s in url.scheme for s in ["http", "grpc"]), url.netloc])
|
612 |
+
return types + [triton]
|
613 |
+
|
614 |
+
@staticmethod
|
615 |
+
def _load_metadata(f=Path('path/to/meta.yaml')):
|
616 |
+
# Load metadata from meta.yaml if it exists
|
617 |
+
if f.exists():
|
618 |
+
d = yaml_load(f)
|
619 |
+
return d['stride'], d['names'] # assign stride, names
|
620 |
+
return None, None
|
621 |
+
|
622 |
+
|
623 |
+
class AutoShape(nn.Module):
|
624 |
+
# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
|
625 |
+
conf = 0.25 # NMS confidence threshold
|
626 |
+
iou = 0.45 # NMS IoU threshold
|
627 |
+
agnostic = False # NMS class-agnostic
|
628 |
+
multi_label = False # NMS multiple labels per box
|
629 |
+
classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
|
630 |
+
max_det = 1000 # maximum number of detections per image
|
631 |
+
amp = False # Automatic Mixed Precision (AMP) inference
|
632 |
+
|
633 |
+
def __init__(self, model, verbose=True):
|
634 |
+
super().__init__()
|
635 |
+
if verbose:
|
636 |
+
LOGGER.info('Adding AutoShape... ')
|
637 |
+
copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
|
638 |
+
self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
|
639 |
+
self.pt = not self.dmb or model.pt # PyTorch model
|
640 |
+
self.model = model.eval()
|
641 |
+
if self.pt:
|
642 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
643 |
+
m.inplace = False # Detect.inplace=False for safe multithread inference
|
644 |
+
m.export = True # do not output loss values
|
645 |
+
|
646 |
+
def _apply(self, fn):
|
647 |
+
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
|
648 |
+
self = super()._apply(fn)
|
649 |
+
if self.pt:
|
650 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
651 |
+
m.stride = fn(m.stride)
|
652 |
+
m.grid = list(map(fn, m.grid))
|
653 |
+
if isinstance(m.anchor_grid, list):
|
654 |
+
m.anchor_grid = list(map(fn, m.anchor_grid))
|
655 |
+
return self
|
656 |
+
|
657 |
+
@smart_inference_mode()
|
658 |
+
def forward(self, ims, size=640, augment=False, profile=False):
|
659 |
+
# Inference from various sources. For size(height=640, width=1280), RGB images example inputs are:
|
660 |
+
# file: ims = 'data/images/zidane.jpg' # str or PosixPath
|
661 |
+
# URI: = 'https://ultralytics.com/images/zidane.jpg'
|
662 |
+
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
|
663 |
+
# PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
|
664 |
+
# numpy: = np.zeros((640,1280,3)) # HWC
|
665 |
+
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
|
666 |
+
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
|
667 |
+
|
668 |
+
dt = (Profile(), Profile(), Profile())
|
669 |
+
with dt[0]:
|
670 |
+
if isinstance(size, int): # expand
|
671 |
+
size = (size, size)
|
672 |
+
p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) # param
|
673 |
+
autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
|
674 |
+
if isinstance(ims, torch.Tensor): # torch
|
675 |
+
with amp.autocast(autocast):
|
676 |
+
return self.model(ims.to(p.device).type_as(p), augment=augment) # inference
|
677 |
+
|
678 |
+
# Pre-process
|
679 |
+
n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of images
|
680 |
+
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
|
681 |
+
for i, im in enumerate(ims):
|
682 |
+
f = f'image{i}' # filename
|
683 |
+
if isinstance(im, (str, Path)): # filename or uri
|
684 |
+
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
|
685 |
+
im = np.asarray(exif_transpose(im))
|
686 |
+
elif isinstance(im, Image.Image): # PIL Image
|
687 |
+
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
|
688 |
+
files.append(Path(f).with_suffix('.jpg').name)
|
689 |
+
if im.shape[0] < 5: # image in CHW
|
690 |
+
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
|
691 |
+
im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch input
|
692 |
+
s = im.shape[:2] # HWC
|
693 |
+
shape0.append(s) # image shape
|
694 |
+
g = max(size) / max(s) # gain
|
695 |
+
shape1.append([int(y * g) for y in s])
|
696 |
+
ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
|
697 |
+
shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] if self.pt else size # inf shape
|
698 |
+
x = [letterbox(im, shape1, auto=False)[0] for im in ims] # pad
|
699 |
+
x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
|
700 |
+
x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
|
701 |
+
|
702 |
+
with amp.autocast(autocast):
|
703 |
+
# Inference
|
704 |
+
with dt[1]:
|
705 |
+
y = self.model(x, augment=augment) # forward
|
706 |
+
|
707 |
+
# Post-process
|
708 |
+
with dt[2]:
|
709 |
+
y = non_max_suppression(y if self.dmb else y[0],
|
710 |
+
self.conf,
|
711 |
+
self.iou,
|
712 |
+
self.classes,
|
713 |
+
self.agnostic,
|
714 |
+
self.multi_label,
|
715 |
+
max_det=self.max_det) # NMS
|
716 |
+
for i in range(n):
|
717 |
+
scale_boxes(shape1, y[i][:, :4], shape0[i])
|
718 |
+
|
719 |
+
return Detections(ims, y, files, dt, self.names, x.shape)
|
720 |
+
|
721 |
+
|
722 |
+
class Detections:
|
723 |
+
# YOLOv5 detections class for inference results
|
724 |
+
def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
|
725 |
+
super().__init__()
|
726 |
+
d = pred[0].device # device
|
727 |
+
gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] # normalizations
|
728 |
+
self.ims = ims # list of images as numpy arrays
|
729 |
+
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
|
730 |
+
self.names = names # class names
|
731 |
+
self.files = files # image filenames
|
732 |
+
self.times = times # profiling times
|
733 |
+
self.xyxy = pred # xyxy pixels
|
734 |
+
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
|
735 |
+
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
|
736 |
+
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
|
737 |
+
self.n = len(self.pred) # number of images (batch size)
|
738 |
+
self.t = tuple(x.t / self.n * 1E3 for x in times) # timestamps (ms)
|
739 |
+
self.s = tuple(shape) # inference BCHW shape
|
740 |
+
|
741 |
+
def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
|
742 |
+
s, crops = '', []
|
743 |
+
for i, (im, pred) in enumerate(zip(self.ims, self.pred)):
|
744 |
+
s += f'\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
|
745 |
+
if pred.shape[0]:
|
746 |
+
for c in pred[:, -1].unique():
|
747 |
+
n = (pred[:, -1] == c).sum() # detections per class
|
748 |
+
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
|
749 |
+
s = s.rstrip(', ')
|
750 |
+
if show or save or render or crop:
|
751 |
+
annotator = Annotator(im, example=str(self.names))
|
752 |
+
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
|
753 |
+
label = f'{self.names[int(cls)]} {conf:.2f}'
|
754 |
+
if crop:
|
755 |
+
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
|
756 |
+
crops.append({
|
757 |
+
'box': box,
|
758 |
+
'conf': conf,
|
759 |
+
'cls': cls,
|
760 |
+
'label': label,
|
761 |
+
'im': save_one_box(box, im, file=file, save=save)})
|
762 |
+
else: # all others
|
763 |
+
annotator.box_label(box, label if labels else '', color=colors(cls))
|
764 |
+
im = annotator.im
|
765 |
+
else:
|
766 |
+
s += '(no detections)'
|
767 |
+
|
768 |
+
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
|
769 |
+
if show:
|
770 |
+
display(im) if is_notebook() else im.show(self.files[i])
|
771 |
+
if save:
|
772 |
+
f = self.files[i]
|
773 |
+
im.save(save_dir / f) # save
|
774 |
+
if i == self.n - 1:
|
775 |
+
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
|
776 |
+
if render:
|
777 |
+
self.ims[i] = np.asarray(im)
|
778 |
+
if pprint:
|
779 |
+
s = s.lstrip('\n')
|
780 |
+
return f'{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t
|
781 |
+
if crop:
|
782 |
+
if save:
|
783 |
+
LOGGER.info(f'Saved results to {save_dir}\n')
|
784 |
+
return crops
|
785 |
+
|
786 |
+
@TryExcept('Showing images is not supported in this environment')
|
787 |
+
def show(self, labels=True):
|
788 |
+
self._run(show=True, labels=labels) # show results
|
789 |
+
|
790 |
+
def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):
|
791 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) # increment save_dir
|
792 |
+
self._run(save=True, labels=labels, save_dir=save_dir) # save results
|
793 |
+
|
794 |
+
def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):
|
795 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
|
796 |
+
return self._run(crop=True, save=save, save_dir=save_dir) # crop results
|
797 |
+
|
798 |
+
def render(self, labels=True):
|
799 |
+
self._run(render=True, labels=labels) # render results
|
800 |
+
return self.ims
|
801 |
+
|
802 |
+
def pandas(self):
|
803 |
+
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
|
804 |
+
new = copy(self) # return copy
|
805 |
+
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
|
806 |
+
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
|
807 |
+
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
|
808 |
+
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
|
809 |
+
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
|
810 |
+
return new
|
811 |
+
|
812 |
+
def tolist(self):
|
813 |
+
# return a list of Detections objects, i.e. 'for result in results.tolist():'
|
814 |
+
r = range(self.n) # iterable
|
815 |
+
x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
|
816 |
+
# for d in x:
|
817 |
+
# for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
|
818 |
+
# setattr(d, k, getattr(d, k)[0]) # pop out of list
|
819 |
+
return x
|
820 |
+
|
821 |
+
def print(self):
|
822 |
+
LOGGER.info(self.__str__())
|
823 |
+
|
824 |
+
def __len__(self): # override len(results)
|
825 |
+
return self.n
|
826 |
+
|
827 |
+
def __str__(self): # override print(results)
|
828 |
+
return self._run(pprint=True) # print results
|
829 |
+
|
830 |
+
def __repr__(self):
|
831 |
+
return f'YOLOv5 {self.__class__} instance\n' + self.__str__()
|
832 |
+
|
833 |
+
|
834 |
+
class Proto(nn.Module):
|
835 |
+
# YOLOv5 mask Proto module for segmentation models
|
836 |
+
def __init__(self, c1, c_=256, c2=32): # ch_in, number of protos, number of masks
|
837 |
+
super().__init__()
|
838 |
+
self.cv1 = Conv(c1, c_, k=3)
|
839 |
+
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
|
840 |
+
self.cv2 = Conv(c_, c_, k=3)
|
841 |
+
self.cv3 = Conv(c_, c2)
|
842 |
+
|
843 |
+
def forward(self, x):
|
844 |
+
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
|
845 |
+
|
846 |
+
|
847 |
+
class Classify(nn.Module):
|
848 |
+
# YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
849 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
|
850 |
+
super().__init__()
|
851 |
+
c_ = 1280 # efficientnet_b0 size
|
852 |
+
self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
|
853 |
+
self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
|
854 |
+
self.drop = nn.Dropout(p=0.0, inplace=True)
|
855 |
+
self.linear = nn.Linear(c_, c2) # to x(b,c2)
|
856 |
+
|
857 |
+
def forward(self, x):
|
858 |
+
if isinstance(x, list):
|
859 |
+
x = torch.cat(x, 1)
|
860 |
+
return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
|
models/experimental.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 utils.downloads import attempt_download
|
12 |
+
|
13 |
+
|
14 |
+
class Sum(nn.Module):
|
15 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
16 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
17 |
+
super().__init__()
|
18 |
+
self.weight = weight # apply weights boolean
|
19 |
+
self.iter = range(n - 1) # iter object
|
20 |
+
if weight:
|
21 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
22 |
+
|
23 |
+
def forward(self, x):
|
24 |
+
y = x[0] # no weight
|
25 |
+
if self.weight:
|
26 |
+
w = torch.sigmoid(self.w) * 2
|
27 |
+
for i in self.iter:
|
28 |
+
y = y + x[i + 1] * w[i]
|
29 |
+
else:
|
30 |
+
for i in self.iter:
|
31 |
+
y = y + x[i + 1]
|
32 |
+
return y
|
33 |
+
|
34 |
+
|
35 |
+
class MixConv2d(nn.Module):
|
36 |
+
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
37 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
38 |
+
super().__init__()
|
39 |
+
n = len(k) # number of convolutions
|
40 |
+
if equal_ch: # equal c_ per group
|
41 |
+
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
42 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
43 |
+
else: # equal weight.numel() per group
|
44 |
+
b = [c2] + [0] * n
|
45 |
+
a = np.eye(n + 1, n, k=-1)
|
46 |
+
a -= np.roll(a, 1, axis=1)
|
47 |
+
a *= np.array(k) ** 2
|
48 |
+
a[0] = 1
|
49 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
50 |
+
|
51 |
+
self.m = nn.ModuleList([
|
52 |
+
nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
53 |
+
self.bn = nn.BatchNorm2d(c2)
|
54 |
+
self.act = nn.SiLU()
|
55 |
+
|
56 |
+
def forward(self, x):
|
57 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
58 |
+
|
59 |
+
|
60 |
+
class Ensemble(nn.ModuleList):
|
61 |
+
# Ensemble of models
|
62 |
+
def __init__(self):
|
63 |
+
super().__init__()
|
64 |
+
|
65 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
66 |
+
y = [module(x, augment, profile, visualize)[0] for module in self]
|
67 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
68 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
69 |
+
y = torch.cat(y, 1) # nms ensemble
|
70 |
+
return y, None # inference, train output
|
71 |
+
|
72 |
+
|
73 |
+
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
74 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
75 |
+
from models.yolo import Detect, Model
|
76 |
+
|
77 |
+
model = Ensemble()
|
78 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
79 |
+
ckpt = torch.load(attempt_download(w), map_location='cpu') # load
|
80 |
+
ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
|
81 |
+
|
82 |
+
# Model compatibility updates
|
83 |
+
if not hasattr(ckpt, 'stride'):
|
84 |
+
ckpt.stride = torch.tensor([32.])
|
85 |
+
if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):
|
86 |
+
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
|
87 |
+
|
88 |
+
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode
|
89 |
+
|
90 |
+
# Module compatibility updates
|
91 |
+
for m in model.modules():
|
92 |
+
t = type(m)
|
93 |
+
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
94 |
+
m.inplace = inplace # torch 1.7.0 compatibility
|
95 |
+
if t is Detect and not isinstance(m.anchor_grid, list):
|
96 |
+
delattr(m, 'anchor_grid')
|
97 |
+
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
98 |
+
elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
|
99 |
+
m.recompute_scale_factor = None # torch 1.11.0 compatibility
|
100 |
+
|
101 |
+
# Return model
|
102 |
+
if len(model) == 1:
|
103 |
+
return model[-1]
|
104 |
+
|
105 |
+
# Return detection ensemble
|
106 |
+
print(f'Ensemble created with {weights}\n')
|
107 |
+
for k in 'names', 'nc', 'yaml':
|
108 |
+
setattr(model, k, getattr(model[0], k))
|
109 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
110 |
+
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
|
111 |
+
return model
|
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
|
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 |
+
]
|
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 |
+
]
|
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 |
+
]
|
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 |
+
]
|
models/hub/yolov5-fpn.yaml
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 FPN head
|
28 |
+
head:
|
29 |
+
[[-1, 3, C3, [1024, False]], # 10 (P5/32-large)
|
30 |
+
|
31 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
32 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
34 |
+
[-1, 3, C3, [512, False]], # 14 (P4/16-medium)
|
35 |
+
|
36 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
37 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
38 |
+
[-1, 1, Conv, [256, 1, 1]],
|
39 |
+
[-1, 3, C3, [256, False]], # 18 (P3/8-small)
|
40 |
+
|
41 |
+
[[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
42 |
+
]
|
models/hub/yolov5-p2.yaml
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
13 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
14 |
+
[-1, 3, C3, [128]],
|
15 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
16 |
+
[-1, 6, C3, [256]],
|
17 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
18 |
+
[-1, 9, C3, [512]],
|
19 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
20 |
+
[-1, 3, C3, [1024]],
|
21 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
22 |
+
]
|
23 |
+
|
24 |
+
# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs
|
25 |
+
head:
|
26 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
27 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
28 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
29 |
+
[-1, 3, C3, [512, False]], # 13
|
30 |
+
|
31 |
+
[-1, 1, Conv, [256, 1, 1]],
|
32 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
33 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
34 |
+
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
35 |
+
|
36 |
+
[-1, 1, Conv, [128, 1, 1]],
|
37 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
38 |
+
[[-1, 2], 1, Concat, [1]], # cat backbone P2
|
39 |
+
[-1, 1, C3, [128, False]], # 21 (P2/4-xsmall)
|
40 |
+
|
41 |
+
[-1, 1, Conv, [128, 3, 2]],
|
42 |
+
[[-1, 18], 1, Concat, [1]], # cat head P3
|
43 |
+
[-1, 3, C3, [256, False]], # 24 (P3/8-small)
|
44 |
+
|
45 |
+
[-1, 1, Conv, [256, 3, 2]],
|
46 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
47 |
+
[-1, 3, C3, [512, False]], # 27 (P4/16-medium)
|
48 |
+
|
49 |
+
[-1, 1, Conv, [512, 3, 2]],
|
50 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
51 |
+
[-1, 3, C3, [1024, False]], # 30 (P5/32-large)
|
52 |
+
|
53 |
+
[[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
|
54 |
+
]
|
models/hub/yolov5-p34.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: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.50 # layer channel multiple
|
7 |
+
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 0-P1/2
|
13 |
+
[ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
|
14 |
+
[ -1, 3, C3, [ 128 ] ],
|
15 |
+
[ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
|
16 |
+
[ -1, 6, C3, [ 256 ] ],
|
17 |
+
[ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
|
18 |
+
[ -1, 9, C3, [ 512 ] ],
|
19 |
+
[ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32
|
20 |
+
[ -1, 3, C3, [ 1024 ] ],
|
21 |
+
[ -1, 1, SPPF, [ 1024, 5 ] ], # 9
|
22 |
+
]
|
23 |
+
|
24 |
+
# YOLOv5 v6.0 head with (P3, P4) outputs
|
25 |
+
head:
|
26 |
+
[ [ -1, 1, Conv, [ 512, 1, 1 ] ],
|
27 |
+
[ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
|
28 |
+
[ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
|
29 |
+
[ -1, 3, C3, [ 512, False ] ], # 13
|
30 |
+
|
31 |
+
[ -1, 1, Conv, [ 256, 1, 1 ] ],
|
32 |
+
[ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
|
33 |
+
[ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
|
34 |
+
[ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
|
35 |
+
|
36 |
+
[ -1, 1, Conv, [ 256, 3, 2 ] ],
|
37 |
+
[ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
|
38 |
+
[ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium)
|
39 |
+
|
40 |
+
[ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4)
|
41 |
+
]
|
models/hub/yolov5-p6.yaml
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
13 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
14 |
+
[-1, 3, C3, [128]],
|
15 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
16 |
+
[-1, 6, C3, [256]],
|
17 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
18 |
+
[-1, 9, C3, [512]],
|
19 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
20 |
+
[-1, 3, C3, [768]],
|
21 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
22 |
+
[-1, 3, C3, [1024]],
|
23 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
24 |
+
]
|
25 |
+
|
26 |
+
# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs
|
27 |
+
head:
|
28 |
+
[[-1, 1, Conv, [768, 1, 1]],
|
29 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
30 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
31 |
+
[-1, 3, C3, [768, False]], # 15
|
32 |
+
|
33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
34 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
35 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
36 |
+
[-1, 3, C3, [512, False]], # 19
|
37 |
+
|
38 |
+
[-1, 1, Conv, [256, 1, 1]],
|
39 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
40 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
41 |
+
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
42 |
+
|
43 |
+
[-1, 1, Conv, [256, 3, 2]],
|
44 |
+
[[-1, 20], 1, Concat, [1]], # cat head P4
|
45 |
+
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
46 |
+
|
47 |
+
[-1, 1, Conv, [512, 3, 2]],
|
48 |
+
[[-1, 16], 1, Concat, [1]], # cat head P5
|
49 |
+
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
50 |
+
|
51 |
+
[-1, 1, Conv, [768, 3, 2]],
|
52 |
+
[[-1, 12], 1, Concat, [1]], # cat head P6
|
53 |
+
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
54 |
+
|
55 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
56 |
+
]
|
models/hub/yolov5-p7.yaml
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: 3 # AutoAnchor evolves 3 anchors per P output layer
|
8 |
+
|
9 |
+
# YOLOv5 v6.0 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
13 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
14 |
+
[-1, 3, C3, [128]],
|
15 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
16 |
+
[-1, 6, C3, [256]],
|
17 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
18 |
+
[-1, 9, C3, [512]],
|
19 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
20 |
+
[-1, 3, C3, [768]],
|
21 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
22 |
+
[-1, 3, C3, [1024]],
|
23 |
+
[-1, 1, Conv, [1280, 3, 2]], # 11-P7/128
|
24 |
+
[-1, 3, C3, [1280]],
|
25 |
+
[-1, 1, SPPF, [1280, 5]], # 13
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs
|
29 |
+
head:
|
30 |
+
[[-1, 1, Conv, [1024, 1, 1]],
|
31 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
32 |
+
[[-1, 10], 1, Concat, [1]], # cat backbone P6
|
33 |
+
[-1, 3, C3, [1024, False]], # 17
|
34 |
+
|
35 |
+
[-1, 1, Conv, [768, 1, 1]],
|
36 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
37 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
38 |
+
[-1, 3, C3, [768, False]], # 21
|
39 |
+
|
40 |
+
[-1, 1, Conv, [512, 1, 1]],
|
41 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
42 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
43 |
+
[-1, 3, C3, [512, False]], # 25
|
44 |
+
|
45 |
+
[-1, 1, Conv, [256, 1, 1]],
|
46 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
47 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
48 |
+
[-1, 3, C3, [256, False]], # 29 (P3/8-small)
|
49 |
+
|
50 |
+
[-1, 1, Conv, [256, 3, 2]],
|
51 |
+
[[-1, 26], 1, Concat, [1]], # cat head P4
|
52 |
+
[-1, 3, C3, [512, False]], # 32 (P4/16-medium)
|
53 |
+
|
54 |
+
[-1, 1, Conv, [512, 3, 2]],
|
55 |
+
[[-1, 22], 1, Concat, [1]], # cat head P5
|
56 |
+
[-1, 3, C3, [768, False]], # 35 (P5/32-large)
|
57 |
+
|
58 |
+
[-1, 1, Conv, [768, 3, 2]],
|
59 |
+
[[-1, 18], 1, Concat, [1]], # cat head P6
|
60 |
+
[-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge)
|
61 |
+
|
62 |
+
[-1, 1, Conv, [1024, 3, 2]],
|
63 |
+
[[-1, 14], 1, Concat, [1]], # cat head P7
|
64 |
+
[-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge)
|
65 |
+
|
66 |
+
[[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7)
|
67 |
+
]
|
models/hub/yolov5-panet.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 PANet 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], 1, Concat, [1]], # cat head P4
|
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 |
+
]
|
models/hub/yolov5l6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
- [19,27, 44,40, 38,94] # P3/8
|
9 |
+
- [96,68, 86,152, 180,137] # P4/16
|
10 |
+
- [140,301, 303,264, 238,542] # P5/32
|
11 |
+
- [436,615, 739,380, 925,792] # P6/64
|
12 |
+
|
13 |
+
# YOLOv5 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
18 |
+
[-1, 3, C3, [128]],
|
19 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
20 |
+
[-1, 6, C3, [256]],
|
21 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
22 |
+
[-1, 9, C3, [512]],
|
23 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
24 |
+
[-1, 3, C3, [768]],
|
25 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
26 |
+
[-1, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 head
|
31 |
+
head:
|
32 |
+
[[-1, 1, Conv, [768, 1, 1]],
|
33 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
34 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
35 |
+
[-1, 3, C3, [768, False]], # 15
|
36 |
+
|
37 |
+
[-1, 1, Conv, [512, 1, 1]],
|
38 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
39 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
40 |
+
[-1, 3, C3, [512, False]], # 19
|
41 |
+
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
44 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
45 |
+
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
46 |
+
|
47 |
+
[-1, 1, Conv, [256, 3, 2]],
|
48 |
+
[[-1, 20], 1, Concat, [1]], # cat head P4
|
49 |
+
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
50 |
+
|
51 |
+
[-1, 1, Conv, [512, 3, 2]],
|
52 |
+
[[-1, 16], 1, Concat, [1]], # cat head P5
|
53 |
+
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
54 |
+
|
55 |
+
[-1, 1, Conv, [768, 3, 2]],
|
56 |
+
[[-1, 12], 1, Concat, [1]], # cat head P6
|
57 |
+
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
58 |
+
|
59 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
60 |
+
]
|
models/hub/yolov5m6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 0.67 # model depth multiple
|
6 |
+
width_multiple: 0.75 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [19,27, 44,40, 38,94] # P3/8
|
9 |
+
- [96,68, 86,152, 180,137] # P4/16
|
10 |
+
- [140,301, 303,264, 238,542] # P5/32
|
11 |
+
- [436,615, 739,380, 925,792] # P6/64
|
12 |
+
|
13 |
+
# YOLOv5 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
18 |
+
[-1, 3, C3, [128]],
|
19 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
20 |
+
[-1, 6, C3, [256]],
|
21 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
22 |
+
[-1, 9, C3, [512]],
|
23 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
24 |
+
[-1, 3, C3, [768]],
|
25 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
26 |
+
[-1, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 head
|
31 |
+
head:
|
32 |
+
[[-1, 1, Conv, [768, 1, 1]],
|
33 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
34 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
35 |
+
[-1, 3, C3, [768, False]], # 15
|
36 |
+
|
37 |
+
[-1, 1, Conv, [512, 1, 1]],
|
38 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
39 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
40 |
+
[-1, 3, C3, [512, False]], # 19
|
41 |
+
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
44 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
45 |
+
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
46 |
+
|
47 |
+
[-1, 1, Conv, [256, 3, 2]],
|
48 |
+
[[-1, 20], 1, Concat, [1]], # cat head P4
|
49 |
+
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
50 |
+
|
51 |
+
[-1, 1, Conv, [512, 3, 2]],
|
52 |
+
[[-1, 16], 1, Concat, [1]], # cat head P5
|
53 |
+
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
54 |
+
|
55 |
+
[-1, 1, Conv, [768, 3, 2]],
|
56 |
+
[[-1, 12], 1, Concat, [1]], # cat head P6
|
57 |
+
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
58 |
+
|
59 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
60 |
+
]
|
models/hub/yolov5n6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.25 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [19,27, 44,40, 38,94] # P3/8
|
9 |
+
- [96,68, 86,152, 180,137] # P4/16
|
10 |
+
- [140,301, 303,264, 238,542] # P5/32
|
11 |
+
- [436,615, 739,380, 925,792] # P6/64
|
12 |
+
|
13 |
+
# YOLOv5 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
18 |
+
[-1, 3, C3, [128]],
|
19 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
20 |
+
[-1, 6, C3, [256]],
|
21 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
22 |
+
[-1, 9, C3, [512]],
|
23 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
24 |
+
[-1, 3, C3, [768]],
|
25 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
26 |
+
[-1, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 head
|
31 |
+
head:
|
32 |
+
[[-1, 1, Conv, [768, 1, 1]],
|
33 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
34 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
35 |
+
[-1, 3, C3, [768, False]], # 15
|
36 |
+
|
37 |
+
[-1, 1, Conv, [512, 1, 1]],
|
38 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
39 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
40 |
+
[-1, 3, C3, [512, False]], # 19
|
41 |
+
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
44 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
45 |
+
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
46 |
+
|
47 |
+
[-1, 1, Conv, [256, 3, 2]],
|
48 |
+
[[-1, 20], 1, Concat, [1]], # cat head P4
|
49 |
+
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
50 |
+
|
51 |
+
[-1, 1, Conv, [512, 3, 2]],
|
52 |
+
[[-1, 16], 1, Concat, [1]], # cat head P5
|
53 |
+
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
54 |
+
|
55 |
+
[-1, 1, Conv, [768, 3, 2]],
|
56 |
+
[[-1, 12], 1, Concat, [1]], # cat head P6
|
57 |
+
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
58 |
+
|
59 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
60 |
+
]
|
models/hub/yolov5s-LeakyReLU.yaml
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
activation: nn.LeakyReLU(0.1) # <----- Conv() activation used throughout entire YOLOv5 model
|
6 |
+
depth_multiple: 0.33 # model depth multiple
|
7 |
+
width_multiple: 0.50 # layer channel multiple
|
8 |
+
anchors:
|
9 |
+
- [10,13, 16,30, 33,23] # P3/8
|
10 |
+
- [30,61, 62,45, 59,119] # P4/16
|
11 |
+
- [116,90, 156,198, 373,326] # P5/32
|
12 |
+
|
13 |
+
# YOLOv5 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
18 |
+
[-1, 3, C3, [128]],
|
19 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
20 |
+
[-1, 6, C3, [256]],
|
21 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
22 |
+
[-1, 9, C3, [512]],
|
23 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
24 |
+
[-1, 3, C3, [1024]],
|
25 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv5 v6.0 head
|
29 |
+
head:
|
30 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
31 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
32 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
33 |
+
[-1, 3, C3, [512, False]], # 13
|
34 |
+
|
35 |
+
[-1, 1, Conv, [256, 1, 1]],
|
36 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
37 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
38 |
+
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
39 |
+
|
40 |
+
[-1, 1, Conv, [256, 3, 2]],
|
41 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
42 |
+
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
43 |
+
|
44 |
+
[-1, 1, Conv, [512, 3, 2]],
|
45 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
46 |
+
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
47 |
+
|
48 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
49 |
+
]
|
models/hub/yolov5s-ghost.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: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.50 # 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, GhostConv, [128, 3, 2]], # 1-P2/4
|
17 |
+
[-1, 3, C3Ghost, [128]],
|
18 |
+
[-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8
|
19 |
+
[-1, 6, C3Ghost, [256]],
|
20 |
+
[-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16
|
21 |
+
[-1, 9, C3Ghost, [512]],
|
22 |
+
[-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32
|
23 |
+
[-1, 3, C3Ghost, [1024]],
|
24 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
25 |
+
]
|
26 |
+
|
27 |
+
# YOLOv5 v6.0 head
|
28 |
+
head:
|
29 |
+
[[-1, 1, GhostConv, [512, 1, 1]],
|
30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
32 |
+
[-1, 3, C3Ghost, [512, False]], # 13
|
33 |
+
|
34 |
+
[-1, 1, GhostConv, [256, 1, 1]],
|
35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
37 |
+
[-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small)
|
38 |
+
|
39 |
+
[-1, 1, GhostConv, [256, 3, 2]],
|
40 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
41 |
+
[-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium)
|
42 |
+
|
43 |
+
[-1, 1, GhostConv, [512, 3, 2]],
|
44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
45 |
+
[-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large)
|
46 |
+
|
47 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
48 |
+
]
|
models/hub/yolov5s-transformer.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: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.50 # 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, C3TR, [1024]], # 9 <--- C3TR() Transformer module
|
24 |
+
[-1, 1, SPPF, [1024, 5]], # 9
|
25 |
+
]
|
26 |
+
|
27 |
+
# YOLOv5 v6.0 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], 1, Concat, [1]], # cat head P4
|
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 |
+
]
|
models/hub/yolov5s6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.50 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [19,27, 44,40, 38,94] # P3/8
|
9 |
+
- [96,68, 86,152, 180,137] # P4/16
|
10 |
+
- [140,301, 303,264, 238,542] # P5/32
|
11 |
+
- [436,615, 739,380, 925,792] # P6/64
|
12 |
+
|
13 |
+
# YOLOv5 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
18 |
+
[-1, 3, C3, [128]],
|
19 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
20 |
+
[-1, 6, C3, [256]],
|
21 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
22 |
+
[-1, 9, C3, [512]],
|
23 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
24 |
+
[-1, 3, C3, [768]],
|
25 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
26 |
+
[-1, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 head
|
31 |
+
head:
|
32 |
+
[[-1, 1, Conv, [768, 1, 1]],
|
33 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
34 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
35 |
+
[-1, 3, C3, [768, False]], # 15
|
36 |
+
|
37 |
+
[-1, 1, Conv, [512, 1, 1]],
|
38 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
39 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
40 |
+
[-1, 3, C3, [512, False]], # 19
|
41 |
+
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
44 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
45 |
+
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
46 |
+
|
47 |
+
[-1, 1, Conv, [256, 3, 2]],
|
48 |
+
[[-1, 20], 1, Concat, [1]], # cat head P4
|
49 |
+
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
50 |
+
|
51 |
+
[-1, 1, Conv, [512, 3, 2]],
|
52 |
+
[[-1, 16], 1, Concat, [1]], # cat head P5
|
53 |
+
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
54 |
+
|
55 |
+
[-1, 1, Conv, [768, 3, 2]],
|
56 |
+
[[-1, 12], 1, Concat, [1]], # cat head P6
|
57 |
+
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
58 |
+
|
59 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
60 |
+
]
|
models/hub/yolov5x6.yaml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.33 # model depth multiple
|
6 |
+
width_multiple: 1.25 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [19,27, 44,40, 38,94] # P3/8
|
9 |
+
- [96,68, 86,152, 180,137] # P4/16
|
10 |
+
- [140,301, 303,264, 238,542] # P5/32
|
11 |
+
- [436,615, 739,380, 925,792] # P6/64
|
12 |
+
|
13 |
+
# YOLOv5 v6.0 backbone
|
14 |
+
backbone:
|
15 |
+
# [from, number, module, args]
|
16 |
+
[[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
18 |
+
[-1, 3, C3, [128]],
|
19 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
20 |
+
[-1, 6, C3, [256]],
|
21 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
22 |
+
[-1, 9, C3, [512]],
|
23 |
+
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
24 |
+
[-1, 3, C3, [768]],
|
25 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
26 |
+
[-1, 3, C3, [1024]],
|
27 |
+
[-1, 1, SPPF, [1024, 5]], # 11
|
28 |
+
]
|
29 |
+
|
30 |
+
# YOLOv5 v6.0 head
|
31 |
+
head:
|
32 |
+
[[-1, 1, Conv, [768, 1, 1]],
|
33 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
34 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
35 |
+
[-1, 3, C3, [768, False]], # 15
|
36 |
+
|
37 |
+
[-1, 1, Conv, [512, 1, 1]],
|
38 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
39 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
40 |
+
[-1, 3, C3, [512, False]], # 19
|
41 |
+
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
44 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
45 |
+
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
46 |
+
|
47 |
+
[-1, 1, Conv, [256, 3, 2]],
|
48 |
+
[[-1, 20], 1, Concat, [1]], # cat head P4
|
49 |
+
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
50 |
+
|
51 |
+
[-1, 1, Conv, [512, 3, 2]],
|
52 |
+
[[-1, 16], 1, Concat, [1]], # cat head P5
|
53 |
+
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
54 |
+
|
55 |
+
[-1, 1, Conv, [768, 3, 2]],
|
56 |
+
[[-1, 12], 1, Concat, [1]], # cat head P6
|
57 |
+
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
58 |
+
|
59 |
+
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
60 |
+
]
|
models/segment/yolov5l-seg.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 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], 1, Concat, [1]], # cat head P4
|
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, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
48 |
+
]
|
models/segment/yolov5m-seg.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: 0.67 # model depth multiple
|
6 |
+
width_multiple: 0.75 # 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 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], 1, Concat, [1]], # cat head P4
|
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, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
48 |
+
]
|
models/segment/yolov5n-seg.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: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.25 # 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 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], 1, Concat, [1]], # cat head P4
|
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, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
48 |
+
]
|
models/segment/yolov5s-seg.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: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.5 # 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 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], 1, Concat, [1]], # cat head P4
|
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, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
48 |
+
]
|
models/segment/yolov5x-seg.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.33 # model depth multiple
|
6 |
+
width_multiple: 1.25 # 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 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], 1, Concat, [1]], # cat head P4
|
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, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
48 |
+
]
|
models/tf.py
ADDED
@@ -0,0 +1,608 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
TensorFlow, Keras and TFLite versions of YOLOv5
|
4 |
+
Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127
|
5 |
+
|
6 |
+
Usage:
|
7 |
+
$ python models/tf.py --weights yolov5s.pt
|
8 |
+
|
9 |
+
Export:
|
10 |
+
$ python export.py --weights yolov5s.pt --include saved_model pb tflite tfjs
|
11 |
+
"""
|
12 |
+
|
13 |
+
import argparse
|
14 |
+
import sys
|
15 |
+
from copy import deepcopy
|
16 |
+
from pathlib import Path
|
17 |
+
|
18 |
+
FILE = Path(__file__).resolve()
|
19 |
+
ROOT = FILE.parents[1] # YOLOv5 root directory
|
20 |
+
if str(ROOT) not in sys.path:
|
21 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
22 |
+
# ROOT = ROOT.relative_to(Path.cwd()) # relative
|
23 |
+
|
24 |
+
import numpy as np
|
25 |
+
import tensorflow as tf
|
26 |
+
import torch
|
27 |
+
import torch.nn as nn
|
28 |
+
from tensorflow import keras
|
29 |
+
|
30 |
+
from models.common import (C3, SPP, SPPF, Bottleneck, BottleneckCSP, C3x, Concat, Conv, CrossConv, DWConv,
|
31 |
+
DWConvTranspose2d, Focus, autopad)
|
32 |
+
from models.experimental import MixConv2d, attempt_load
|
33 |
+
from models.yolo import Detect, Segment
|
34 |
+
from utils.activations import SiLU
|
35 |
+
from utils.general import LOGGER, make_divisible, print_args
|
36 |
+
|
37 |
+
|
38 |
+
class TFBN(keras.layers.Layer):
|
39 |
+
# TensorFlow BatchNormalization wrapper
|
40 |
+
def __init__(self, w=None):
|
41 |
+
super().__init__()
|
42 |
+
self.bn = keras.layers.BatchNormalization(
|
43 |
+
beta_initializer=keras.initializers.Constant(w.bias.numpy()),
|
44 |
+
gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
|
45 |
+
moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
|
46 |
+
moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
|
47 |
+
epsilon=w.eps)
|
48 |
+
|
49 |
+
def call(self, inputs):
|
50 |
+
return self.bn(inputs)
|
51 |
+
|
52 |
+
|
53 |
+
class TFPad(keras.layers.Layer):
|
54 |
+
# Pad inputs in spatial dimensions 1 and 2
|
55 |
+
def __init__(self, pad):
|
56 |
+
super().__init__()
|
57 |
+
if isinstance(pad, int):
|
58 |
+
self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
|
59 |
+
else: # tuple/list
|
60 |
+
self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]])
|
61 |
+
|
62 |
+
def call(self, inputs):
|
63 |
+
return tf.pad(inputs, self.pad, mode='constant', constant_values=0)
|
64 |
+
|
65 |
+
|
66 |
+
class TFConv(keras.layers.Layer):
|
67 |
+
# Standard convolution
|
68 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
|
69 |
+
# ch_in, ch_out, weights, kernel, stride, padding, groups
|
70 |
+
super().__init__()
|
71 |
+
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
|
72 |
+
# TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
|
73 |
+
# see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
|
74 |
+
conv = keras.layers.Conv2D(
|
75 |
+
filters=c2,
|
76 |
+
kernel_size=k,
|
77 |
+
strides=s,
|
78 |
+
padding='SAME' if s == 1 else 'VALID',
|
79 |
+
use_bias=not hasattr(w, 'bn'),
|
80 |
+
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
|
81 |
+
bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
|
82 |
+
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
|
83 |
+
self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
|
84 |
+
self.act = activations(w.act) if act else tf.identity
|
85 |
+
|
86 |
+
def call(self, inputs):
|
87 |
+
return self.act(self.bn(self.conv(inputs)))
|
88 |
+
|
89 |
+
|
90 |
+
class TFDWConv(keras.layers.Layer):
|
91 |
+
# Depthwise convolution
|
92 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
|
93 |
+
# ch_in, ch_out, weights, kernel, stride, padding, groups
|
94 |
+
super().__init__()
|
95 |
+
assert c2 % c1 == 0, f'TFDWConv() output={c2} must be a multiple of input={c1} channels'
|
96 |
+
conv = keras.layers.DepthwiseConv2D(
|
97 |
+
kernel_size=k,
|
98 |
+
depth_multiplier=c2 // c1,
|
99 |
+
strides=s,
|
100 |
+
padding='SAME' if s == 1 else 'VALID',
|
101 |
+
use_bias=not hasattr(w, 'bn'),
|
102 |
+
depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
|
103 |
+
bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
|
104 |
+
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
|
105 |
+
self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
|
106 |
+
self.act = activations(w.act) if act else tf.identity
|
107 |
+
|
108 |
+
def call(self, inputs):
|
109 |
+
return self.act(self.bn(self.conv(inputs)))
|
110 |
+
|
111 |
+
|
112 |
+
class TFDWConvTranspose2d(keras.layers.Layer):
|
113 |
+
# Depthwise ConvTranspose2d
|
114 |
+
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
|
115 |
+
# ch_in, ch_out, weights, kernel, stride, padding, groups
|
116 |
+
super().__init__()
|
117 |
+
assert c1 == c2, f'TFDWConv() output={c2} must be equal to input={c1} channels'
|
118 |
+
assert k == 4 and p1 == 1, 'TFDWConv() only valid for k=4 and p1=1'
|
119 |
+
weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy()
|
120 |
+
self.c1 = c1
|
121 |
+
self.conv = [
|
122 |
+
keras.layers.Conv2DTranspose(filters=1,
|
123 |
+
kernel_size=k,
|
124 |
+
strides=s,
|
125 |
+
padding='VALID',
|
126 |
+
output_padding=p2,
|
127 |
+
use_bias=True,
|
128 |
+
kernel_initializer=keras.initializers.Constant(weight[..., i:i + 1]),
|
129 |
+
bias_initializer=keras.initializers.Constant(bias[i])) for i in range(c1)]
|
130 |
+
|
131 |
+
def call(self, inputs):
|
132 |
+
return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1]
|
133 |
+
|
134 |
+
|
135 |
+
class TFFocus(keras.layers.Layer):
|
136 |
+
# Focus wh information into c-space
|
137 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
|
138 |
+
# ch_in, ch_out, kernel, stride, padding, groups
|
139 |
+
super().__init__()
|
140 |
+
self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
|
141 |
+
|
142 |
+
def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
|
143 |
+
# inputs = inputs / 255 # normalize 0-255 to 0-1
|
144 |
+
inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]]
|
145 |
+
return self.conv(tf.concat(inputs, 3))
|
146 |
+
|
147 |
+
|
148 |
+
class TFBottleneck(keras.layers.Layer):
|
149 |
+
# Standard bottleneck
|
150 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion
|
151 |
+
super().__init__()
|
152 |
+
c_ = int(c2 * e) # hidden channels
|
153 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
154 |
+
self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
|
155 |
+
self.add = shortcut and c1 == c2
|
156 |
+
|
157 |
+
def call(self, inputs):
|
158 |
+
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
|
159 |
+
|
160 |
+
|
161 |
+
class TFCrossConv(keras.layers.Layer):
|
162 |
+
# Cross Convolution
|
163 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
|
164 |
+
super().__init__()
|
165 |
+
c_ = int(c2 * e) # hidden channels
|
166 |
+
self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1)
|
167 |
+
self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2)
|
168 |
+
self.add = shortcut and c1 == c2
|
169 |
+
|
170 |
+
def call(self, inputs):
|
171 |
+
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
|
172 |
+
|
173 |
+
|
174 |
+
class TFConv2d(keras.layers.Layer):
|
175 |
+
# Substitution for PyTorch nn.Conv2D
|
176 |
+
def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
|
177 |
+
super().__init__()
|
178 |
+
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
|
179 |
+
self.conv = keras.layers.Conv2D(filters=c2,
|
180 |
+
kernel_size=k,
|
181 |
+
strides=s,
|
182 |
+
padding='VALID',
|
183 |
+
use_bias=bias,
|
184 |
+
kernel_initializer=keras.initializers.Constant(
|
185 |
+
w.weight.permute(2, 3, 1, 0).numpy()),
|
186 |
+
bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None)
|
187 |
+
|
188 |
+
def call(self, inputs):
|
189 |
+
return self.conv(inputs)
|
190 |
+
|
191 |
+
|
192 |
+
class TFBottleneckCSP(keras.layers.Layer):
|
193 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
194 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
195 |
+
# ch_in, ch_out, number, shortcut, groups, expansion
|
196 |
+
super().__init__()
|
197 |
+
c_ = int(c2 * e) # hidden channels
|
198 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
199 |
+
self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
|
200 |
+
self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
|
201 |
+
self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
|
202 |
+
self.bn = TFBN(w.bn)
|
203 |
+
self.act = lambda x: keras.activations.swish(x)
|
204 |
+
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
|
205 |
+
|
206 |
+
def call(self, inputs):
|
207 |
+
y1 = self.cv3(self.m(self.cv1(inputs)))
|
208 |
+
y2 = self.cv2(inputs)
|
209 |
+
return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
|
210 |
+
|
211 |
+
|
212 |
+
class TFC3(keras.layers.Layer):
|
213 |
+
# CSP Bottleneck with 3 convolutions
|
214 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
215 |
+
# ch_in, ch_out, number, shortcut, groups, expansion
|
216 |
+
super().__init__()
|
217 |
+
c_ = int(c2 * e) # hidden channels
|
218 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
219 |
+
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
|
220 |
+
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
|
221 |
+
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
|
222 |
+
|
223 |
+
def call(self, inputs):
|
224 |
+
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
|
225 |
+
|
226 |
+
|
227 |
+
class TFC3x(keras.layers.Layer):
|
228 |
+
# 3 module with cross-convolutions
|
229 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
230 |
+
# ch_in, ch_out, number, shortcut, groups, expansion
|
231 |
+
super().__init__()
|
232 |
+
c_ = int(c2 * e) # hidden channels
|
233 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
234 |
+
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
|
235 |
+
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
|
236 |
+
self.m = keras.Sequential([
|
237 |
+
TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)])
|
238 |
+
|
239 |
+
def call(self, inputs):
|
240 |
+
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
|
241 |
+
|
242 |
+
|
243 |
+
class TFSPP(keras.layers.Layer):
|
244 |
+
# Spatial pyramid pooling layer used in YOLOv3-SPP
|
245 |
+
def __init__(self, c1, c2, k=(5, 9, 13), w=None):
|
246 |
+
super().__init__()
|
247 |
+
c_ = c1 // 2 # hidden channels
|
248 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
249 |
+
self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
|
250 |
+
self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]
|
251 |
+
|
252 |
+
def call(self, inputs):
|
253 |
+
x = self.cv1(inputs)
|
254 |
+
return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
|
255 |
+
|
256 |
+
|
257 |
+
class TFSPPF(keras.layers.Layer):
|
258 |
+
# Spatial pyramid pooling-Fast layer
|
259 |
+
def __init__(self, c1, c2, k=5, w=None):
|
260 |
+
super().__init__()
|
261 |
+
c_ = c1 // 2 # hidden channels
|
262 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
263 |
+
self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
|
264 |
+
self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')
|
265 |
+
|
266 |
+
def call(self, inputs):
|
267 |
+
x = self.cv1(inputs)
|
268 |
+
y1 = self.m(x)
|
269 |
+
y2 = self.m(y1)
|
270 |
+
return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
|
271 |
+
|
272 |
+
|
273 |
+
class TFDetect(keras.layers.Layer):
|
274 |
+
# TF YOLOv5 Detect layer
|
275 |
+
def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer
|
276 |
+
super().__init__()
|
277 |
+
self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
|
278 |
+
self.nc = nc # number of classes
|
279 |
+
self.no = nc + 5 # number of outputs per anchor
|
280 |
+
self.nl = len(anchors) # number of detection layers
|
281 |
+
self.na = len(anchors[0]) // 2 # number of anchors
|
282 |
+
self.grid = [tf.zeros(1)] * self.nl # init grid
|
283 |
+
self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
|
284 |
+
self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2])
|
285 |
+
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
|
286 |
+
self.training = False # set to False after building model
|
287 |
+
self.imgsz = imgsz
|
288 |
+
for i in range(self.nl):
|
289 |
+
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
|
290 |
+
self.grid[i] = self._make_grid(nx, ny)
|
291 |
+
|
292 |
+
def call(self, inputs):
|
293 |
+
z = [] # inference output
|
294 |
+
x = []
|
295 |
+
for i in range(self.nl):
|
296 |
+
x.append(self.m[i](inputs[i]))
|
297 |
+
# x(bs,20,20,255) to x(bs,3,20,20,85)
|
298 |
+
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
|
299 |
+
x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])
|
300 |
+
|
301 |
+
if not self.training: # inference
|
302 |
+
y = x[i]
|
303 |
+
grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5
|
304 |
+
anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4
|
305 |
+
xy = (tf.sigmoid(y[..., 0:2]) * 2 + grid) * self.stride[i] # xy
|
306 |
+
wh = tf.sigmoid(y[..., 2:4]) ** 2 * anchor_grid
|
307 |
+
# Normalize xywh to 0-1 to reduce calibration error
|
308 |
+
xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
|
309 |
+
wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
|
310 |
+
y = tf.concat([xy, wh, tf.sigmoid(y[..., 4:5 + self.nc]), y[..., 5 + self.nc:]], -1)
|
311 |
+
z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))
|
312 |
+
|
313 |
+
return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1),)
|
314 |
+
|
315 |
+
@staticmethod
|
316 |
+
def _make_grid(nx=20, ny=20):
|
317 |
+
# yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
|
318 |
+
# return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
|
319 |
+
xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
|
320 |
+
return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
|
321 |
+
|
322 |
+
|
323 |
+
class TFSegment(TFDetect):
|
324 |
+
# YOLOv5 Segment head for segmentation models
|
325 |
+
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), imgsz=(640, 640), w=None):
|
326 |
+
super().__init__(nc, anchors, ch, imgsz, w)
|
327 |
+
self.nm = nm # number of masks
|
328 |
+
self.npr = npr # number of protos
|
329 |
+
self.no = 5 + nc + self.nm # number of outputs per anchor
|
330 |
+
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] # output conv
|
331 |
+
self.proto = TFProto(ch[0], self.npr, self.nm, w=w.proto) # protos
|
332 |
+
self.detect = TFDetect.call
|
333 |
+
|
334 |
+
def call(self, x):
|
335 |
+
p = self.proto(x[0])
|
336 |
+
# p = TFUpsample(None, scale_factor=4, mode='nearest')(self.proto(x[0])) # (optional) full-size protos
|
337 |
+
p = tf.transpose(p, [0, 3, 1, 2]) # from shape(1,160,160,32) to shape(1,32,160,160)
|
338 |
+
x = self.detect(self, x)
|
339 |
+
return (x, p) if self.training else (x[0], p)
|
340 |
+
|
341 |
+
|
342 |
+
class TFProto(keras.layers.Layer):
|
343 |
+
|
344 |
+
def __init__(self, c1, c_=256, c2=32, w=None):
|
345 |
+
super().__init__()
|
346 |
+
self.cv1 = TFConv(c1, c_, k=3, w=w.cv1)
|
347 |
+
self.upsample = TFUpsample(None, scale_factor=2, mode='nearest')
|
348 |
+
self.cv2 = TFConv(c_, c_, k=3, w=w.cv2)
|
349 |
+
self.cv3 = TFConv(c_, c2, w=w.cv3)
|
350 |
+
|
351 |
+
def call(self, inputs):
|
352 |
+
return self.cv3(self.cv2(self.upsample(self.cv1(inputs))))
|
353 |
+
|
354 |
+
|
355 |
+
class TFUpsample(keras.layers.Layer):
|
356 |
+
# TF version of torch.nn.Upsample()
|
357 |
+
def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'
|
358 |
+
super().__init__()
|
359 |
+
assert scale_factor % 2 == 0, "scale_factor must be multiple of 2"
|
360 |
+
self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * scale_factor, x.shape[2] * scale_factor), mode)
|
361 |
+
# self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
|
362 |
+
# with default arguments: align_corners=False, half_pixel_centers=False
|
363 |
+
# self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
|
364 |
+
# size=(x.shape[1] * 2, x.shape[2] * 2))
|
365 |
+
|
366 |
+
def call(self, inputs):
|
367 |
+
return self.upsample(inputs)
|
368 |
+
|
369 |
+
|
370 |
+
class TFConcat(keras.layers.Layer):
|
371 |
+
# TF version of torch.concat()
|
372 |
+
def __init__(self, dimension=1, w=None):
|
373 |
+
super().__init__()
|
374 |
+
assert dimension == 1, "convert only NCHW to NHWC concat"
|
375 |
+
self.d = 3
|
376 |
+
|
377 |
+
def call(self, inputs):
|
378 |
+
return tf.concat(inputs, self.d)
|
379 |
+
|
380 |
+
|
381 |
+
def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
|
382 |
+
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
|
383 |
+
anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
|
384 |
+
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
385 |
+
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
386 |
+
|
387 |
+
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
388 |
+
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
|
389 |
+
m_str = m
|
390 |
+
m = eval(m) if isinstance(m, str) else m # eval strings
|
391 |
+
for j, a in enumerate(args):
|
392 |
+
try:
|
393 |
+
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
394 |
+
except NameError:
|
395 |
+
pass
|
396 |
+
|
397 |
+
n = max(round(n * gd), 1) if n > 1 else n # depth gain
|
398 |
+
if m in [
|
399 |
+
nn.Conv2d, Conv, DWConv, DWConvTranspose2d, Bottleneck, SPP, SPPF, MixConv2d, Focus, CrossConv,
|
400 |
+
BottleneckCSP, C3, C3x]:
|
401 |
+
c1, c2 = ch[f], args[0]
|
402 |
+
c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
|
403 |
+
|
404 |
+
args = [c1, c2, *args[1:]]
|
405 |
+
if m in [BottleneckCSP, C3, C3x]:
|
406 |
+
args.insert(2, n)
|
407 |
+
n = 1
|
408 |
+
elif m is nn.BatchNorm2d:
|
409 |
+
args = [ch[f]]
|
410 |
+
elif m is Concat:
|
411 |
+
c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
|
412 |
+
elif m in [Detect, Segment]:
|
413 |
+
args.append([ch[x + 1] for x in f])
|
414 |
+
if isinstance(args[1], int): # number of anchors
|
415 |
+
args[1] = [list(range(args[1] * 2))] * len(f)
|
416 |
+
if m is Segment:
|
417 |
+
args[3] = make_divisible(args[3] * gw, 8)
|
418 |
+
args.append(imgsz)
|
419 |
+
else:
|
420 |
+
c2 = ch[f]
|
421 |
+
|
422 |
+
tf_m = eval('TF' + m_str.replace('nn.', ''))
|
423 |
+
m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \
|
424 |
+
else tf_m(*args, w=model.model[i]) # module
|
425 |
+
|
426 |
+
torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
|
427 |
+
t = str(m)[8:-2].replace('__main__.', '') # module type
|
428 |
+
np = sum(x.numel() for x in torch_m_.parameters()) # number params
|
429 |
+
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
430 |
+
LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print
|
431 |
+
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
432 |
+
layers.append(m_)
|
433 |
+
ch.append(c2)
|
434 |
+
return keras.Sequential(layers), sorted(save)
|
435 |
+
|
436 |
+
|
437 |
+
class TFModel:
|
438 |
+
# TF YOLOv5 model
|
439 |
+
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes
|
440 |
+
super().__init__()
|
441 |
+
if isinstance(cfg, dict):
|
442 |
+
self.yaml = cfg # model dict
|
443 |
+
else: # is *.yaml
|
444 |
+
import yaml # for torch hub
|
445 |
+
self.yaml_file = Path(cfg).name
|
446 |
+
with open(cfg) as f:
|
447 |
+
self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
448 |
+
|
449 |
+
# Define model
|
450 |
+
if nc and nc != self.yaml['nc']:
|
451 |
+
LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
|
452 |
+
self.yaml['nc'] = nc # override yaml value
|
453 |
+
self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
|
454 |
+
|
455 |
+
def predict(self,
|
456 |
+
inputs,
|
457 |
+
tf_nms=False,
|
458 |
+
agnostic_nms=False,
|
459 |
+
topk_per_class=100,
|
460 |
+
topk_all=100,
|
461 |
+
iou_thres=0.45,
|
462 |
+
conf_thres=0.25):
|
463 |
+
y = [] # outputs
|
464 |
+
x = inputs
|
465 |
+
for m in self.model.layers:
|
466 |
+
if m.f != -1: # if not from previous layer
|
467 |
+
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
|
468 |
+
|
469 |
+
x = m(x) # run
|
470 |
+
y.append(x if m.i in self.savelist else None) # save output
|
471 |
+
|
472 |
+
# Add TensorFlow NMS
|
473 |
+
if tf_nms:
|
474 |
+
boxes = self._xywh2xyxy(x[0][..., :4])
|
475 |
+
probs = x[0][:, :, 4:5]
|
476 |
+
classes = x[0][:, :, 5:]
|
477 |
+
scores = probs * classes
|
478 |
+
if agnostic_nms:
|
479 |
+
nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
|
480 |
+
else:
|
481 |
+
boxes = tf.expand_dims(boxes, 2)
|
482 |
+
nms = tf.image.combined_non_max_suppression(boxes,
|
483 |
+
scores,
|
484 |
+
topk_per_class,
|
485 |
+
topk_all,
|
486 |
+
iou_thres,
|
487 |
+
conf_thres,
|
488 |
+
clip_boxes=False)
|
489 |
+
return (nms,)
|
490 |
+
return x # output [1,6300,85] = [xywh, conf, class0, class1, ...]
|
491 |
+
# x = x[0] # [x(1,6300,85), ...] to x(6300,85)
|
492 |
+
# xywh = x[..., :4] # x(6300,4) boxes
|
493 |
+
# conf = x[..., 4:5] # x(6300,1) confidences
|
494 |
+
# cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
|
495 |
+
# return tf.concat([conf, cls, xywh], 1)
|
496 |
+
|
497 |
+
@staticmethod
|
498 |
+
def _xywh2xyxy(xywh):
|
499 |
+
# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
|
500 |
+
x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
|
501 |
+
return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
|
502 |
+
|
503 |
+
|
504 |
+
class AgnosticNMS(keras.layers.Layer):
|
505 |
+
# TF Agnostic NMS
|
506 |
+
def call(self, input, topk_all, iou_thres, conf_thres):
|
507 |
+
# wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450
|
508 |
+
return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres),
|
509 |
+
input,
|
510 |
+
fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
|
511 |
+
name='agnostic_nms')
|
512 |
+
|
513 |
+
@staticmethod
|
514 |
+
def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
|
515 |
+
boxes, classes, scores = x
|
516 |
+
class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
|
517 |
+
scores_inp = tf.reduce_max(scores, -1)
|
518 |
+
selected_inds = tf.image.non_max_suppression(boxes,
|
519 |
+
scores_inp,
|
520 |
+
max_output_size=topk_all,
|
521 |
+
iou_threshold=iou_thres,
|
522 |
+
score_threshold=conf_thres)
|
523 |
+
selected_boxes = tf.gather(boxes, selected_inds)
|
524 |
+
padded_boxes = tf.pad(selected_boxes,
|
525 |
+
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
|
526 |
+
mode="CONSTANT",
|
527 |
+
constant_values=0.0)
|
528 |
+
selected_scores = tf.gather(scores_inp, selected_inds)
|
529 |
+
padded_scores = tf.pad(selected_scores,
|
530 |
+
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
|
531 |
+
mode="CONSTANT",
|
532 |
+
constant_values=-1.0)
|
533 |
+
selected_classes = tf.gather(class_inds, selected_inds)
|
534 |
+
padded_classes = tf.pad(selected_classes,
|
535 |
+
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
|
536 |
+
mode="CONSTANT",
|
537 |
+
constant_values=-1.0)
|
538 |
+
valid_detections = tf.shape(selected_inds)[0]
|
539 |
+
return padded_boxes, padded_scores, padded_classes, valid_detections
|
540 |
+
|
541 |
+
|
542 |
+
def activations(act=nn.SiLU):
|
543 |
+
# Returns TF activation from input PyTorch activation
|
544 |
+
if isinstance(act, nn.LeakyReLU):
|
545 |
+
return lambda x: keras.activations.relu(x, alpha=0.1)
|
546 |
+
elif isinstance(act, nn.Hardswish):
|
547 |
+
return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667
|
548 |
+
elif isinstance(act, (nn.SiLU, SiLU)):
|
549 |
+
return lambda x: keras.activations.swish(x)
|
550 |
+
else:
|
551 |
+
raise Exception(f'no matching TensorFlow activation found for PyTorch activation {act}')
|
552 |
+
|
553 |
+
|
554 |
+
def representative_dataset_gen(dataset, ncalib=100):
|
555 |
+
# Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
|
556 |
+
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
|
557 |
+
im = np.transpose(img, [1, 2, 0])
|
558 |
+
im = np.expand_dims(im, axis=0).astype(np.float32)
|
559 |
+
im /= 255
|
560 |
+
yield [im]
|
561 |
+
if n >= ncalib:
|
562 |
+
break
|
563 |
+
|
564 |
+
|
565 |
+
def run(
|
566 |
+
weights=ROOT / 'yolov5s.pt', # weights path
|
567 |
+
imgsz=(640, 640), # inference size h,w
|
568 |
+
batch_size=1, # batch size
|
569 |
+
dynamic=False, # dynamic batch size
|
570 |
+
):
|
571 |
+
# PyTorch model
|
572 |
+
im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
|
573 |
+
model = attempt_load(weights, device=torch.device('cpu'), inplace=True, fuse=False)
|
574 |
+
_ = model(im) # inference
|
575 |
+
model.info()
|
576 |
+
|
577 |
+
# TensorFlow model
|
578 |
+
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
|
579 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
580 |
+
_ = tf_model.predict(im) # inference
|
581 |
+
|
582 |
+
# Keras model
|
583 |
+
im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
|
584 |
+
keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
|
585 |
+
keras_model.summary()
|
586 |
+
|
587 |
+
LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.')
|
588 |
+
|
589 |
+
|
590 |
+
def parse_opt():
|
591 |
+
parser = argparse.ArgumentParser()
|
592 |
+
parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
|
593 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
|
594 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
595 |
+
parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')
|
596 |
+
opt = parser.parse_args()
|
597 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
598 |
+
print_args(vars(opt))
|
599 |
+
return opt
|
600 |
+
|
601 |
+
|
602 |
+
def main(opt):
|
603 |
+
run(**vars(opt))
|
604 |
+
|
605 |
+
|
606 |
+
if __name__ == "__main__":
|
607 |
+
opt = parse_opt()
|
608 |
+
main(opt)
|
models/yolo.py
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
+
"""
|
3 |
+
YOLO-specific modules
|
4 |
+
|
5 |
+
Usage:
|
6 |
+
$ python models/yolo.py --cfg yolov5s.yaml
|
7 |
+
"""
|
8 |
+
|
9 |
+
import argparse
|
10 |
+
import contextlib
|
11 |
+
import os
|
12 |
+
import platform
|
13 |
+
import sys
|
14 |
+
from copy import deepcopy
|
15 |
+
from pathlib import Path
|
16 |
+
|
17 |
+
FILE = Path(__file__).resolve()
|
18 |
+
ROOT = FILE.parents[1] # YOLOv5 root directory
|
19 |
+
if str(ROOT) not in sys.path:
|
20 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
21 |
+
if platform.system() != 'Windows':
|
22 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
23 |
+
|
24 |
+
from models.common import *
|
25 |
+
from models.experimental import *
|
26 |
+
from utils.autoanchor import check_anchor_order
|
27 |
+
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
|
28 |
+
from utils.plots import feature_visualization
|
29 |
+
from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
|
30 |
+
time_sync)
|
31 |
+
|
32 |
+
try:
|
33 |
+
import thop # for FLOPs computation
|
34 |
+
except ImportError:
|
35 |
+
thop = None
|
36 |
+
|
37 |
+
|
38 |
+
class Detect(nn.Module):
|
39 |
+
# YOLOv5 Detect head for detection models
|
40 |
+
stride = None # strides computed during build
|
41 |
+
dynamic = False # force grid reconstruction
|
42 |
+
export = False # export mode
|
43 |
+
|
44 |
+
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
|
45 |
+
super().__init__()
|
46 |
+
self.nc = nc # number of classes
|
47 |
+
self.no = nc + 5 # number of outputs per anchor
|
48 |
+
self.nl = len(anchors) # number of detection layers
|
49 |
+
self.na = len(anchors[0]) // 2 # number of anchors
|
50 |
+
self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
|
51 |
+
self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
|
52 |
+
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
|
53 |
+
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
|
54 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
55 |
+
|
56 |
+
def forward(self, x):
|
57 |
+
z = [] # inference output
|
58 |
+
for i in range(self.nl):
|
59 |
+
x[i] = self.m[i](x[i]) # conv
|
60 |
+
bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
|
61 |
+
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
|
62 |
+
|
63 |
+
if not self.training: # inference
|
64 |
+
if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
|
65 |
+
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
|
66 |
+
|
67 |
+
if isinstance(self, Segment): # (boxes + masks)
|
68 |
+
xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
|
69 |
+
xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
|
70 |
+
wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
|
71 |
+
y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
|
72 |
+
else: # Detect (boxes only)
|
73 |
+
xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
|
74 |
+
xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
|
75 |
+
wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
|
76 |
+
y = torch.cat((xy, wh, conf), 4)
|
77 |
+
z.append(y.view(bs, self.na * nx * ny, self.no))
|
78 |
+
|
79 |
+
return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
|
80 |
+
|
81 |
+
def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):
|
82 |
+
d = self.anchors[i].device
|
83 |
+
t = self.anchors[i].dtype
|
84 |
+
shape = 1, self.na, ny, nx, 2 # grid shape
|
85 |
+
y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
|
86 |
+
yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
|
87 |
+
grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
|
88 |
+
anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
|
89 |
+
return grid, anchor_grid
|
90 |
+
|
91 |
+
|
92 |
+
class Segment(Detect):
|
93 |
+
# YOLOv5 Segment head for segmentation models
|
94 |
+
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
|
95 |
+
super().__init__(nc, anchors, ch, inplace)
|
96 |
+
self.nm = nm # number of masks
|
97 |
+
self.npr = npr # number of protos
|
98 |
+
self.no = 5 + nc + self.nm # number of outputs per anchor
|
99 |
+
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
|
100 |
+
self.proto = Proto(ch[0], self.npr, self.nm) # protos
|
101 |
+
self.detect = Detect.forward
|
102 |
+
|
103 |
+
def forward(self, x):
|
104 |
+
p = self.proto(x[0])
|
105 |
+
x = self.detect(self, x)
|
106 |
+
return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
|
107 |
+
|
108 |
+
|
109 |
+
class BaseModel(nn.Module):
|
110 |
+
# YOLOv5 base model
|
111 |
+
def forward(self, x, profile=False, visualize=False):
|
112 |
+
return self._forward_once(x, profile, visualize) # single-scale inference, train
|
113 |
+
|
114 |
+
def _forward_once(self, x, profile=False, visualize=False):
|
115 |
+
y, dt = [], [] # outputs
|
116 |
+
for m in self.model:
|
117 |
+
if m.f != -1: # if not from previous layer
|
118 |
+
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
|
119 |
+
if profile:
|
120 |
+
self._profile_one_layer(m, x, dt)
|
121 |
+
x = m(x) # run
|
122 |
+
y.append(x if m.i in self.save else None) # save output
|
123 |
+
if visualize:
|
124 |
+
feature_visualization(x, m.type, m.i, save_dir=visualize)
|
125 |
+
return x
|
126 |
+
|
127 |
+
def _profile_one_layer(self, m, x, dt):
|
128 |
+
c = m == self.model[-1] # is final layer, copy input as inplace fix
|
129 |
+
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
|
130 |
+
t = time_sync()
|
131 |
+
for _ in range(10):
|
132 |
+
m(x.copy() if c else x)
|
133 |
+
dt.append((time_sync() - t) * 100)
|
134 |
+
if m == self.model[0]:
|
135 |
+
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
|
136 |
+
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
|
137 |
+
if c:
|
138 |
+
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
|
139 |
+
|
140 |
+
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
|
141 |
+
LOGGER.info('Fusing layers... ')
|
142 |
+
for m in self.model.modules():
|
143 |
+
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
|
144 |
+
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
|
145 |
+
delattr(m, 'bn') # remove batchnorm
|
146 |
+
m.forward = m.forward_fuse # update forward
|
147 |
+
self.info()
|
148 |
+
return self
|
149 |
+
|
150 |
+
def info(self, verbose=False, img_size=640): # print model information
|
151 |
+
model_info(self, verbose, img_size)
|
152 |
+
|
153 |
+
def _apply(self, fn):
|
154 |
+
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
|
155 |
+
self = super()._apply(fn)
|
156 |
+
m = self.model[-1] # Detect()
|
157 |
+
if isinstance(m, (Detect, Segment)):
|
158 |
+
m.stride = fn(m.stride)
|
159 |
+
m.grid = list(map(fn, m.grid))
|
160 |
+
if isinstance(m.anchor_grid, list):
|
161 |
+
m.anchor_grid = list(map(fn, m.anchor_grid))
|
162 |
+
return self
|
163 |
+
|
164 |
+
|
165 |
+
class DetectionModel(BaseModel):
|
166 |
+
# YOLOv5 detection model
|
167 |
+
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
|
168 |
+
super().__init__()
|
169 |
+
if isinstance(cfg, dict):
|
170 |
+
self.yaml = cfg # model dict
|
171 |
+
else: # is *.yaml
|
172 |
+
import yaml # for torch hub
|
173 |
+
self.yaml_file = Path(cfg).name
|
174 |
+
with open(cfg, encoding='ascii', errors='ignore') as f:
|
175 |
+
self.yaml = yaml.safe_load(f) # model dict
|
176 |
+
|
177 |
+
# Define model
|
178 |
+
ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
|
179 |
+
if nc and nc != self.yaml['nc']:
|
180 |
+
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
|
181 |
+
self.yaml['nc'] = nc # override yaml value
|
182 |
+
if anchors:
|
183 |
+
LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
|
184 |
+
self.yaml['anchors'] = round(anchors) # override yaml value
|
185 |
+
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
|
186 |
+
self.names = [str(i) for i in range(self.yaml['nc'])] # default names
|
187 |
+
self.inplace = self.yaml.get('inplace', True)
|
188 |
+
|
189 |
+
# Build strides, anchors
|
190 |
+
m = self.model[-1] # Detect()
|
191 |
+
if isinstance(m, (Detect, Segment)):
|
192 |
+
s = 256 # 2x min stride
|
193 |
+
m.inplace = self.inplace
|
194 |
+
forward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
|
195 |
+
m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward
|
196 |
+
check_anchor_order(m)
|
197 |
+
m.anchors /= m.stride.view(-1, 1, 1)
|
198 |
+
self.stride = m.stride
|
199 |
+
self._initialize_biases() # only run once
|
200 |
+
|
201 |
+
# Init weights, biases
|
202 |
+
initialize_weights(self)
|
203 |
+
self.info()
|
204 |
+
LOGGER.info('')
|
205 |
+
|
206 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
207 |
+
if augment:
|
208 |
+
return self._forward_augment(x) # augmented inference, None
|
209 |
+
return self._forward_once(x, profile, visualize) # single-scale inference, train
|
210 |
+
|
211 |
+
def _forward_augment(self, x):
|
212 |
+
img_size = x.shape[-2:] # height, width
|
213 |
+
s = [1, 0.83, 0.67] # scales
|
214 |
+
f = [None, 3, None] # flips (2-ud, 3-lr)
|
215 |
+
y = [] # outputs
|
216 |
+
for si, fi in zip(s, f):
|
217 |
+
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
|
218 |
+
yi = self._forward_once(xi)[0] # forward
|
219 |
+
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
|
220 |
+
yi = self._descale_pred(yi, fi, si, img_size)
|
221 |
+
y.append(yi)
|
222 |
+
y = self._clip_augmented(y) # clip augmented tails
|
223 |
+
return torch.cat(y, 1), None # augmented inference, train
|
224 |
+
|
225 |
+
def _descale_pred(self, p, flips, scale, img_size):
|
226 |
+
# de-scale predictions following augmented inference (inverse operation)
|
227 |
+
if self.inplace:
|
228 |
+
p[..., :4] /= scale # de-scale
|
229 |
+
if flips == 2:
|
230 |
+
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
|
231 |
+
elif flips == 3:
|
232 |
+
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
|
233 |
+
else:
|
234 |
+
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
|
235 |
+
if flips == 2:
|
236 |
+
y = img_size[0] - y # de-flip ud
|
237 |
+
elif flips == 3:
|
238 |
+
x = img_size[1] - x # de-flip lr
|
239 |
+
p = torch.cat((x, y, wh, p[..., 4:]), -1)
|
240 |
+
return p
|
241 |
+
|
242 |
+
def _clip_augmented(self, y):
|
243 |
+
# Clip YOLOv5 augmented inference tails
|
244 |
+
nl = self.model[-1].nl # number of detection layers (P3-P5)
|
245 |
+
g = sum(4 ** x for x in range(nl)) # grid points
|
246 |
+
e = 1 # exclude layer count
|
247 |
+
i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
|
248 |
+
y[0] = y[0][:, :-i] # large
|
249 |
+
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
|
250 |
+
y[-1] = y[-1][:, i:] # small
|
251 |
+
return y
|
252 |
+
|
253 |
+
def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
|
254 |
+
# https://arxiv.org/abs/1708.02002 section 3.3
|
255 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
|
256 |
+
m = self.model[-1] # Detect() module
|
257 |
+
for mi, s in zip(m.m, m.stride): # from
|
258 |
+
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
|
259 |
+
b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
|
260 |
+
b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # cls
|
261 |
+
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
|
262 |
+
|
263 |
+
|
264 |
+
Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility
|
265 |
+
|
266 |
+
|
267 |
+
class SegmentationModel(DetectionModel):
|
268 |
+
# YOLOv5 segmentation model
|
269 |
+
def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None):
|
270 |
+
super().__init__(cfg, ch, nc, anchors)
|
271 |
+
|
272 |
+
|
273 |
+
class ClassificationModel(BaseModel):
|
274 |
+
# YOLOv5 classification model
|
275 |
+
def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index
|
276 |
+
super().__init__()
|
277 |
+
self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
|
278 |
+
|
279 |
+
def _from_detection_model(self, model, nc=1000, cutoff=10):
|
280 |
+
# Create a YOLOv5 classification model from a YOLOv5 detection model
|
281 |
+
if isinstance(model, DetectMultiBackend):
|
282 |
+
model = model.model # unwrap DetectMultiBackend
|
283 |
+
model.model = model.model[:cutoff] # backbone
|
284 |
+
m = model.model[-1] # last layer
|
285 |
+
ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module
|
286 |
+
c = Classify(ch, nc) # Classify()
|
287 |
+
c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type
|
288 |
+
model.model[-1] = c # replace
|
289 |
+
self.model = model.model
|
290 |
+
self.stride = model.stride
|
291 |
+
self.save = []
|
292 |
+
self.nc = nc
|
293 |
+
|
294 |
+
def _from_yaml(self, cfg):
|
295 |
+
# Create a YOLOv5 classification model from a *.yaml file
|
296 |
+
self.model = None
|
297 |
+
|
298 |
+
|
299 |
+
def parse_model(d, ch): # model_dict, input_channels(3)
|
300 |
+
# Parse a YOLOv5 model.yaml dictionary
|
301 |
+
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
|
302 |
+
anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation')
|
303 |
+
if act:
|
304 |
+
Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
|
305 |
+
LOGGER.info(f"{colorstr('activation:')} {act}") # print
|
306 |
+
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
307 |
+
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
308 |
+
|
309 |
+
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
310 |
+
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
|
311 |
+
m = eval(m) if isinstance(m, str) else m # eval strings
|
312 |
+
for j, a in enumerate(args):
|
313 |
+
with contextlib.suppress(NameError):
|
314 |
+
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
315 |
+
|
316 |
+
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
|
317 |
+
if m in {
|
318 |
+
Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
|
319 |
+
BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:
|
320 |
+
c1, c2 = ch[f], args[0]
|
321 |
+
if c2 != no: # if not output
|
322 |
+
c2 = make_divisible(c2 * gw, 8)
|
323 |
+
|
324 |
+
args = [c1, c2, *args[1:]]
|
325 |
+
if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
|
326 |
+
args.insert(2, n) # number of repeats
|
327 |
+
n = 1
|
328 |
+
elif m is nn.BatchNorm2d:
|
329 |
+
args = [ch[f]]
|
330 |
+
elif m is Concat:
|
331 |
+
c2 = sum(ch[x] for x in f)
|
332 |
+
# TODO: channel, gw, gd
|
333 |
+
elif m in {Detect, Segment}:
|
334 |
+
args.append([ch[x] for x in f])
|
335 |
+
if isinstance(args[1], int): # number of anchors
|
336 |
+
args[1] = [list(range(args[1] * 2))] * len(f)
|
337 |
+
if m is Segment:
|
338 |
+
args[3] = make_divisible(args[3] * gw, 8)
|
339 |
+
elif m is Contract:
|
340 |
+
c2 = ch[f] * args[0] ** 2
|
341 |
+
elif m is Expand:
|
342 |
+
c2 = ch[f] // args[0] ** 2
|
343 |
+
else:
|
344 |
+
c2 = ch[f]
|
345 |
+
|
346 |
+
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
|
347 |
+
t = str(m)[8:-2].replace('__main__.', '') # module type
|
348 |
+
np = sum(x.numel() for x in m_.parameters()) # number params
|
349 |
+
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
350 |
+
LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
|
351 |
+
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
352 |
+
layers.append(m_)
|
353 |
+
if i == 0:
|
354 |
+
ch = []
|
355 |
+
ch.append(c2)
|
356 |
+
return nn.Sequential(*layers), sorted(save)
|
357 |
+
|
358 |
+
|
359 |
+
if __name__ == '__main__':
|
360 |
+
parser = argparse.ArgumentParser()
|
361 |
+
parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
|
362 |
+
parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
|
363 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
364 |
+
parser.add_argument('--profile', action='store_true', help='profile model speed')
|
365 |
+
parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
|
366 |
+
parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
|
367 |
+
opt = parser.parse_args()
|
368 |
+
opt.cfg = check_yaml(opt.cfg) # check YAML
|
369 |
+
print_args(vars(opt))
|
370 |
+
device = select_device(opt.device)
|
371 |
+
|
372 |
+
# Create model
|
373 |
+
im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
|
374 |
+
model = Model(opt.cfg).to(device)
|
375 |
+
|
376 |
+
# Options
|
377 |
+
if opt.line_profile: # profile layer by layer
|
378 |
+
model(im, profile=True)
|
379 |
+
|
380 |
+
elif opt.profile: # profile forward-backward
|
381 |
+
results = profile(input=im, ops=[model], n=3)
|
382 |
+
|
383 |
+
elif opt.test: # test all models
|
384 |
+
for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
|
385 |
+
try:
|
386 |
+
_ = Model(cfg)
|
387 |
+
except Exception as e:
|
388 |
+
print(f'Error in {cfg}: {e}')
|
389 |
+
|
390 |
+
else: # report fused model summary
|
391 |
+
model.fuse()
|
models/yolov5l.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 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], 1, Concat, [1]], # cat head P4
|
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 |
+
]
|
models/yolov5m.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: 0.67 # model depth multiple
|
6 |
+
width_multiple: 0.75 # 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 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], 1, Concat, [1]], # cat head P4
|
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 |
+
]
|
models/yolov5n.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: 0.33 # model depth multiple
|
6 |
+
width_multiple: 0.25 # 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 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], 1, Concat, [1]], # cat head P4
|
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 |
+
]
|