nyonyong commited on
Commit
0e365d4
β€’
1 Parent(s): d9bba41

Directory fix

Browse files
Files changed (48) hide show
  1. TextDetection/models/__init__.py +0 -0
  2. TextDetection/models/__pycache__/__init__.cpython-310.pyc +0 -0
  3. TextDetection/models/__pycache__/__init__.cpython-39.pyc +0 -0
  4. TextDetection/models/__pycache__/common.cpython-310.pyc +0 -0
  5. TextDetection/models/__pycache__/common.cpython-39.pyc +0 -0
  6. TextDetection/models/__pycache__/experimental.cpython-310.pyc +0 -0
  7. TextDetection/models/__pycache__/experimental.cpython-39.pyc +0 -0
  8. TextDetection/models/__pycache__/yolo.cpython-310.pyc +0 -0
  9. TextDetection/models/__pycache__/yolo.cpython-39.pyc +0 -0
  10. TextDetection/models/common.py +871 -0
  11. TextDetection/models/experimental.py +111 -0
  12. TextDetection/models/hub/anchors.yaml +59 -0
  13. TextDetection/models/hub/yolov3-spp.yaml +51 -0
  14. TextDetection/models/hub/yolov3-tiny.yaml +41 -0
  15. TextDetection/models/hub/yolov3.yaml +51 -0
  16. TextDetection/models/hub/yolov5-bifpn.yaml +48 -0
  17. TextDetection/models/hub/yolov5-fpn.yaml +42 -0
  18. TextDetection/models/hub/yolov5-p2.yaml +54 -0
  19. TextDetection/models/hub/yolov5-p34.yaml +41 -0
  20. TextDetection/models/hub/yolov5-p6.yaml +56 -0
  21. TextDetection/models/hub/yolov5-p7.yaml +67 -0
  22. TextDetection/models/hub/yolov5-panet.yaml +48 -0
  23. TextDetection/models/hub/yolov5l6.yaml +60 -0
  24. TextDetection/models/hub/yolov5m6.yaml +60 -0
  25. TextDetection/models/hub/yolov5n6.yaml +60 -0
  26. TextDetection/models/hub/yolov5s-LeakyReLU.yaml +49 -0
  27. TextDetection/models/hub/yolov5s-ghost.yaml +48 -0
  28. TextDetection/models/hub/yolov5s-transformer.yaml +48 -0
  29. TextDetection/models/hub/yolov5s6.yaml +60 -0
  30. TextDetection/models/hub/yolov5x6.yaml +60 -0
  31. TextDetection/models/segment/yolov5l-seg.yaml +48 -0
  32. TextDetection/models/segment/yolov5m-seg.yaml +48 -0
  33. TextDetection/models/segment/yolov5n-seg.yaml +48 -0
  34. TextDetection/models/segment/yolov5s-seg.yaml +48 -0
  35. TextDetection/models/segment/yolov5x-seg.yaml +48 -0
  36. TextDetection/models/tf.py +608 -0
  37. TextDetection/models/yolo.py +391 -0
  38. TextDetection/models/yolov5l.yaml +48 -0
  39. TextDetection/models/yolov5m.yaml +48 -0
  40. TextDetection/models/yolov5n.yaml +48 -0
  41. TextDetection/models/yolov5s.yaml +48 -0
  42. TextDetection/models/yolov5x.yaml +48 -0
  43. app.py +5 -6
  44. directories.py +2 -2
  45. noteImg2.jpg +0 -0
  46. noteimg1.jpg +0 -0
  47. noteimg3.jpg +0 -0
  48. process.py +2 -2
TextDetection/models/__init__.py ADDED
File without changes
TextDetection/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
TextDetection/models/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (136 Bytes). View file
 
TextDetection/models/__pycache__/common.cpython-310.pyc ADDED
Binary file (37 kB). View file
 
TextDetection/models/__pycache__/common.cpython-39.pyc ADDED
Binary file (37.6 kB). View file
 
TextDetection/models/__pycache__/experimental.cpython-310.pyc ADDED
Binary file (4.89 kB). View file
 
TextDetection/models/__pycache__/experimental.cpython-39.pyc ADDED
Binary file (4.81 kB). View file
 
TextDetection/models/__pycache__/yolo.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
TextDetection/models/__pycache__/yolo.cpython-39.pyc ADDED
Binary file (16 kB). View file
 
