当前位置:   article > 正文

yolov5-python调用精简源码_python yolo 源码

python yolo 源码
  1. import time
  2. import numpy as np
  3. import torch
  4. from models.common import DetectMultiBackend
  5. from utils.augmentations import letterbox
  6. from utils.general import (check_img_size, cv2,
  7. non_max_suppression, scale_coords)
  8. from utils.plots import Annotator, colors
  9. from utils.torch_utils import select_device
  10. class YOLOv5Detector:
  11. """ YOLOv5 object detection """
  12. def __init__(self, weights='yolov5s.pt', conf_thres=0.25, iou_thres=0.45, imgsz=640, data='data/coco128.yaml'):
  13. """ Initialization """
  14. self.conf_thres = conf_thres
  15. self.iou_thres = iou_thres
  16. self.device = select_device('0')
  17. self.model = DetectMultiBackend(weights, device=self.device, dnn=False, data=data, fp16=False)
  18. self.stride, self.names, self.pt = self.model.stride, self.model.names, self.model.pt
  19. self.imgsz = check_img_size(imgsz, s=self.stride) # check image size
  20. def image_preprocess(self, image):
  21. im0 = image.copy()
  22. im = letterbox(im0, self.imgsz, stride=32, auto=True)[0] # padded resize
  23. im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
  24. im = np.ascontiguousarray(im) # contiguous
  25. im = torch.from_numpy(im).to(self.device)
  26. im = im.half() if self.model.fp16 else im.float() # uint8 to fp16/32
  27. im /= 255 # 0 - 255 to 0.0 - 1.0
  28. if len(im.shape) == 3:
  29. im = im[None] # expand for batch dim
  30. # Dataloader
  31. return im
  32. def __call__(self, image, *args, **kwargs):
  33. im = self.image_preprocess(image)
  34. pred = self.model(im, augment=False, visualize=False)
  35. pred = non_max_suppression(pred,
  36. conf_thres=0.25,
  37. iou_thres=0.45,
  38. classes=None,
  39. agnostic=False,
  40. multi_label=False,
  41. labels=(),
  42. max_det=1000)
  43. for i, det in enumerate(pred): # per image
  44. annotator = Annotator(im0, example=str(self.names))
  45. if len(det):
  46. det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
  47. for *xyxy, conf, cls in reversed(det):
  48. label = f'{self.names[int(cls)]} {conf:.2f}'
  49. annotator.box_label(xyxy, label, color=colors(2, True))
  50. return im0
  51. yolov5_detector = YOLOv5Detector(weights='best.pt')
  52. img = r'C:\Users\Administrator\Desktop\000000011244.jpg'
  53. while True:
  54. im0 = cv2.imread(img)
  55. t0 = time.time()
  56. im0 = yolov5_detector(im0)
  57. print(f'Done. ({time.time() - t0:.3f}s)')
  58. # print(time.time() - t0)
  59. cv2.imshow("123456", im0)
  60. cv2.waitKey(1) # 1 millisecond

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

闽ICP备14008679号