当前位置:   article > 正文

Yolov5-v5.0 导出onnx推理结果完全错误_tracerwarning: converting a tensor to a python boo

tracerwarning: converting a tensor to a python boolean might cause the trace

楼主研究生在读,在搞模型部署方面的研究,记录一些遇到的问题。

最近使用yolov5-v5.0时,用官方提供的yolov5s.pt权重文件并利用export.py文件导出onnx模型时,虽然能够导出onnx模型但其onnx模型经实测输出是错误的,网上没搜到解决方案,所以楼主发文记录并提供自己的解决方式,有帮助欢迎点赞收藏。

首先在yolov5-v5.0运行官方export.py导出onnx如下:

python export.py --weights yolov5s.pt --img 640 --batch 1
  1. Starting ONNX export with onnx 1.13.1...
  2. F:\RV1126\yolov5-5.0\models\yolo.py:106: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  3. if augment:
  4. F:\RV1126\yolov5-5.0\models\yolo.py:131: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  5. if profile:
  6. F:\RV1126\yolov5-5.0\models\yolo.py:142: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  7. if profile:
  8. ONNX export success, saved as yolov5s.onnx

可以看到能够导出yolov5s.onnx的模型。

但推理时会出现一些IndexError问题,导致根本无法推理或者是能够推理但推理结果完全错误。本人使用的推理程序代码如下:

参考博客https://blog.csdn.net/qq128252/article/details/127105463

  1. import os
  2. import cv2
  3. import numpy as np
  4. import onnxruntime
  5. import time
  6. CLASSES=['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
  7. 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
  8. 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
  9. 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
  10. 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
  11. 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
  12. 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
  13. 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
  14. 'hair drier', 'toothbrush'] #coco80类别
  15. class YOLOV5():
  16. def __init__(self,onnxpath):
  17. self.onnx_session=onnxruntime.InferenceSession(onnxpath)
  18. self.input_name=self.get_input_name()
  19. self.output_name=self.get_output_name()
  20. #-------------------------------------------------------
  21. # 获取输入输出的名字
  22. #-------------------------------------------------------
  23. def get_input_name(self):
  24. input_name=[]
  25. for node in self.onnx_session.get_inputs():
  26. input_name.append(node.name)
  27. return input_name
  28. def get_output_name(self):
  29. output_name=[]
  30. for node in self.onnx_session.get_outputs():
  31. output_name.append(node.name)
  32. return output_name
  33. #-------------------------------------------------------
  34. # 输入图像
  35. #-------------------------------------------------------
  36. def get_input_feed(self,img_tensor):
  37. input_feed={}
  38. for name in self.input_name:
  39. input_feed[name]=img_tensor
  40. return input_feed
  41. #-------------------------------------------------------
  42. # 1.cv2读取图像并resize
  43. # 2.图像转BGR2RGB和HWC2CHW
  44. # 3.图像归一化
  45. # 4.图像增加维度
  46. # 5.onnx_session 推理
  47. #-------------------------------------------------------
  48. def inference(self,img_path):
  49. img=cv2.imread(img_path)
  50. or_img=cv2.resize(img,(640,640))
  51. img=or_img[:,:,::-1].transpose(2,0,1) #BGR2RGB和HWC2CHW
  52. img=img.astype(dtype=np.float32)
  53. img/=255.0
  54. img=np.expand_dims(img,axis=0)
  55. input_feed=self.get_input_feed(img)
  56. pred=self.onnx_session.run(None,input_feed)[0]
  57. return pred,or_img
  58. #dets: array [x,6] 6个值分别为x1,y1,x2,y2,score,class
  59. #thresh: 阈值
  60. def nms(dets, thresh):
  61. x1 = dets[:, 0]
  62. y1 = dets[:, 1]
  63. x2 = dets[:, 2]
  64. y2 = dets[:, 3]
  65. #-------------------------------------------------------
  66. # 计算框的面积
  67. # 置信度从大到小排序
  68. #-------------------------------------------------------
  69. areas = (y2 - y1 + 1) * (x2 - x1 + 1)
  70. scores = dets[:, 4]
  71. keep = []
  72. index = scores.argsort()[::-1]
  73. while index.size > 0:
  74. i = index[0]
  75. keep.append(i)
  76. #-------------------------------------------------------
  77. # 计算相交面积
  78. # 1.相交
  79. # 2.不相交
  80. #-------------------------------------------------------
  81. x11 = np.maximum(x1[i], x1[index[1:]])
  82. y11 = np.maximum(y1[i], y1[index[1:]])
  83. x22 = np.minimum(x2[i], x2[index[1:]])
  84. y22 = np.minimum(y2[i], y2[index[1:]])
  85. w = np.maximum(0, x22 - x11 + 1)
  86. h = np.maximum(0, y22 - y11 + 1)
  87. overlaps = w * h
  88. #-------------------------------------------------------
  89. # 计算该框与其它框的IOU,去除掉重复的框,即IOU值大的框
  90. # IOU小于thresh的框保留下来
  91. #-------------------------------------------------------
  92. ious = overlaps / (areas[i] + areas[index[1:]] - overlaps)
  93. idx = np.where(ious <= thresh)[0]
  94. index = index[idx + 1]
  95. return keep
  96. def xywh2xyxy(x):
  97. # [x, y, w, h] to [x1, y1, x2, y2]
  98. y = np.copy(x)
  99. y[:, 0] = x[:, 0] - x[:, 2] / 2
  100. y[:, 1] = x[:, 1] - x[:, 3] / 2
  101. y[:, 2] = x[:, 0] + x[:, 2] / 2
  102. y[:, 3] = x[:, 1] + x[:, 3] / 2
  103. return y
  104. def filter_box(org_box,conf_thres,iou_thres): #过滤掉无用的框
  105. #-------------------------------------------------------
  106. # 删除为1的维度
  107. # 删除置信度小于conf_thres的BOX
  108. #-------------------------------------------------------
  109. org_box=np.squeeze(org_box)
  110. conf = org_box[..., 4] > conf_thres
  111. box = org_box[conf == True]
  112. #-------------------------------------------------------
  113. # 通过argmax获取置信度最大的类别
  114. #-------------------------------------------------------
  115. cls_cinf = box[..., 5:]
  116. cls = []
  117. for i in range(len(cls_cinf)):
  118. cls.append(int(np.argmax(cls_cinf[i])))
  119. all_cls = list(set(cls))
  120. #-------------------------------------------------------
  121. # 分别对每个类别进行过滤
  122. # 1.将第6列元素替换为类别下标
  123. # 2.xywh2xyxy 坐标转换
  124. # 3.经过非极大抑制后输出的BOX下标
  125. # 4.利用下标取出非极大抑制后的BOX
  126. #-------------------------------------------------------
  127. output = []
  128. for i in range(len(all_cls)):
  129. curr_cls = all_cls[i]
  130. curr_cls_box = []
  131. curr_out_box = []
  132. for j in range(len(cls)):
  133. if cls[j] == curr_cls:
  134. box[j][5] = curr_cls
  135. curr_cls_box.append(box[j][:6])
  136. curr_cls_box = np.array(curr_cls_box)
  137. # curr_cls_box_old = np.copy(curr_cls_box)
  138. curr_cls_box = xywh2xyxy(curr_cls_box)
  139. curr_out_box = nms(curr_cls_box,iou_thres)
  140. for k in curr_out_box:
  141. output.append(curr_cls_box[k])
  142. output = np.array(output)
  143. return output
  144. def draw(image,box_data):
  145. #-------------------------------------------------------
  146. # 取整,方便画框
  147. #-------------------------------------------------------
  148. boxes=box_data[...,:4].astype(np.int32)
  149. scores=box_data[...,4]
  150. classes=box_data[...,5].astype(np.int32)
  151. for box, score, cl in zip(boxes, scores, classes):
  152. top, left, right, bottom = box
  153. print('class: {}, score: {}'.format(CLASSES[cl], score))
  154. print('box coordinate left,top,right,down: [{}, {}, {}, {}]'.format(top, left, right, bottom))
  155. cv2.rectangle(image, (top, left), (right, bottom), (255, 0, 0), 2)
  156. cv2.putText(image, '{0} {1:.2f}'.format(CLASSES[cl], score),
  157. (top, left ),
  158. cv2.FONT_HERSHEY_SIMPLEX,
  159. 0.6, (0, 0, 255), 2)
  160. if __name__=="__main__":
  161. onnx_path='yolov5s.onnx'
  162. model=YOLOV5(onnx_path)
  163. output,or_img=model.inference('bus.jpg')
  164. outbox=filter_box(output,0.5,0.5)
  165. draw(or_img,outbox)
  166. cv2.imwrite('onnx_run2.jpg',or_img)