TextDetection/models/common.py ADDED
@@ -0,0 +1,871 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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 PIL import Image
25
+ from torch.cuda import amp
26
+
27
+ from utils import TryExcept
28
+ from utils.dataloaders import exif_transpose, letterbox
29
+ from utils.general import (LOGGER, ROOT, Profile, check_requirements, check_suffix, check_version, colorstr,
30
+ increment_path, is_jupyter, make_divisible, non_max_suppression, scale_boxes, xywh2xyxy,
31
+ xyxy2xywh, yaml_load)
32
+ from utils.plots import Annotator, colors, save_one_box
33
+ from utils.torch_utils import copy_attr, smart_inference_mode
34
+
35
+
36
+ def autopad(k, p=None, d=1): # kernel, padding, dilation
37
+ # Pad to 'same' shape outputs
38
+ if d > 1:
39
+ k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
40
+ if p is None:
41
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
42
+ return p
43
+
44
+
45
+ class Conv(nn.Module):
46
+ # Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
47
+ default_act = nn.SiLU() # default activation
48
+
49
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
50
+ super().__init__()
51
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
52
+ self.bn = nn.BatchNorm2d(c2)
53
+ self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
54
+
55
+ def forward(self, x):
56
+ return self.act(self.bn(self.conv(x)))
57
+
58
+ def forward_fuse(self, x):
59
+ return self.act(self.conv(x))
60
+
61
+
62
+ class DWConv(Conv):
63
+ # Depth-wise convolution
64
+ def __init__(self, c1, c2, k=1, s=1, d=1, act=True): # ch_in, ch_out, kernel, stride, dilation, activation
65
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
66
+
67
+
68
+ class DWConvTranspose2d(nn.ConvTranspose2d):
69
+ # Depth-wise transpose convolution
70
+ def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
71
+ super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
72
+
73
+
74
+ class TransformerLayer(nn.Module):
75
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
76
+ def __init__(self, c, num_heads):
77
+ super().__init__()
78
+ self.q = nn.Linear(c, c, bias=False)
79
+ self.k = nn.Linear(c, c, bias=False)
80
+ self.v = nn.Linear(c, c, bias=False)
81
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
82
+ self.fc1 = nn.Linear(c, c, bias=False)
83
+ self.fc2 = nn.Linear(c, c, bias=False)
84
+
85
+ def forward(self, x):
86
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
87
+ x = self.fc2(self.fc1(x)) + x
88
+ return x
89
+
90
+
91
+ class TransformerBlock(nn.Module):
92
+ # Vision Transformer https://arxiv.org/abs/2010.11929
93
+ def __init__(self, c1, c2, num_heads, num_layers):
94
+ super().__init__()
95
+ self.conv = None
96
+ if c1 != c2:
97
+ self.conv = Conv(c1, c2)
98
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
99
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
100
+ self.c2 = c2
101
+
102
+ def forward(self, x):
103
+ if self.conv is not None:
104
+ x = self.conv(x)
105
+ b, _, w, h = x.shape
106
+ p = x.flatten(2).permute(2, 0, 1)
107
+ return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
108
+
109
+
110
+ class Bottleneck(nn.Module):
111
+ # Standard bottleneck
112
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
113
+ super().__init__()
114
+ c_ = int(c2 * e) # hidden channels
115
+ self.cv1 = Conv(c1, c_, 1, 1)
116
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
117
+ self.add = shortcut and c1 == c2
118
+
119
+ def forward(self, x):
120
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
121
+
122
+
123
+ class BottleneckCSP(nn.Module):
124
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
125
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
126
+ super().__init__()
127
+ c_ = int(c2 * e) # hidden channels
128
+ self.cv1 = Conv(c1, c_, 1, 1)
129
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
130
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
131
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
132
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
133
+ self.act = nn.SiLU()
134
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
135
+
136
+ def forward(self, x):
137
+ y1 = self.cv3(self.m(self.cv1(x)))
138
+ y2 = self.cv2(x)
139
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
140
+
141
+
142
+ class CrossConv(nn.Module):
143
+ # Cross Convolution Downsample
144
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
145
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
146
+ super().__init__()
147
+ c_ = int(c2 * e) # hidden channels
148
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
149
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
150
+ self.add = shortcut and c1 == c2
151
+
152
+ def forward(self, x):
153
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
154
+
155
+
156
+ class C3(nn.Module):
157
+ # CSP Bottleneck with 3 convolutions
158
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
159
+ super().__init__()
160
+ c_ = int(c2 * e) # hidden channels
161
+ self.cv1 = Conv(c1, c_, 1, 1)
162
+ self.cv2 = Conv(c1, c_, 1, 1)
163
+ self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
164
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
165
+
166
+ def forward(self, x):
167
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
168
+
169
+
170
+ class C3x(C3):
171
+ # C3 module with cross-convolutions
172
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
173
+ super().__init__(c1, c2, n, shortcut, g, e)
174
+ c_ = int(c2 * e)
175
+ self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
176
+
177
+
178
+ class C3TR(C3):
179
+ # C3 module with TransformerBlock()
180
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
181
+ super().__init__(c1, c2, n, shortcut, g, e)
182
+ c_ = int(c2 * e)
183
+ self.m = TransformerBlock(c_, c_, 4, n)
184
+
185
+
186
+ class C3SPP(C3):
187
+ # C3 module with SPP()
188
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
189
+ super().__init__(c1, c2, n, shortcut, g, e)
190
+ c_ = int(c2 * e)
191
+ self.m = SPP(c_, c_, k)
192
+
193
+
194
+ class C3Ghost(C3):
195
+ # C3 module with GhostBottleneck()
196
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
197
+ super().__init__(c1, c2, n, shortcut, g, e)
198
+ c_ = int(c2 * e) # hidden channels
199
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
200
+
201
+
202
+ class SPP(nn.Module):
203
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
204
+ def __init__(self, c1, c2, k=(5, 9, 13)):
205
+ super().__init__()
206
+ c_ = c1 // 2 # hidden channels
207
+ self.cv1 = Conv(c1, c_, 1, 1)
208
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
209
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
210
+
211
+ def forward(self, x):
212
+ x = self.cv1(x)
213
+ with warnings.catch_warnings():
214
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
215
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
216
+
217
+
218
+ class SPPF(nn.Module):
219
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
220
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
221
+ super().__init__()
222
+ c_ = c1 // 2 # hidden channels
223
+ self.cv1 = Conv(c1, c_, 1, 1)
224
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
225
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
226
+
227
+ def forward(self, x):
228
+ x = self.cv1(x)
229
+ with warnings.catch_warnings():
230
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
231
+ y1 = self.m(x)
232
+ y2 = self.m(y1)
233
+ return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
234
+
235
+
236
+ class Focus(nn.Module):
237
+ # Focus wh information into c-space
238
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
239
+ super().__init__()
240
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)
241
+ # self.contract = Contract(gain=2)
242
+
243
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
244
+ return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
245
+ # return self.conv(self.contract(x))
246
+
247
+
248
+ class GhostConv(nn.Module):
249
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
250
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
251
+ super().__init__()
252
+ c_ = c2 // 2 # hidden channels
253
+ self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
254
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
255
+
256
+ def forward(self, x):
257
+ y = self.cv1(x)
258
+ return torch.cat((y, self.cv2(y)), 1)
259
+
260
+
261
+ class GhostBottleneck(nn.Module):
262
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
263
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
264
+ super().__init__()
265
+ c_ = c2 // 2
266
+ self.conv = nn.Sequential(
267
+ GhostConv(c1, c_, 1, 1), # pw
268
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
269
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
270
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,
271
+ act=False)) if s == 2 else nn.Identity()
272
+
273
+ def forward(self, x):
274
+ return self.conv(x) + self.shortcut(x)
275
+
276
+
277
+ class Contract(nn.Module):
278
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
279
+ def __init__(self, gain=2):
280
+ super().__init__()
281
+ self.gain = gain
282
+
283
+ def forward(self, x):
284
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
285
+ s = self.gain
286
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
287
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
288
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
289
+
290
+
291
+ class Expand(nn.Module):
292
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
293
+ def __init__(self, gain=2):
294
+ super().__init__()
295
+ self.gain = gain
296
+
297
+ def forward(self, x):
298
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
299
+ s = self.gain
300
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
301
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
302
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
303
+
304
+
305
+ class Concat(nn.Module):
306
+ # Concatenate a list of tensors along dimension
307
+ def __init__(self, dimension=1):
308
+ super().__init__()
309
+ self.d = dimension
310
+
311
+ def forward(self, x):
312
+ return torch.cat(x, self.d)
313
+
314
+
315
+ class DetectMultiBackend(nn.Module):
316
+ # YOLOv5 MultiBackend class for python inference on various backends
317
+ def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):
318
+ # Usage:
319
+ # PyTorch: weights = *.pt
320
+ # TorchScript: *.torchscript
321
+ # ONNX Runtime: *.onnx
322
+ # ONNX OpenCV DNN: *.onnx --dnn
323
+ # OpenVINO: *_openvino_model
324
+ # CoreML: *.mlmodel
325
+ # TensorRT: *.engine
326
+ # TensorFlow SavedModel: *_saved_model
327
+ # TensorFlow GraphDef: *.pb
328
+ # TensorFlow Lite: *.tflite
329
+ # TensorFlow Edge TPU: *_edgetpu.tflite
330
+ # PaddlePaddle: *_paddle_model
331
+ from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
332
+
333
+ super().__init__()
334
+ w = str(weights[0] if isinstance(weights, list) else weights)
335
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)
336
+ fp16 &= pt or jit or onnx or engine or triton # FP16
337
+ nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)
338
+ stride = 32 # default stride
339
+ cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA
340
+ if not (pt or triton):
341
+ w = attempt_download(w) # download if not local
342
+
343
+ if pt: # PyTorch
344
+ model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
345
+ stride = max(int(model.stride.max()), 32) # model stride
346
+ names = model.module.names if hasattr(model, 'module') else model.names # get class names
347
+ model.half() if fp16 else model.float()
348
+ self.model = model # explicitly assign for to(), cpu(), cuda(), half()
349
+ elif jit: # TorchScript
350
+ LOGGER.info(f'Loading {w} for TorchScript inference...')
351
+ extra_files = {'config.txt': ''} # model metadata
352
+ model = torch.jit.load(w, _extra_files=extra_files, map_location=device)
353
+ model.half() if fp16 else model.float()
354
+ if extra_files['config.txt']: # load metadata dict
355
+ d = json.loads(extra_files['config.txt'],
356
+ object_hook=lambda d: {
357
+ 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.BILINEAR)
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)] # 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
+ if is_jupyter():
771
+ from IPython.display import display
772
+ display(im)
773
+ else:
774
+ im.show(self.files[i])
775
+ if save:
776
+ f = self.files[i]
777
+ im.save(save_dir / f) # save
778
+ if i == self.n - 1:
779
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
780
+ if render:
781
+ self.ims[i] = np.asarray(im)
782
+ if pprint:
783
+ s = s.lstrip('\n')
784
+ return f'{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t
785
+ if crop:
786
+ if save:
787
+ LOGGER.info(f'Saved results to {save_dir}\n')
788
+ return crops
789
+
790
+ @TryExcept('Showing images is not supported in this environment')
791
+ def show(self, labels=True):
792
+ self._run(show=True, labels=labels) # show results
793
+
794
+ def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):
795
+ save_dir = increment_path(save_dir, exist_ok, mkdir=True) # increment save_dir
796
+ self._run(save=True, labels=labels, save_dir=save_dir) # save results
797
+
798
+ def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):
799
+ save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
800
+ return self._run(crop=True, save=save, save_dir=save_dir) # crop results
801
+
802
+ def render(self, labels=True):
803
+ self._run(render=True, labels=labels) # render results
804
+ return self.ims
805
+
806
+ def pandas(self):
807
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
808
+ new = copy(self) # return copy
809
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
810
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
811
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
812
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
813
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
814
+ return new
815
+
816
+ def tolist(self):
817
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
818
+ r = range(self.n) # iterable
819
+ x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
820
+ # for d in x:
821
+ # for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
822
+ # setattr(d, k, getattr(d, k)[0]) # pop out of list
823
+ return x
824
+
825
+ def print(self):
826
+ LOGGER.info(self.__str__())
827
+
828
+ def __len__(self): # override len(results)
829
+ return self.n
830
+
831
+ def __str__(self): # override print(results)
832
+ return self._run(pprint=True) # print results
833
+
834
+ def __repr__(self):
835
+ return f'YOLOv5 {self.__class__} instance\n' + self.__str__()
836
+
837
+
838
+ class Proto(nn.Module):
839
+ # YOLOv5 mask Proto module for segmentation models
840
+ def __init__(self, c1, c_=256, c2=32): # ch_in, number of protos, number of masks
841
+ super().__init__()
842
+ self.cv1 = Conv(c1, c_, k=3)
843
+ self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
844
+ self.cv2 = Conv(c_, c_, k=3)
845
+ self.cv3 = Conv(c_, c2)
846
+
847
+ def forward(self, x):
848
+ return self.cv3(self.cv2(self.upsample(self.cv1(x))))
849
+
850
+
851
+ class Classify(nn.Module):
852
+ # YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2)
853
+ def __init__(self,
854
+ c1,
855
+ c2,
856
+ k=1,
857
+ s=1,
858
+ p=None,
859
+ g=1,
860
+ dropout_p=0.0): # ch_in, ch_out, kernel, stride, padding, groups, dropout probability
861
+ super().__init__()
862
+ c_ = 1280 # efficientnet_b0 size
863
+ self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
864
+ self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
865
+ self.drop = nn.Dropout(p=dropout_p, inplace=True)
866
+ self.linear = nn.Linear(c_, c2) # to x(b,c2)
867
+
868
+ def forward(self, x):
869
+ if isinstance(x, list):
870
+ x = torch.cat(x, 1)
871
+ return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
TextDetection/models/experimental.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
TextDetection/models/hub/anchors.yaml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
TextDetection/models/hub/yolov3-spp.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov3-tiny.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov3.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-bifpn.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-fpn.yaml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-p2.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-p34.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-p6.yaml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-p7.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5-panet.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5l6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5m6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5n6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5s-LeakyReLU.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5s-ghost.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5s-transformer.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5s6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/hub/yolov5x6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/segment/yolov5l-seg.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/segment/yolov5m-seg.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/segment/yolov5n-seg.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/segment/yolov5s-seg.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/segment/yolov5x-seg.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/tf.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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)
TextDetection/models/yolo.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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 * # noqa
25
+ from models.experimental import * # noqa
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()
TextDetection/models/yolov5l.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/yolov5m.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/yolov5n.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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
+ ]
TextDetection/models/yolov5s.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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, 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
+ ]
TextDetection/models/yolov5x.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 πŸš€ by Ultralytics, AGPL-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, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48
+ ]
app.py CHANGED
@@ -17,14 +17,13 @@ def HCR(im):
17
 
