当前位置:   article > 正文

YOLOv10环境搭建、模型预测和ONNX推理_yolov10安装

yolov10安装

目录

1、开源代码、模型下载

2、环境配置

3、模型预测

4、onnxruntime测试


1、开源代码、模型下载

代码下载链接:https://github.com/THU-MIG/yolov10

模型下载:

YOLOv10-N:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10n.pt

YOLOv10-S:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10s.pt

YOLOv10-M:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10m.pt

YOLOv10-B:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10b.pt

YOLOv10-L:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10l.pt

YOLOv10-X:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10x.pt

2、环境配置

打开Anaconda3终端,进入base环境,创建新环境

  1. conda create -n yolov10 python=3.9
  2. conda activate yolov10
  3. #cd到yolov10的目录下
  4. pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
  5. pip install -e .

3、模型预测

安装完成之后,我们简单执行下推理命令测试下效果,默认读取yolov10-main/ultralytics/assets文件夹下的所有图像:

yolo predict model=yolov10s.pt

或者使用脚本

  1. from ultralytics import YOLOv10
  2. import glob
  3. import os
  4. import numpy as np
  5. import cv2
  6. classes = {
  7. 0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus',
  8. 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant',
  9. 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat',
  10. 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear',
  11. 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag',
  12. 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard',
  13. 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove',
  14. 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle',
  15. 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl',
  16. 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli',
  17. 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake',
  18. 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table',
  19. 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard',
  20. 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink',
  21. 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors',
  22. 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'
  23. }
  24. class Colors:
  25. """Ultralytics color palette https://ultralytics.com/."""
  26. def __init__(self):
  27. """Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values()."""
  28. hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
  29. '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
  30. self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
  31. # print(self.palette)
  32. self.n = len(self.palette)
  33. def __call__(self, i, bgr=False):
  34. """Converts hex color codes to rgb values."""
  35. c = self.palette[int(i) % self.n]
  36. return (c[2], c[1], c[0]) if bgr else c
  37. @staticmethod
  38. def hex2rgb(h): # rgb order (PIL)
  39. return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
  40. colors = Colors() # create instance for 'from utils.plots import colors'
  41. imgpath = r'D:\Yolov10\yolov10-main\yolov10-detect\test2'
  42. modelpath = r'D:\Yolov10\yolov10-main\yolov10-detect\yolov10s.pt'
  43. save_dir = imgpath + '_Rst'
  44. os.makedirs(save_dir,exist_ok=True)
  45. model = YOLOv10(modelpath)
  46. imgs = glob.glob(os.path.join(imgpath,'*.jpg'))
  47. for img in imgs:
  48. imgname = img.split('\\')[-1]
  49. frame = cv2.imread(img)
  50. results = model.predict(img)[0]
  51. # results = model(img)
  52. for box in results.boxes:
  53. # print(box)
  54. xyxy = box.xyxy.squeeze().tolist()
  55. x1, y1, x2, y2 = int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])
  56. c, conf = int(box.cls), float(box.conf)
  57. name = classes[c]
  58. color = colors(c, True)
  59. cv2.rectangle(frame, (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3])), color, thickness=2, lineType=cv2.LINE_AA)
  60. cv2.putText(frame, f"{name}: {conf:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, color,
  61. 2)
  62. # cv2.imshow('image', frame)
  63. # cv2.waitKey(0)
  64. cv2.imwrite(save_dir+'\\'+imgname,frame)

运行结果如下:

4、onnxruntime测试

(1)onnx模型转换

yolo export model=yolov10s.pt format=onnx opset=13 simplify

 运行后会在文件yolov10s.pt存放路径下生成一个的yolov10s.onnxONNX模型文件

可以通过这个网站Netron查看导出的节点信息:

(2)模型推理

通过 Ultralytics 框架测试下能否正常推理:

yolo predict model=yolov10s.onnx

