Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

tf.py 20 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. TensorFlow, Keras and TFLite versions of YOLOv5
  4. Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127
  5. Usage:
  6. $ python models/tf.py --weights yolov5s.pt
  7. Export:
  8. $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs
  9. """
  10. import argparse
  11. import logging
  12. import sys
  13. from copy import deepcopy
  14. from pathlib import Path
  15. FILE = Path(__file__).resolve()
  16. ROOT = FILE.parents[1] # yolov5/ dir
  17. sys.path.append(ROOT.as_posix()) # add yolov5/ to path
  18. import numpy as np
  19. import tensorflow as tf
  20. import torch
  21. import torch.nn as nn
  22. from tensorflow import keras
  23. from models.common import Conv, Bottleneck, SPP, DWConv, Focus, BottleneckCSP, Concat, autopad, C3
  24. from models.experimental import MixConv2d, CrossConv, attempt_load
  25. from models.yolo import Detect
  26. from utils.general import colorstr, make_divisible, set_logging
  27. from utils.activations import SiLU
  28. LOGGER = logging.getLogger(__name__)
  29. class TFBN(keras.layers.Layer):
  30. # TensorFlow BatchNormalization wrapper
  31. def __init__(self, w=None):
  32. super(TFBN, self).__init__()
  33. self.bn = keras.layers.BatchNormalization(
  34. beta_initializer=keras.initializers.Constant(w.bias.numpy()),
  35. gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
  36. moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
  37. moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
  38. epsilon=w.eps)
  39. def call(self, inputs):
  40. return self.bn(inputs)
  41. class TFPad(keras.layers.Layer):
  42. def __init__(self, pad):
  43. super(TFPad, self).__init__()
  44. self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
  45. def call(self, inputs):
  46. return tf.pad(inputs, self.pad, mode='constant', constant_values=0)
  47. class TFConv(keras.layers.Layer):
  48. # Standard convolution
  49. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
  50. # ch_in, ch_out, weights, kernel, stride, padding, groups
  51. super(TFConv, self).__init__()
  52. assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
  53. assert isinstance(k, int), "Convolution with multiple kernels are not allowed."
  54. # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
  55. # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
  56. conv = keras.layers.Conv2D(
  57. c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False,
  58. kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()))
  59. self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
  60. self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
  61. # YOLOv5 activations
  62. if isinstance(w.act, nn.LeakyReLU):
  63. self.act = (lambda x: keras.activations.relu(x, alpha=0.1)) if act else tf.identity
  64. elif isinstance(w.act, nn.Hardswish):
  65. self.act = (lambda x: x * tf.nn.relu6(x + 3) * 0.166666667) if act else tf.identity
  66. elif isinstance(w.act, (nn.SiLU, SiLU)):
  67. self.act = (lambda x: keras.activations.swish(x)) if act else tf.identity
  68. else:
  69. raise Exception(f'no matching TensorFlow activation found for {w.act}')
  70. def call(self, inputs):
  71. return self.act(self.bn(self.conv(inputs)))
  72. class TFFocus(keras.layers.Layer):
  73. # Focus wh information into c-space
  74. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
  75. # ch_in, ch_out, kernel, stride, padding, groups
  76. super(TFFocus, self).__init__()
  77. self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
  78. def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
  79. # inputs = inputs / 255. # normalize 0-255 to 0-1
  80. return self.conv(tf.concat([inputs[:, ::2, ::2, :],
  81. inputs[:, 1::2, ::2, :],
  82. inputs[:, ::2, 1::2, :],
  83. inputs[:, 1::2, 1::2, :]], 3))
  84. class TFBottleneck(keras.layers.Layer):
  85. # Standard bottleneck
  86. def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion
  87. super(TFBottleneck, self).__init__()
  88. c_ = int(c2 * e) # hidden channels
  89. self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
  90. self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
  91. self.add = shortcut and c1 == c2
  92. def call(self, inputs):
  93. return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
  94. class TFConv2d(keras.layers.Layer):
  95. # Substitution for PyTorch nn.Conv2D
  96. def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
  97. super(TFConv2d, self).__init__()
  98. assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
  99. self.conv = keras.layers.Conv2D(
  100. c2, k, s, 'VALID', use_bias=bias,
  101. kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),
  102. bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None, )
  103. def call(self, inputs):
  104. return self.conv(inputs)
  105. class TFBottleneckCSP(keras.layers.Layer):
  106. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  107. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
  108. # ch_in, ch_out, number, shortcut, groups, expansion
  109. super(TFBottleneckCSP, self).__init__()
  110. c_ = int(c2 * e) # hidden channels
  111. self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
  112. self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
  113. self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
  114. self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
  115. self.bn = TFBN(w.bn)
  116. self.act = lambda x: keras.activations.relu(x, alpha=0.1)
  117. self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
  118. def call(self, inputs):
  119. y1 = self.cv3(self.m(self.cv1(inputs)))
  120. y2 = self.cv2(inputs)
  121. return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
  122. class TFC3(keras.layers.Layer):
  123. # CSP Bottleneck with 3 convolutions
  124. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
  125. # ch_in, ch_out, number, shortcut, groups, expansion
  126. super(TFC3, self).__init__()
  127. c_ = int(c2 * e) # hidden channels
  128. self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
  129. self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
  130. self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
  131. self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
  132. def call(self, inputs):
  133. return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
  134. class TFSPP(keras.layers.Layer):
  135. # Spatial pyramid pooling layer used in YOLOv3-SPP
  136. def __init__(self, c1, c2, k=(5, 9, 13), w=None):
  137. super(TFSPP, self).__init__()
  138. c_ = c1 // 2 # hidden channels
  139. self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
  140. self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
  141. self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]
  142. def call(self, inputs):
  143. x = self.cv1(inputs)
  144. return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
  145. class TFDetect(keras.layers.Layer):
  146. def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer
  147. super(TFDetect, self).__init__()
  148. self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
  149. self.nc = nc # number of classes
  150. self.no = nc + 5 # number of outputs per anchor
  151. self.nl = len(anchors) # number of detection layers
  152. self.na = len(anchors[0]) // 2 # number of anchors
  153. self.grid = [tf.zeros(1)] * self.nl # init grid
  154. self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
  155. self.anchor_grid = tf.reshape(tf.convert_to_tensor(w.anchor_grid.numpy(), dtype=tf.float32),
  156. [self.nl, 1, -1, 1, 2])
  157. self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
  158. self.training = False # set to False after building model
  159. self.imgsz = imgsz
  160. for i in range(self.nl):
  161. ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
  162. self.grid[i] = self._make_grid(nx, ny)
  163. def call(self, inputs):
  164. z = [] # inference output
  165. x = []
  166. for i in range(self.nl):
  167. x.append(self.m[i](inputs[i]))
  168. # x(bs,20,20,255) to x(bs,3,20,20,85)
  169. ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
  170. x[i] = tf.transpose(tf.reshape(x[i], [-1, ny * nx, self.na, self.no]), [0, 2, 1, 3])
  171. if not self.training: # inference
  172. y = tf.sigmoid(x[i])
  173. xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
  174. wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]
  175. # Normalize xywh to 0-1 to reduce calibration error
  176. xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
  177. wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
  178. y = tf.concat([xy, wh, y[..., 4:]], -1)
  179. z.append(tf.reshape(y, [-1, 3 * ny * nx, self.no]))
  180. return x if self.training else (tf.concat(z, 1), x)
  181. @staticmethod
  182. def _make_grid(nx=20, ny=20):
  183. # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  184. # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  185. xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
  186. return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
  187. class TFUpsample(keras.layers.Layer):
  188. def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'
  189. super(TFUpsample, self).__init__()
  190. assert scale_factor == 2, "scale_factor must be 2"
  191. self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode)
  192. # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
  193. # with default arguments: align_corners=False, half_pixel_centers=False
  194. # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
  195. # size=(x.shape[1] * 2, x.shape[2] * 2))
  196. def call(self, inputs):
  197. return self.upsample(inputs)
  198. class TFConcat(keras.layers.Layer):
  199. def __init__(self, dimension=1, w=None):
  200. super(TFConcat, self).__init__()
  201. assert dimension == 1, "convert only NCHW to NHWC concat"
  202. self.d = 3
  203. def call(self, inputs):
  204. return tf.concat(inputs, self.d)
  205. def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
  206. LOGGER.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
  207. anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
  208. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
  209. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
  210. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  211. for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
  212. m_str = m
  213. m = eval(m) if isinstance(m, str) else m # eval strings
  214. for j, a in enumerate(args):
  215. try:
  216. args[j] = eval(a) if isinstance(a, str) else a # eval strings
  217. except:
  218. pass
  219. n = max(round(n * gd), 1) if n > 1 else n # depth gain
  220. if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:
  221. c1, c2 = ch[f], args[0]
  222. c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
  223. args = [c1, c2, *args[1:]]
  224. if m in [BottleneckCSP, C3]:
  225. args.insert(2, n)
  226. n = 1
  227. elif m is nn.BatchNorm2d:
  228. args = [ch[f]]
  229. elif m is Concat:
  230. c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])
  231. elif m is Detect:
  232. args.append([ch[x + 1] for x in f])
  233. if isinstance(args[1], int): # number of anchors
  234. args[1] = [list(range(args[1] * 2))] * len(f)
  235. args.append(imgsz)
  236. else:
  237. c2 = ch[f]
  238. tf_m = eval('TF' + m_str.replace('nn.', ''))
  239. m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \
  240. else tf_m(*args, w=model.model[i]) # module
  241. torch_m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
  242. t = str(m)[8:-2].replace('__main__.', '') # module type
  243. np = sum([x.numel() for x in torch_m_.parameters()]) # number params
  244. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
  245. LOGGER.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
  246. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  247. layers.append(m_)
  248. ch.append(c2)
  249. return keras.Sequential(layers), sorted(save)
  250. class TFModel:
  251. def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes
  252. super(TFModel, self).__init__()
  253. if isinstance(cfg, dict):
  254. self.yaml = cfg # model dict
  255. else: # is *.yaml
  256. import yaml # for torch hub
  257. self.yaml_file = Path(cfg).name
  258. with open(cfg) as f:
  259. self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
  260. # Define model
  261. if nc and nc != self.yaml['nc']:
  262. print('Overriding %s nc=%g with nc=%g' % (cfg, self.yaml['nc'], nc))
  263. self.yaml['nc'] = nc # override yaml value
  264. self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
  265. def predict(self, inputs, tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
  266. conf_thres=0.25):
  267. y = [] # outputs
  268. x = inputs
  269. for i, m in enumerate(self.model.layers):
  270. if m.f != -1: # if not from previous layer
  271. 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
  272. x = m(x) # run
  273. y.append(x if m.i in self.savelist else None) # save output
  274. # Add TensorFlow NMS
  275. if tf_nms:
  276. boxes = self._xywh2xyxy(x[0][..., :4])
  277. probs = x[0][:, :, 4:5]
  278. classes = x[0][:, :, 5:]
  279. scores = probs * classes
  280. if agnostic_nms:
  281. nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
  282. return nms, x[1]
  283. else:
  284. boxes = tf.expand_dims(boxes, 2)
  285. nms = tf.image.combined_non_max_suppression(
  286. boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False)
  287. return nms, x[1]
  288. return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]
  289. # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85)
  290. # xywh = x[..., :4] # x(6300,4) boxes
  291. # conf = x[..., 4:5] # x(6300,1) confidences
  292. # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
  293. # return tf.concat([conf, cls, xywh], 1)
  294. @staticmethod
  295. def _xywh2xyxy(xywh):
  296. # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
  297. x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
  298. return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
  299. class AgnosticNMS(keras.layers.Layer):
  300. # TF Agnostic NMS
  301. def call(self, input, topk_all, iou_thres, conf_thres):
  302. # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450
  303. return tf.map_fn(self._nms, input,
  304. fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
  305. name='agnostic_nms')
  306. @staticmethod
  307. def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
  308. boxes, classes, scores = x
  309. class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
  310. scores_inp = tf.reduce_max(scores, -1)
  311. selected_inds = tf.image.non_max_suppression(
  312. boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres)
  313. selected_boxes = tf.gather(boxes, selected_inds)
  314. padded_boxes = tf.pad(selected_boxes,
  315. paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
  316. mode="CONSTANT", constant_values=0.0)
  317. selected_scores = tf.gather(scores_inp, selected_inds)
  318. padded_scores = tf.pad(selected_scores,
  319. paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
  320. mode="CONSTANT", constant_values=-1.0)
  321. selected_classes = tf.gather(class_inds, selected_inds)
  322. padded_classes = tf.pad(selected_classes,
  323. paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
  324. mode="CONSTANT", constant_values=-1.0)
  325. valid_detections = tf.shape(selected_inds)[0]
  326. return padded_boxes, padded_scores, padded_classes, valid_detections
  327. def representative_dataset_gen(dataset, ncalib=100):
  328. # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
  329. for n, (path, img, im0s, vid_cap) in enumerate(dataset):
  330. input = np.transpose(img, [1, 2, 0])
  331. input = np.expand_dims(input, axis=0).astype(np.float32)
  332. input /= 255.0
  333. yield [input]
  334. if n >= ncalib:
  335. break
  336. def run(weights=ROOT / 'yolov5s.pt', # weights path
  337. imgsz=(640, 640), # inference size h,w
  338. batch_size=1, # batch size
  339. dynamic=False, # dynamic batch size
  340. ):
  341. # PyTorch model
  342. im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
  343. model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False)
  344. y = model(im) # inference
  345. model.info()
  346. # TensorFlow model
  347. im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
  348. tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
  349. y = tf_model.predict(im) # inference
  350. # Keras model
  351. im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
  352. keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
  353. keras_model.summary()
  354. def parse_opt():
  355. parser = argparse.ArgumentParser()
  356. parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
  357. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  358. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  359. parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')
  360. opt = parser.parse_args()
  361. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  362. return opt
  363. def main(opt):
  364. set_logging()
  365. print(colorstr('tf.py: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  366. run(**vars(opt))
  367. if __name__ == "__main__":
  368. opt = parse_opt()
  369. main(opt)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...