18
  title = "HCR"
19
  description = "[Postech X KITA] Elite Undergradute AI Strategy Program | AI Project Competition Team 2 OCR Part"
20
- article = "<p style='text-align: center'> Handwritten Text Character Recognition Task " \
21
- "Text Detection + Text Rearrangement + Text Recognition" \
22
- "For More Information" \
23
- "<a href='https://bandalcom.github.io/'>GitBlog</a> |" \
24
  "<a href='https://github.com/bandalcom/Postech+KITA_AI-Project'>Source code</a></p>"
25
 
26
  #<a href='https://github.com/bandalcom/Postech+KITA_AI-Project'>Source code</a>
27
  #examples = [['zidane.jpg'], ['bus.jpg']]
28
  #examples=examples,
29
- gr.Interface(fn=HCR, inputs="image", outputs = "text", title=title, description=description, article=article, analytics_enabled=False).launch(
30
- debug=True)
 
17
 
18
  title = "HCR"
19
  description = "[Postech X KITA] Elite Undergradute AI Strategy Program | AI Project Competition Team 2 OCR Part"
20
+ article = "<p style='text-align: center'> Handwritten Text Character Recognition Task \n" \
21
+ "Text Detection + Text Rearrangement + Text Recognition\n" \
22
+ "For More Information\n" \
23
+ "<a href='https://bandalcom.github.io/'>GitBlog</a> | " \
24
  "<a href='https://github.com/bandalcom/Postech+KITA_AI-Project'>Source code</a></p>"