或者使用推理脚本

  1. import glob
  2. import os
  3. import cv2
  4. import numpy as np
  5. import onnxruntime as ort
  6. classes = {
  7. 0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus',
  8. 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant',
  9. 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat',
  10. 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear',
  11. 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag',
  12. 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard',
  13. 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove',
  14. 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle',
  15. 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl',
  16. 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli',
  17. 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake',
  18. 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table',
  19. 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard',
  20. 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink',
  21. 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors',
  22. 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'
  23. }
  24. class Colors:
  25. """Ultralytics color palette https://ultralytics.com/."""
  26. def __init__(self):
  27. """Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values()."""
  28. hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
  29. '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
  30. self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
  31. # print(self.palette)
  32. self.n = len(self.palette)
  33. def __call__(self, i, bgr=False):
  34. """Converts hex color codes to rgb values."""
  35. c = self.palette[int(i) % self.n]
  36. return (c[2], c[1], c[0]) if bgr else c
  37. @staticmethod
  38. def hex2rgb(h): # rgb order (PIL)
  39. return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
  40. colors = Colors() # create instance for 'from utils.plots import colors'
  41. def letterbox(
  42. im,
  43. new_shape,
  44. color=(114, 114, 114),
  45. auto=False,
  46. scaleFill=False,
  47. scaleup=True,
  48. stride=32,
  49. ):
  50. """
  51. Resize and pad image while meeting stride-multiple constraints
  52. Returns:
  53. im (array): (height, width, 3)
  54. ratio (array): [w_ratio, h_ratio]
  55. (dw, dh) (array): [w_padding h_padding]
  56. """
  57. shape = im.shape[:2] # current shape [height, width]
  58. if isinstance(new_shape, int): # [h_rect, w_rect]
  59. new_shape = (new_shape, new_shape)
  60. # Scale ratio (new / old)
  61. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  62. if not scaleup: # only scale down, do not scale up (for better val mAP)
  63. r = min(r, 1.0)
  64. # Compute padding
  65. ratio = r, r # wh ratios
  66. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) # w h
  67. dw, dh = (
  68. new_shape[1] - new_unpad[0],
  69. new_shape[0] - new_unpad[1],
  70. ) # wh padding
  71. if auto: # minimum rectangle
  72. dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
  73. elif scaleFill: # stretch
  74. dw, dh = 0.0, 0.0
  75. new_unpad = (new_shape[1], new_shape[0]) # [w h]
  76. ratio = (
  77. new_shape[1] / shape[1],
  78. new_shape[0] / shape[0],
  79. ) # [w_ratio, h_ratio]
  80. dw /= 2 # divide padding into 2 sides
  81. dh /= 2
  82. if shape[::-1] != new_unpad: # resize
  83. im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
  84. top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
  85. left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
  86. im = cv2.copyMakeBorder(
  87. im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
  88. )
  89. return im, ratio, (dw, dh)
  90. def rescale_coords(boxes, image_shape, input_shape):
  91. image_height, image_width = image_shape
  92. input_height, input_width = input_shape
  93. scale = min(input_width / image_width, input_height / image_height)
  94. pad_w = (input_width - image_width * scale) / 2
  95. pad_h = (input_height - image_height * scale) / 2
  96. boxes[:, [0, 2]] = (boxes[:, [0, 2]] - pad_w) / scale
  97. boxes[:, [1, 3]] = (boxes[:, [1, 3]] - pad_h) / scale
  98. boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, image_width)
  99. boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, image_height)
  100. return boxes.astype(int)
  101. def preprocess(image, input_shape):
  102. # Resize
  103. input_img = letterbox(image, input_shape)[0]
  104. # Transpose
  105. input_img = input_img[..., ::-1].transpose(2, 0, 1)
  106. # Expand
  107. input_img = input_img[np.newaxis, :, :, :].astype(np.float32)
  108. # Contiguous
  109. input_img = np.ascontiguousarray(input_img)
  110. # Norm
  111. blob = input_img / 255.0
  112. return blob
  113. def postprocess(outs, conf_thres, image_shape, input_shape):
  114. # Filtered by conf
  115. outs = outs[outs[:, 4] >= conf_thres]
  116. # Extract
  117. boxes = outs[:, :4]
  118. scores = outs[:, -2]
  119. labels = outs[:, -1].astype(int)
  120. # Rescale
  121. boxes = rescale_coords(boxes, image_shape, input_shape)
  122. return boxes, scores, labels
  123. def main():
  124. conf_thres = 0.25
  125. input_shape = (640, 640)
  126. image_path = r'D:\Yolov10\yolov10-main\ultralytics\assets'
  127. save_path = image_path + '_Rst'
  128. os.makedirs(save_path,exist_ok=True)
  129. model_path = r'D:\Yolov10\yolov10-main\yolov10-detect\yolov10s.onnx'
  130. ort_model = ort.InferenceSession(model_path)
  131. imgs = glob.glob(os.path.join(image_path,'*.jpg'))
  132. imgs.sort()
  133. for img in imgs:
  134. imgname = img.split('\\')[-1]
  135. # Preprocess
  136. im0 = cv2.imread(img)
  137. image_shape = im0.shape[:2]
  138. blob = preprocess(im0, input_shape)
  139. # Inference
  140. outs = ort_model.run(None, {'images': blob})[0][0]
  141. # Postprocess
  142. boxes, scores, labels = postprocess(outs, conf_thres, image_shape, input_shape)
  143. # 保存结果
  144. for label, score, box in zip(labels, scores, boxes):
  145. label_text = f'{classes[label]}: {score:.2f}'
  146. color = colors(label,True)
  147. cv2.rectangle(im0, (box[0], box[1]), (box[2], box[3]), color, thickness=2, lineType=cv2.LINE_AA)
  148. cv2.putText(im0, label_text, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
  149. # cv2.imshow('image', im0)
  150. # cv2.waitKey(0)
  151. cv2.imwrite(save_path+'\\'+imgname, im0)
  152. if __name__ == '__main__':
  153. main()

参考:YOLOv10 正式发布!原理、部署、应用一站式齐全-CSDN博客

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

闽ICP备14008679号