基于Yolov7的路面病害检测代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

206 lines
8.9KB

  1. import argparse
  2. import sys
  3. import time
  4. import warnings
  5. sys.path.append('./') # to run '$ python *.py' files in subdirectories
  6. import torch
  7. import torch.nn as nn
  8. from torch.utils.mobile_optimizer import optimize_for_mobile
  9. import models
  10. from models.experimental import attempt_load, End2End
  11. from utils.activations import Hardswish, SiLU
  12. from utils.general import set_logging, check_img_size
  13. from utils.torch_utils import select_device
  14. from utils.add_nms import RegisterNMS
  15. if __name__ == '__main__':
  16. parser = argparse.ArgumentParser()
  17. parser.add_argument('--weights', type=str, default='./yolor-csp-c.pt', help='weights path')
  18. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
  19. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  20. parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes')
  21. parser.add_argument('--dynamic-batch', action='store_true', help='dynamic batch onnx for tensorrt and onnx-runtime')
  22. parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
  23. parser.add_argument('--end2end', action='store_true', help='export end2end onnx')
  24. parser.add_argument('--max-wh', type=int, default=None, help='None for tensorrt nms, int value for onnx-runtime nms')
  25. parser.add_argument('--topk-all', type=int, default=100, help='topk objects for every images')
  26. parser.add_argument('--iou-thres', type=float, default=0.45, help='iou threshold for NMS')
  27. parser.add_argument('--conf-thres', type=float, default=0.25, help='conf threshold for NMS')
  28. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  29. parser.add_argument('--simplify', action='store_true', help='simplify onnx model')
  30. parser.add_argument('--include-nms', action='store_true', help='export end2end onnx')
  31. parser.add_argument('--fp16', action='store_true', help='CoreML FP16 half-precision export')
  32. parser.add_argument('--int8', action='store_true', help='CoreML INT8 quantization')
  33. opt = parser.parse_args()
  34. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  35. opt.dynamic = opt.dynamic and not opt.end2end
  36. opt.dynamic = False if opt.dynamic_batch else opt.dynamic
  37. print(opt)
  38. set_logging()
  39. t = time.time()
  40. # Load PyTorch model
  41. device = select_device(opt.device)
  42. model = attempt_load(opt.weights, map_location=device) # load FP32 model
  43. labels = model.names
  44. # Checks
  45. gs = int(max(model.stride)) # grid size (max stride)
  46. opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
  47. # Input
  48. img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
  49. # Update model
  50. for k, m in model.named_modules():
  51. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  52. if isinstance(m, models.common.Conv): # assign export-friendly activations
  53. if isinstance(m.act, nn.Hardswish):
  54. m.act = Hardswish()
  55. elif isinstance(m.act, nn.SiLU):
  56. m.act = SiLU()
  57. # elif isinstance(m, models.yolo.Detect):
  58. # m.forward = m.forward_export # assign forward (optional)
  59. model.model[-1].export = not opt.grid # set Detect() layer grid export
  60. y = model(img) # dry run
  61. if opt.include_nms:
  62. model.model[-1].include_nms = True
  63. y = None
  64. # TorchScript export
  65. try:
  66. print('\nStarting TorchScript export with torch %s...' % torch.__version__)
  67. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  68. ts = torch.jit.trace(model, img, strict=False)
  69. ts.save(f)
  70. print('TorchScript export success, saved as %s' % f)
  71. except Exception as e:
  72. print('TorchScript export failure: %s' % e)
  73. # CoreML export
  74. try:
  75. import coremltools as ct
  76. print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
  77. # convert model from torchscript and apply pixel scaling as per detect.py
  78. ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
  79. bits, mode = (8, 'kmeans_lut') if opt.int8 else (16, 'linear') if opt.fp16 else (32, None)
  80. if bits < 32:
  81. if sys.platform.lower() == 'darwin': # quantization only supported on macOS
  82. with warnings.catch_warnings():
  83. warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
  84. ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
  85. else:
  86. print('quantization only supported on macOS, skipping...')
  87. f = opt.weights.replace('.pt', '.mlmodel') # filename
  88. ct_model.save(f)
  89. print('CoreML export success, saved as %s' % f)
  90. except Exception as e:
  91. print('CoreML export failure: %s' % e)
  92. # TorchScript-Lite export
  93. try:
  94. print('\nStarting TorchScript-Lite export with torch %s...' % torch.__version__)
  95. f = opt.weights.replace('.pt', '.torchscript.ptl') # filename
  96. tsl = torch.jit.trace(model, img, strict=False)
  97. tsl = optimize_for_mobile(tsl)
  98. tsl._save_for_lite_interpreter(f)
  99. print('TorchScript-Lite export success, saved as %s' % f)
  100. except Exception as e:
  101. print('TorchScript-Lite export failure: %s' % e)
  102. # ONNX export
  103. try:
  104. import onnx
  105. print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
  106. f = opt.weights.replace('.pt', '.onnx') # filename
  107. model.eval()
  108. output_names = ['classes', 'boxes'] if y is None else ['output']
  109. dynamic_axes = None
  110. if opt.dynamic:
  111. dynamic_axes = {'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
  112. 'output': {0: 'batch', 2: 'y', 3: 'x'}}
  113. if opt.dynamic_batch:
  114. opt.batch_size = 'batch'
  115. dynamic_axes = {
  116. 'images': {
  117. 0: 'batch',
  118. }, }
  119. if opt.end2end and opt.max_wh is None:
  120. output_axes = {
  121. 'num_dets': {0: 'batch'},
  122. 'det_boxes': {0: 'batch'},
  123. 'det_scores': {0: 'batch'},
  124. 'det_classes': {0: 'batch'},
  125. }
  126. else:
  127. output_axes = {
  128. 'output': {0: 'batch'},
  129. }
  130. dynamic_axes.update(output_axes)
  131. if opt.grid:
  132. if opt.end2end:
  133. print('\nStarting export end2end onnx model for %s...' % 'TensorRT' if opt.max_wh is None else 'onnxruntime')
  134. model = End2End(model,opt.topk_all,opt.iou_thres,opt.conf_thres,opt.max_wh,device,len(labels))
  135. if opt.end2end and opt.max_wh is None:
  136. output_names = ['num_dets', 'det_boxes', 'det_scores', 'det_classes']
  137. shapes = [opt.batch_size, 1, opt.batch_size, opt.topk_all, 4,
  138. opt.batch_size, opt.topk_all, opt.batch_size, opt.topk_all]
  139. else:
  140. output_names = ['output']
  141. else:
  142. model.model[-1].concat = True
  143. torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
  144. output_names=output_names,
  145. dynamic_axes=dynamic_axes)
  146. # Checks
  147. onnx_model = onnx.load(f) # load onnx model
  148. onnx.checker.check_model(onnx_model) # check onnx model
  149. if opt.end2end and opt.max_wh is None:
  150. for i in onnx_model.graph.output:
  151. for j in i.type.tensor_type.shape.dim:
  152. j.dim_param = str(shapes.pop(0))
  153. # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
  154. # # Metadata
  155. # d = {'stride': int(max(model.stride))}
  156. # for k, v in d.items():
  157. # meta = onnx_model.metadata_props.add()
  158. # meta.key, meta.value = k, str(v)
  159. # onnx.save(onnx_model, f)
  160. if opt.simplify:
  161. try:
  162. import onnxsim
  163. print('\nStarting to simplify ONNX...')
  164. onnx_model, check = onnxsim.simplify(onnx_model)
  165. assert check, 'assert check failed'
  166. except Exception as e:
  167. print(f'Simplifier failure: {e}')
  168. # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
  169. onnx.save(onnx_model,f)
  170. print('ONNX export success, saved as %s' % f)
  171. if opt.include_nms:
  172. print('Registering NMS plugin for ONNX...')
  173. mo = RegisterNMS(f)
  174. mo.register_nms()
  175. mo.save(f)
  176. except Exception as e:
  177. print('ONNX export failure: %s' % e)
  178. # Finish
  179. print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))