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.

4 年之前
4 年之前
4 年之前
precommit: yapf (#5494) * precommit: yapf * align isort * fix # Conflicts: # utils/plots.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update setup.cfg * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update setup.cfg * Update setup.cfg * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update wandb_utils.py * Update augmentations.py * Update setup.cfg * Update yolo.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update val.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * simplify colorstr * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * val run fix * export.py last comma * Update export.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update hubconf.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * PyTorch Hub tuple fix * PyTorch Hub tuple fix2 * PyTorch Hub tuple fix3 * Update setup Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
2 年之前
Add EdgeTPU support (#3630) * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * Put representative dataset in tfl_int8 block * detect.py TF inference * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * detect.py TF inference * Put representative dataset in tfl_int8 block * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * implement C3() and SiLU() * Add TensorFlow and TFLite Detection * Add --tfl-detect for TFLite Detection * Add int8 quantized TFLite inference in detect.py * Add --edgetpu for Edge TPU detection * Fix --img-size to add rectangle TensorFlow and TFLite input * Add --no-tf-nms to detect objects using models combined with TensorFlow NMS * Fix --img-size list type input * Update README.md * Add Android project for TFLite inference * Upgrade TensorFlow v2.3.1 -> v2.4.0 * Disable normalization of xywh * Rewrite names init in detect.py * Change input resolution 640 -> 320 on Android * Disable NNAPI * Update README.me --img 640 -> 320 * Update README.me for Edge TPU * Update README.md * Fix reshape dim to support dynamic batching * Fix reshape dim to support dynamic batching * Add epsilon argument in tf_BN, which is different between TF and PT * Set stride to None if not using PyTorch, and do not warmup without PyTorch * Add list support in check_img_size() * Add list input support in detect.py * sys.path.append('./') to run from yolov5/ * Add int8 quantization support for TensorFlow 2.5 * Add get_coco128.sh * Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU) * Update requirements.txt * Replace torch.load() with attempt_load() * Update requirements.txt * Add --tf-raw-resize to set half_pixel_centers=False * Remove android directory * Update README.md * Update README.md * Add multiple OS support for EdgeTPU detection * Fix export and detect * Export 3 YOLO heads with Edge TPU models * Remove xywh denormalization with Edge TPU models in detect.py * Fix saved_model and pb detect error * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix pre-commit.ci failure * Add edgetpu in export.py docstring * Fix Edge TPU model detection exported by TF 2.7 * Add class names for TF/TFLite in DetectMultibackend * Fix assignment with nl in TFLite Detection * Add check when getting Edge TPU compiler version * Add UTF-8 encoding in opening --data file for Windows * Remove redundant TensorFlow import * Add Edge TPU in export.py's docstring * Add the detect layer in Edge TPU model conversion * Default `dnn=False` * Cleanup data.yaml loading * Update detect.py * Update val.py * Comments and generalize data.yaml names Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: unknown <fangjiacong@ut.cn> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2 年之前
precommit: yapf (#5494) * precommit: yapf * align isort * fix # Conflicts: # utils/plots.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update setup.cfg * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update setup.cfg * Update setup.cfg * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update wandb_utils.py * Update augmentations.py * Update setup.cfg * Update yolo.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update val.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * simplify colorstr * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * val run fix * export.py last comma * Update export.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update hubconf.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * PyTorch Hub tuple fix * PyTorch Hub tuple fix2 * PyTorch Hub tuple fix3 * Update setup Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
2 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
4 年之前
Add EdgeTPU support (#3630) * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * Put representative dataset in tfl_int8 block * detect.py TF inference * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * detect.py TF inference * Put representative dataset in tfl_int8 block * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * implement C3() and SiLU() * Add TensorFlow and TFLite Detection * Add --tfl-detect for TFLite Detection * Add int8 quantized TFLite inference in detect.py * Add --edgetpu for Edge TPU detection * Fix --img-size to add rectangle TensorFlow and TFLite input * Add --no-tf-nms to detect objects using models combined with TensorFlow NMS * Fix --img-size list type input * Update README.md * Add Android project for TFLite inference * Upgrade TensorFlow v2.3.1 -> v2.4.0 * Disable normalization of xywh * Rewrite names init in detect.py * Change input resolution 640 -> 320 on Android * Disable NNAPI * Update README.me --img 640 -> 320 * Update README.me for Edge TPU * Update README.md * Fix reshape dim to support dynamic batching * Fix reshape dim to support dynamic batching * Add epsilon argument in tf_BN, which is different between TF and PT * Set stride to None if not using PyTorch, and do not warmup without PyTorch * Add list support in check_img_size() * Add list input support in detect.py * sys.path.append('./') to run from yolov5/ * Add int8 quantization support for TensorFlow 2.5 * Add get_coco128.sh * Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU) * Update requirements.txt * Replace torch.load() with attempt_load() * Update requirements.txt * Add --tf-raw-resize to set half_pixel_centers=False * Remove android directory * Update README.md * Update README.md * Add multiple OS support for EdgeTPU detection * Fix export and detect * Export 3 YOLO heads with Edge TPU models * Remove xywh denormalization with Edge TPU models in detect.py * Fix saved_model and pb detect error * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix pre-commit.ci failure * Add edgetpu in export.py docstring * Fix Edge TPU model detection exported by TF 2.7 * Add class names for TF/TFLite in DetectMultibackend * Fix assignment with nl in TFLite Detection * Add check when getting Edge TPU compiler version * Add UTF-8 encoding in opening --data file for Windows * Remove redundant TensorFlow import * Add Edge TPU in export.py's docstring * Add the detect layer in Edge TPU model conversion * Default `dnn=False` * Cleanup data.yaml loading * Update detect.py * Update val.py * Comments and generalize data.yaml names Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: unknown <fangjiacong@ut.cn> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2 年之前
Add TensorFlow and TFLite export (#1127) * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * Put representative dataset in tfl_int8 block * detect.py TF inference * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * detect.py TF inference * Put representative dataset in tfl_int8 block * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * implement C3() and SiLU() * Fix reshape dim to support dynamic batching * Add epsilon argument in tf_BN, which is different between TF and PT * Set stride to None if not using PyTorch, and do not warmup without PyTorch * Add list support in check_img_size() * Add list input support in detect.py * sys.path.append('./') to run from yolov5/ * Add int8 quantization support for TensorFlow 2.5 * Add get_coco128.sh * Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU) * Update requirements.txt * Replace torch.load() with attempt_load() * Update requirements.txt * Add --tf-raw-resize to set half_pixel_centers=False * Add --agnostic-nms for TF class-agnostic NMS * Cleanup after merge * Cleanup2 after merge * Cleanup3 after merge * Add tf.py docstring with credit and usage * pb saved_model and tflite use only one model in detect.py * Add use cases in docstring of tf.py * Remove redundant `stride` definition * Remove keras direct import * Fix `check_requirements(('tensorflow>=2.4.1',))` Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
3 年之前
4 年之前
4 年之前
4 年之前
Add TensorFlow and TFLite export (#1127) * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * Put representative dataset in tfl_int8 block * detect.py TF inference * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * Add models/tf.py for TensorFlow and TFLite export * Set auto=False for int8 calibration * Update requirements.txt for TensorFlow and TFLite export * Read anchors directly from PyTorch weights * Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export * Remove check_anchor_order, check_file, set_logging from import * Reformat code and optimize imports * Autodownload model and check cfg * update --source path, img-size to 320, single output * Adjust representative_dataset * detect.py TF inference * Put representative dataset in tfl_int8 block * weights to string * weights to string * cleanup tf.py * Add --dynamic-batch-size * Add xywh normalization to reduce calibration error * Update requirements.txt TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error * Fix imports Move C3 from models.experimental to models.common * implement C3() and SiLU() * Fix reshape dim to support dynamic batching * Add epsilon argument in tf_BN, which is different between TF and PT * Set stride to None if not using PyTorch, and do not warmup without PyTorch * Add list support in check_img_size() * Add list input support in detect.py * sys.path.append('./') to run from yolov5/ * Add int8 quantization support for TensorFlow 2.5 * Add get_coco128.sh * Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU) * Update requirements.txt * Replace torch.load() with attempt_load() * Update requirements.txt * Add --tf-raw-resize to set half_pixel_centers=False * Add --agnostic-nms for TF class-agnostic NMS * Cleanup after merge * Cleanup2 after merge * Cleanup3 after merge * Add tf.py docstring with credit and usage * pb saved_model and tflite use only one model in detect.py * Add use cases in docstring of tf.py * Remove redundant `stride` definition * Remove keras direct import * Fix `check_requirements(('tensorflow>=2.4.1',))` Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
3 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Run inference on images, videos, directories, streams, etc.
  4. Usage - sources:
  5. $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
  6. img.jpg # image
  7. vid.mp4 # video
  8. path/ # directory
  9. path/*.jpg # glob
  10. 'https://youtu.be/Zgi9g1ksQHc' # YouTube
  11. 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
  12. Usage - formats:
  13. $ python path/to/detect.py --weights yolov5s.pt # PyTorch
  14. yolov5s.torchscript # TorchScript
  15. yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
  16. yolov5s.xml # OpenVINO
  17. yolov5s.engine # TensorRT
  18. yolov5s.mlmodel # CoreML (MacOS-only)
  19. yolov5s_saved_model # TensorFlow SavedModel
  20. yolov5s.pb # TensorFlow GraphDef
  21. yolov5s.tflite # TensorFlow Lite
  22. yolov5s_edgetpu.tflite # TensorFlow Edge TPU
  23. """
  24. import argparse
  25. import os
  26. import sys
  27. from pathlib import Path
  28. import torch
  29. import torch.backends.cudnn as cudnn
  30. FILE = Path(__file__).resolve()
  31. ROOT = FILE.parents[0] # YOLOv5 root directory
  32. if str(ROOT) not in sys.path:
  33. sys.path.append(str(ROOT)) # add ROOT to PATH
  34. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  35. from models.common import DetectMultiBackend
  36. from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
  37. from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
  38. increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
  39. from utils.plots import Annotator, colors, save_one_box
  40. from utils.torch_utils import select_device, time_sync
  41. @torch.no_grad()
  42. def run(
  43. weights=ROOT / 'yolov5s.pt', # model.pt path(s)
  44. source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
  45. data=ROOT / 'data/coco128.yaml', # dataset.yaml path
  46. imgsz=(640, 640), # inference size (height, width)
  47. conf_thres=0.25, # confidence threshold
  48. iou_thres=0.45, # NMS IOU threshold
  49. max_det=1000, # maximum detections per image
  50. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  51. view_img=False, # show results
  52. save_txt=False, # save results to *.txt
  53. save_conf=False, # save confidences in --save-txt labels
  54. save_crop=False, # save cropped prediction boxes
  55. nosave=False, # do not save images/videos
  56. classes=None, # filter by class: --class 0, or --class 0 2 3
  57. agnostic_nms=False, # class-agnostic NMS
  58. augment=False, # augmented inference
  59. visualize=False, # visualize features
  60. update=False, # update all models
  61. project=ROOT / 'runs/detect', # save results to project/name
  62. name='exp', # save results to project/name
  63. exist_ok=False, # existing project/name ok, do not increment
  64. line_thickness=3, # bounding box thickness (pixels)
  65. hide_labels=False, # hide labels
  66. hide_conf=False, # hide confidences
  67. half=False, # use FP16 half-precision inference
  68. dnn=False, # use OpenCV DNN for ONNX inference
  69. ):
  70. source = str(source)
  71. save_img = not nosave and not source.endswith('.txt') # save inference images
  72. is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  73. is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
  74. webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
  75. if is_url and is_file:
  76. source = check_file(source) # download
  77. # Directories
  78. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  79. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  80. # Load model
  81. device = select_device(device)
  82. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
  83. stride, names, pt = model.stride, model.names, model.pt
  84. imgsz = check_img_size(imgsz, s=stride) # check image size
  85. # Dataloader
  86. if webcam:
  87. view_img = check_imshow()
  88. cudnn.benchmark = True # set True to speed up constant image size inference
  89. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  90. bs = len(dataset) # batch_size
  91. else:
  92. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
  93. bs = 1 # batch_size
  94. vid_path, vid_writer = [None] * bs, [None] * bs
  95. # Run inference
  96. model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
  97. dt, seen = [0.0, 0.0, 0.0], 0
  98. for path, im, im0s, vid_cap, s in dataset:
  99. t1 = time_sync()
  100. im = torch.from_numpy(im).to(device)
  101. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  102. im /= 255 # 0 - 255 to 0.0 - 1.0
  103. if len(im.shape) == 3:
  104. im = im[None] # expand for batch dim
  105. t2 = time_sync()
  106. dt[0] += t2 - t1
  107. # Inference
  108. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  109. pred = model(im, augment=augment, visualize=visualize)
  110. t3 = time_sync()
  111. dt[1] += t3 - t2
  112. # NMS
  113. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  114. dt[2] += time_sync() - t3
  115. # Second-stage classifier (optional)
  116. # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  117. # Process predictions
  118. for i, det in enumerate(pred): # per image
  119. seen += 1
  120. if webcam: # batch_size >= 1
  121. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  122. s += f'{i}: '
  123. else:
  124. p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
  125. p = Path(p) # to Path
  126. save_path = str(save_dir / p.name) # im.jpg
  127. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
  128. s += '%gx%g ' % im.shape[2:] # print string
  129. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  130. imc = im0.copy() if save_crop else im0 # for save_crop
  131. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  132. if len(det):
  133. # Rescale boxes from img_size to im0 size
  134. det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
  135. # Print results
  136. for c in det[:, -1].unique():
  137. n = (det[:, -1] == c).sum() # detections per class
  138. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  139. # Write results
  140. for *xyxy, conf, cls in reversed(det):
  141. if save_txt: # Write to file
  142. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  143. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  144. with open(txt_path + '.txt', 'a') as f:
  145. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  146. if save_img or save_crop or view_img: # Add bbox to image
  147. c = int(cls) # integer class
  148. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  149. annotator.box_label(xyxy, label, color=colors(c, True))
  150. if save_crop:
  151. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  152. # Stream results
  153. im0 = annotator.result()
  154. if view_img:
  155. cv2.imshow(str(p), im0)
  156. cv2.waitKey(1) # 1 millisecond
  157. # Save results (image with detections)
  158. if save_img:
  159. if dataset.mode == 'image':
  160. cv2.imwrite(save_path, im0)
  161. else: # 'video' or 'stream'
  162. if vid_path[i] != save_path: # new video
  163. vid_path[i] = save_path
  164. if isinstance(vid_writer[i], cv2.VideoWriter):
  165. vid_writer[i].release() # release previous video writer
  166. if vid_cap: # video
  167. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  168. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  169. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  170. else: # stream
  171. fps, w, h = 30, im0.shape[1], im0.shape[0]
  172. save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
  173. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  174. vid_writer[i].write(im0)
  175. # Print time (inference-only)
  176. LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
  177. # Print results
  178. t = tuple(x / seen * 1E3 for x in dt) # speeds per image
  179. LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
  180. if save_txt or save_img:
  181. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  182. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  183. if update:
  184. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  185. def parse_opt():
  186. parser = argparse.ArgumentParser()
  187. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
  188. parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
  189. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
  190. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  191. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  192. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  193. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  194. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  195. parser.add_argument('--view-img', action='store_true', help='show results')
  196. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  197. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  198. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  199. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  200. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
  201. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  202. parser.add_argument('--augment', action='store_true', help='augmented inference')
  203. parser.add_argument('--visualize', action='store_true', help='visualize features')
  204. parser.add_argument('--update', action='store_true', help='update all models')
  205. parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
  206. parser.add_argument('--name', default='exp', help='save results to project/name')
  207. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  208. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  209. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  210. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  211. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  212. parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
  213. opt = parser.parse_args()
  214. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  215. print_args(vars(opt))
  216. return opt
  217. def main(opt):
  218. check_requirements(exclude=('tensorboard', 'thop'))
  219. run(**vars(opt))
  220. if __name__ == "__main__":
  221. opt = parse_opt()
  222. main(opt)