25
 
26
  #<a href='https://github.com/bandalcom/Postech+KITA_AI-Project'>Source code</a>
27
  #examples = [['zidane.jpg'], ['bus.jpg']]
28
  #examples=examples,
29
+ gr.Interface(fn=HCR, inputs="image", outputs = "text", title=title, description=description, examples=["noteimg1.jpg", "noteimg2.jpg","noteimg3.jpg"], article=article, analytics_enabled=False).launch(debug=True)
 
directories.py CHANGED
@@ -1,4 +1,4 @@
1
- home_dir = "~"
2
  yolo_dir = "/TextDetection"
3
  input_img = "/TextDetection/cookie/user_input.jpg"
4
  detect_model_dir = "/runs/wordDetection/weights/best.pt"
@@ -8,4 +8,4 @@ folder_path = cropped_img_path + "/crops/word"
8
  DBSCAN_dir = "/TextRearrange"
9
  recog_dir = "/TextRecognition"
10
  recog_model_dir = "/TextRecognition/best_accuracy_s/best_accuracy_s.pth"
11
- txt_file_path = "log_demo_result.txt"
 
1
+ home_dir = "/home/user/app"
2
  yolo_dir = "/TextDetection"
3
  input_img = "/TextDetection/cookie/user_input.jpg"
