predict.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. """
  3. Run YOLOv5 segmentation inference on images, videos, directories, streams, etc.
  4. Usage - sources:
  5. $ python segment/predict.py --weights yolov5s-seg.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 segment/predict.py --weights yolov5s-seg.pt # PyTorch
  17. yolov5s-seg.torchscript # TorchScript
  18. yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn
  19. yolov5s-seg_openvino_model # OpenVINO
  20. yolov5s-seg.engine # TensorRT
  21. yolov5s-seg.mlmodel # CoreML (macOS-only)
  22. yolov5s-seg_saved_model # TensorFlow SavedModel
  23. yolov5s-seg.pb # TensorFlow GraphDef
  24. yolov5s-seg.tflite # TensorFlow Lite
  25. yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU
  26. yolov5s-seg_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. FILE = Path(__file__).resolve()
  35. ROOT = FILE.parents[1] # YOLOv5 root directory
  36. if str(ROOT) not in sys.path:
  37. sys.path.append(str(ROOT)) # add ROOT to PATH
  38. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  39. from models.common import DetectMultiBackend
  40. from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
  41. from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
  42. increment_path, non_max_suppression, print_args, scale_boxes, scale_segments,
  43. strip_optimizer)
  44. from utils.plots import Annotator, colors, save_one_box
  45. from utils.segment.general import masks2segments, process_mask, process_mask_native
  46. from utils.torch_utils import select_device, smart_inference_mode
  47. @smart_inference_mode()
  48. def run(
  49. weights=ROOT / 'yolov5s-seg.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=(640, 640), # inference size (height, width)
  53. conf_thres=0.25, # confidence threshold
  54. iou_thres=0.45, # NMS IOU threshold
  55. max_det=1000, # maximum detections per image
  56. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  57. view_img=False, # show results
  58. save_txt=False, # save results to *.txt
  59. save_conf=False, # save confidences in --save-txt labels
  60. save_crop=False, # save cropped prediction boxes
  61. nosave=False, # do not save images/videos
  62. classes=None, # filter by class: --class 0, or --class 0 2 3
  63. agnostic_nms=False, # class-agnostic NMS
  64. augment=False, # augmented inference
  65. visualize=False, # visualize features
  66. update=False, # update all models
  67. project=ROOT / 'runs/predict-seg', # save results to project/name
  68. name='exp', # save results to project/name
  69. exist_ok=False, # existing project/name ok, do not increment
  70. line_thickness=3, # bounding box thickness (pixels)
  71. hide_labels=False, # hide labels
  72. hide_conf=False, # hide confidences
  73. half=False, # use FP16 half-precision inference
  74. dnn=False, # use OpenCV DNN for ONNX inference
  75. vid_stride=1, # video frame-rate stride
  76. retina_masks=False,
  77. ):
  78. source = str(source)
  79. save_img = not nosave and not source.endswith('.txt') # save inference images
  80. is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  81. is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
  82. webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
  83. screenshot = source.lower().startswith('screen')
  84. if is_url and is_file:
  85. source = check_file(source) # download
  86. # Directories
  87. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  88. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  89. # Load model
  90. device = select_device(device)
  91. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
  92. stride, names, pt = model.stride, model.names, model.pt
  93. imgsz = check_img_size(imgsz, s=stride) # check image size
  94. # Dataloader
  95. bs = 1 # batch_size
  96. if webcam:
  97. #view_img = check_imshow(warn=True)
  98. view_img = False
  99. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  100. bs = len(dataset)
  101. elif screenshot:
  102. dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
  103. else:
  104. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  105. vid_path, vid_writer = [None] * bs, [None] * bs
  106. # Run inference
  107. model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
  108. seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
  109. for path, im, im0s, vid_cap, s in dataset:
  110. with dt[0]:
  111. im = torch.from_numpy(im).to(model.device)
  112. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  113. im /= 255 # 0 - 255 to 0.0 - 1.0
  114. if len(im.shape) == 3:
  115. im = im[None] # expand for batch dim
  116. # Inference
  117. with dt[1]:
  118. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  119. pred, proto = model(im, augment=augment, visualize=visualize)[:2]
  120. # NMS
  121. with dt[2]:
  122. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det, nm=32)
  123. # Second-stage classifier (optional)
  124. # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  125. # Process predictions
  126. for i, det in enumerate(pred): # per image
  127. seen += 1
  128. if webcam: # batch_size >= 1
  129. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  130. s += f'{i}: '
  131. else:
  132. p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
  133. p = Path(p) # to Path
  134. save_path = str(save_dir / p.name) # im.jpg
  135. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
  136. s += '%gx%g ' % im.shape[2:] # print string
  137. imc = im0.copy() if save_crop else im0 # for save_crop
  138. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  139. if len(det):
  140. if retina_masks:
  141. # scale bbox first the crop masks
  142. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() # rescale boxes to im0 size
  143. masks = process_mask_native(proto[i], det[:, 6:], det[:, :4], im0.shape[:2]) # HWC
  144. else:
  145. masks = process_mask(proto[i], det[:, 6:], det[:, :4], im.shape[2:], upsample=True) # HWC
  146. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round() # rescale boxes to im0 size
  147. # Segments
  148. if save_txt:
  149. segments = [
  150. scale_segments(im0.shape if retina_masks else im.shape[2:], x, im0.shape, normalize=True)
  151. for x in reversed(masks2segments(masks))]
  152. # Print results
  153. for c in det[:, 5].unique():
  154. n = (det[:, 5] == c).sum() # detections per class
  155. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  156. # Mask plotting
  157. annotator.masks(
  158. masks,
  159. colors=[colors(x, True) for x in det[:, 5]],
  160. im_gpu=torch.as_tensor(im0, dtype=torch.float16).to(device).permute(2, 0, 1).flip(0).contiguous() /
  161. 255 if retina_masks else im[i])
  162. # Write results
  163. for j, (*xyxy, conf, cls) in enumerate(reversed(det[:, :6])):
  164. if save_txt: # Write to file
  165. seg = segments[j].reshape(-1) # (n,2) to (n*2)
  166. line = (cls, *seg, conf) if save_conf else (cls, *seg) # label format
  167. with open(f'{txt_path}.txt', 'a') as f:
  168. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  169. if save_img or save_crop or view_img: # Add bbox to image
  170. c = int(cls) # integer class
  171. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  172. annotator.box_label(xyxy, label, color=colors(c, True))
  173. # annotator.draw.polygon(segments[j], outline=colors(c, True), width=3)
  174. if save_crop:
  175. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  176. # Stream results
  177. im0 = annotator.result()
  178. if view_img:
  179. if platform.system() == 'Linux' and p not in windows:
  180. windows.append(p)
  181. cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  182. cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
  183. cv2.imshow(str(p), im0)
  184. if cv2.waitKey(1) == ord('q'): # 1 millisecond
  185. exit()
  186. # Save results (image with detections)
  187. if save_img:
  188. if dataset.mode == 'image':
  189. cv2.imwrite(save_path, im0)
  190. else: # 'video' or 'stream'
  191. if vid_path[i] != save_path: # new video
  192. vid_path[i] = save_path
  193. if isinstance(vid_writer[i], cv2.VideoWriter):
  194. vid_writer[i].release() # release previous video writer
  195. if vid_cap: # video
  196. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  197. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  198. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  199. else: # stream
  200. fps, w, h = 30, im0.shape[1], im0.shape[0]
  201. save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
  202. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  203. vid_writer[i].write(im0)
  204. # Print time (inference-only)
  205. LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
  206. # Print results
  207. t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
  208. LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
  209. if save_txt or save_img:
  210. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  211. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  212. if update:
  213. strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
  214. def parse_opt():
  215. parser = argparse.ArgumentParser()
  216. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-seg.pt', help='model path(s)')
  217. parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
  218. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
  219. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  220. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  221. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  222. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  223. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  224. parser.add_argument('--view-img', action='store_true', help='show results')
  225. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  226. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  227. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  228. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  229. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
  230. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  231. parser.add_argument('--augment', action='store_true', help='augmented inference')
  232. parser.add_argument('--visualize', action='store_true', help='visualize features')
  233. parser.add_argument('--update', action='store_true', help='update all models')
  234. parser.add_argument('--project', default=ROOT / 'runs/predict-seg', help='save results to project/name')
  235. parser.add_argument('--name', default='exp', help='save results to project/name')
  236. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  237. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  238. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  239. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  240. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  241. parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
  242. parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
  243. parser.add_argument('--retina-masks', action='store_true', help='whether to plot masks in native resolution')
  244. opt = parser.parse_args()
  245. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  246. print_args(vars(opt))
  247. return opt
  248. def main(opt):
  249. check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
  250. run(**vars(opt))
  251. if __name__ == '__main__':
  252. opt = parse_opt()
  253. main(opt)