predict.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. """
  3. Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
  4. Usage - sources:
  5. $ python classify/predict.py --weights yolov5s-cls.pt --source 0 # webcam
  6. img.jpg # image
  7. vid.mp4 # video
  8. screen # screenshot
  9. path/ # directory
  10. list.txt # list of images
  11. list.streams # list of streams
  12. 'path/*.jpg' # glob
  13. 'https://youtu.be/Zgi9g1ksQHc' # YouTube
  14. 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
  15. Usage - formats:
  16. $ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
  17. yolov5s-cls.torchscript # TorchScript
  18. yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
  19. yolov5s-cls_openvino_model # OpenVINO
  20. yolov5s-cls.engine # TensorRT
  21. yolov5s-cls.mlmodel # CoreML (macOS-only)
  22. yolov5s-cls_saved_model # TensorFlow SavedModel
  23. yolov5s-cls.pb # TensorFlow GraphDef
  24. yolov5s-cls.tflite # TensorFlow Lite
  25. yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
  26. yolov5s-cls_paddle_model # PaddlePaddle
  27. """
  28. import argparse
  29. import os
  30. import platform
  31. import sys
  32. from pathlib import Path
  33. import torch
  34. import torch.nn.functional as F
  35. FILE = Path(__file__).resolve()
  36. ROOT = FILE.parents[1] # YOLOv5 root directory
  37. if str(ROOT) not in sys.path:
  38. sys.path.append(str(ROOT)) # add ROOT to PATH
  39. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  40. from models.common import DetectMultiBackend
  41. from utils.augmentations import classify_transforms
  42. from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
  43. from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
  44. increment_path, print_args, strip_optimizer)
  45. from utils.plots import Annotator
  46. from utils.torch_utils import select_device, smart_inference_mode
  47. @smart_inference_mode()
  48. def run(
  49. weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
  50. source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)
  51. data=ROOT / 'data/coco128.yaml', # dataset.yaml path
  52. imgsz=(224, 224), # inference size (height, width)
  53. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  54. view_img=False, # show results
  55. save_txt=False, # save results to *.txt
  56. nosave=False, # do not save images/videos
  57. augment=False, # augmented inference
  58. visualize=False, # visualize features
  59. update=False, # update all models
  60. project=ROOT / 'runs/predict-cls', # save results to project/name
  61. name='exp', # save results to project/name
  62. exist_ok=False, # existing project/name ok, do not increment
  63. half=False, # use FP16 half-precision inference
  64. dnn=False, # use OpenCV DNN for ONNX inference
  65. vid_stride=1, # video frame-rate stride
  66. ):
  67. source = str(source)
  68. save_img = not nosave and not source.endswith('.txt') # save inference images
  69. is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  70. is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
  71. webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
  72. screenshot = source.lower().startswith('screen')
  73. if is_url and is_file:
  74. source = check_file(source) # download
  75. # Directories
  76. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  77. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  78. # Load model
  79. device = select_device(device)
  80. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
  81. stride, names, pt = model.stride, model.names, model.pt
  82. imgsz = check_img_size(imgsz, s=stride) # check image size
  83. # Dataloader
  84. bs = 1 # batch_size
  85. if webcam:
  86. view_img = check_imshow(warn=True)
  87. dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
  88. bs = len(dataset)
  89. elif screenshot:
  90. dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
  91. else:
  92. dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
  93. vid_path, vid_writer = [None] * bs, [None] * bs
  94. # Run inference
  95. model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
  96. seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
  97. for path, im, im0s, vid_cap, s in dataset:
  98. with dt[0]:
  99. im = torch.Tensor(im).to(model.device)
  100. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  101. if len(im.shape) == 3:
  102. im = im[None] # expand for batch dim
  103. # Inference
  104. with dt[1]:
  105. results = model(im)
  106. # Post-process
  107. with dt[2]:
  108. pred = F.softmax(results, dim=1) # probabilities
  109. # Process predictions
  110. for i, prob in enumerate(pred): # per image
  111. seen += 1
  112. if webcam: # batch_size >= 1
  113. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  114. s += f'{i}: '
  115. else:
  116. p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
  117. p = Path(p) # to Path
  118. save_path = str(save_dir / p.name) # im.jpg
  119. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
  120. s += '%gx%g ' % im.shape[2:] # print string
  121. annotator = Annotator(im0, example=str(names), pil=True)
  122. # Print results
  123. top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
  124. s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
  125. # Write results
  126. text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)
  127. if save_img or view_img: # Add bbox to image
  128. annotator.text((32, 32), text, txt_color=(255, 255, 255))
  129. if save_txt: # Write to file
  130. with open(f'{txt_path}.txt', 'a') as f:
  131. f.write(text + '\n')
  132. # Stream results
  133. im0 = annotator.result()
  134. if view_img:
  135. if platform.system() == 'Linux' and p not in windows:
  136. windows.append(p)
  137. cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  138. cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
  139. cv2.imshow(str(p), im0)
  140. cv2.waitKey(1) # 1 millisecond
  141. # Save results (image with detections)
  142. if save_img:
  143. if dataset.mode == 'image':
  144. cv2.imwrite(save_path, im0)
  145. else: # 'video' or 'stream'
  146. if vid_path[i] != save_path: # new video
  147. vid_path[i] = save_path
  148. if isinstance(vid_writer[i], cv2.VideoWriter):
  149. vid_writer[i].release() # release previous video writer
  150. if vid_cap: # video
  151. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  152. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  153. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  154. else: # stream
  155. fps, w, h = 30, im0.shape[1], im0.shape[0]
  156. save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
  157. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  158. vid_writer[i].write(im0)
  159. # Print time (inference-only)
  160. LOGGER.info(f'{s}{dt[1].dt * 1E3:.1f}ms')
  161. # Print results
  162. t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
  163. LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
  164. if save_txt or save_img:
  165. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  166. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  167. if update:
  168. strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
  169. def parse_opt():
  170. parser = argparse.ArgumentParser()
  171. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')
  172. parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
  173. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
  174. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')
  175. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  176. parser.add_argument('--view-img', action='store_true', help='show results')
  177. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  178. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  179. parser.add_argument('--augment', action='store_true', help='augmented inference')
  180. parser.add_argument('--visualize', action='store_true', help='visualize features')
  181. parser.add_argument('--update', action='store_true', help='update all models')
  182. parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')
  183. parser.add_argument('--name', default='exp', help='save results to project/name')
  184. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  185. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  186. parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
  187. parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
  188. opt = parser.parse_args()
  189. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  190. print_args(vars(opt))
  191. return opt
  192. def main(opt):
  193. check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
  194. run(**vars(opt))
  195. if __name__ == '__main__':
  196. opt = parse_opt()
  197. main(opt)