推理程序经测试是没有问题的,但使用之前导出的onnx模型时报错,根本无法推理。所以必定是onnx模型本身的问题,运行时会报索引错误:

Traceback (most recent call last):
  File "f:/RV1126/yolov5-5.0/onnx_run2.py", line 181, in <module>
    draw(or_img,outbox)
  File "f:/RV1126/yolov5-5.0/onnx_run2.py", line 160, in draw
    scores=box_data[...,4]
IndexError: index 4 is out of bounds for axis 0 with size 0。

错误如下所示:

  1. (tf) PS F:\RV1126\yolov5-5.0> & D:/Anoconda3/envs/tf/python.exe f:/RV1126/yolov5-5.0/onnx_run2.py
  2. Traceback (most recent call last):
  3. File "f:/RV1126/yolov5-5.0/onnx_run2.py", line 181, in <module>
  4. draw(or_img,outbox)
  5. File "f:/RV1126/yolov5-5.0/onnx_run2.py", line 160, in draw
  6. scores=box_data[...,4]
  7. IndexError: index 4 is out of bounds for axis 0 with size 0

楼主先是尝试解决不能推理的问题,最终虽然使得模型能够推理,但结果也是完全错误的。如下:

可以看到模型疯狂输出图中不存在的目标,并且score明显错误,bed标签置信度居然超过了1。

最终解决方法换成yolov5-v6.0版用export.py文件导出onnx模型即可。如下可以看到成功运行,推理结果正确:

  1. (tf) PS F:\RV1126\yolov5-6.0> & D:/Anoconda3/envs/tf/python.exe f:/RV1126/yolov5-6.0/onnx_run2.py
  2. class: person, score: 0.8907531499862671
  3. box coordinate left,top,right,down: [535, 234, 639, 517]
  4. class: person, score: 0.8881538510322571
  5. box coordinate left,top,right,down: [175, 240, 273, 509]
  6. class: person, score: 0.8382899761199951
  7. box coordinate left,top,right,down: [44, 234, 180, 528]
  8. class: person, score: 0.6425769329071045
  9. box coordinate left,top,right,down: [0, 326, 72, 526]
  10. class: bus, score: 0.6496226787567139
  11. box coordinate left,top,right,down: [21, 121, 637, 443]

 推测是yolov5-v5.0版本和6.0版本onnx导出存在不兼容情况。对大家有帮助的话欢迎点赞收藏。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/850131
推荐阅读
相关标签
  

闽ICP备14008679号