4
  detect_model_dir = "/runs/wordDetection/weights/best.pt"
 
8
  DBSCAN_dir = "/TextRearrange"
9
  recog_dir = "/TextRecognition"
10
  recog_model_dir = "/TextRecognition/best_accuracy_s/best_accuracy_s.pth"
11
+ txt_file_path = "/home/user/app/TextRecognition/log_demo_result.txt"
noteImg2.jpg ADDED
noteimg1.jpg ADDED
noteimg3.jpg ADDED
process.py CHANGED
@@ -55,13 +55,13 @@ def textDetection(im):
55
 
56
  def textRearrange():
57
  ## subprocess.call('cd ' + Dir.DBSCAN_dir, shell=True)
58
- subprocess.call(['python', Dir.DBSCAN_dir+'/DBSCAN.py'])
59
 
60
  def textRecognition():
61
  #%cd /content/drive/MyDrive/KITA/Text/lmdb/deep-text-recognition-benchmark
62
  ## subprocess.call('cd '+Dir.recog_dir, shell=True)
63
  #!CUDA_VISIBLE_DEVICES=0 python3 demo.py --Transformation TPS --FeatureExtraction ResNet --SequenceModeling BiLSTM --Prediction Attn --image_folder /content/drive/MyDrive/KITA/Text/YOLO/runs/detect/youtube_data2/crops/word --saved_model /content/drive/MyDrive/KITA/Text/best_accuracy_s/best_accuracy_s.pth
64
- subprocess.call('CUDA_VISIBLE_DEVICES="" python3 '+ Dir.recog_dir +'/demo.py --Transformation TPS --FeatureExtraction ResNet --SequenceModeling BiLSTM --Prediction Attn --image_folder ' + Dir.yolo_dir + Dir.cropped_img_path + '/crops/word --saved_model '+ Dir.recog_model_dir, shell=True)
65
 
66
  def getHcrResult(file_path):#*#
67
  texts = ""
 
55
 
56
  def textRearrange():
57
  ## subprocess.call('cd ' + Dir.DBSCAN_dir, shell=True)
58
+ subprocess.call(['python', "/home/user/app"+Dir.DBSCAN_dir+'/DBSCAN.py'])
59
 
60
  def textRecognition():
61
  #%cd /content/drive/MyDrive/KITA/Text/lmdb/deep-text-recognition-benchmark
62
  ## subprocess.call('cd '+Dir.recog_dir, shell=True)
63
  #!CUDA_VISIBLE_DEVICES=0 python3 demo.py --Transformation TPS --FeatureExtraction ResNet --SequenceModeling BiLSTM --Prediction Attn --image_folder /content/drive/MyDrive/KITA/Text/YOLO/runs/detect/youtube_data2/crops/word --saved_model /content/drive/MyDrive/KITA/Text/best_accuracy_s/best_accuracy_s.pth
64
+ subprocess.call('CUDA_VISIBLE_DEVICES="" python3 '+ "/home/user/app"+ Dir.recog_dir +'/demo.py --Transformation TPS --FeatureExtraction ResNet --SequenceModeling BiLSTM --Prediction Attn --image_folder /home/user/app' + Dir.yolo_dir + Dir.cropped_img_path + '/crops/word --saved_model '+ Dir.recog_model_dir, shell=True)
65
 
66
  def getHcrResult(file_path):#*#
67
  texts = ""