您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

286 行
14KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Run inference on images, videos, directories, streams, etc.
  4. Usage:
  5. $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640
  6. """
  7. import argparse
  8. import sys
  9. import time
  10. from pathlib import Path
  11. import cv2
  12. import numpy as np
  13. import torch
  14. import torch.backends.cudnn as cudnn
  15. FILE = Path(__file__).absolute()
  16. sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
  17. from models.experimental import attempt_load
  18. from utils.datasets import LoadStreams, LoadImages
  19. from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \
  20. apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
  21. from utils.plots import colors, plot_one_box
  22. from utils.torch_utils import select_device, load_classifier, time_sync
  23. @torch.no_grad()
  24. def run(weights='yolov5s.pt', # model.pt path(s)
  25. source='data/images', # file/dir/URL/glob, 0 for webcam
  26. imgsz=640, # inference size (pixels)
  27. conf_thres=0.25, # confidence threshold
  28. iou_thres=0.45, # NMS IOU threshold
  29. max_det=1000, # maximum detections per image
  30. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  31. view_img=False, # show results
  32. save_txt=False, # save results to *.txt
  33. save_conf=False, # save confidences in --save-txt labels
  34. save_crop=False, # save cropped prediction boxes
  35. nosave=False, # do not save images/videos
  36. classes=None, # filter by class: --class 0, or --class 0 2 3
  37. agnostic_nms=False, # class-agnostic NMS
  38. augment=False, # augmented inference
  39. visualize=False, # visualize features
  40. update=False, # update all models
  41. project='runs/detect', # save results to project/name
  42. name='exp', # save results to project/name
  43. exist_ok=False, # existing project/name ok, do not increment
  44. line_thickness=3, # bounding box thickness (pixels)
  45. hide_labels=False, # hide labels
  46. hide_conf=False, # hide confidences
  47. half=False, # use FP16 half-precision inference
  48. tfl_int8=False, # INT8 quantized TFLite model
  49. ):
  50. save_img = not nosave and not source.endswith('.txt') # save inference images
  51. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  52. ('rtsp://', 'rtmp://', 'http://', 'https://'))
  53. # Directories
  54. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  55. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  56. # Initialize
  57. set_logging()
  58. device = select_device(device)
  59. half &= device.type != 'cpu' # half precision only supported on CUDA
  60. # Load model
  61. w = weights[0] if isinstance(weights, list) else weights
  62. classify, suffix = False, Path(w).suffix.lower()
  63. pt, onnx, tflite, pb, saved_model = (suffix == x for x in ['.pt', '.onnx', '.tflite', '.pb', '']) # backend
  64. stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults
  65. if pt:
  66. model = attempt_load(weights, map_location=device) # load FP32 model
  67. stride = int(model.stride.max()) # model stride
  68. names = model.module.names if hasattr(model, 'module') else model.names # get class names
  69. if half:
  70. model.half() # to FP16
  71. if classify: # second-stage classifier
  72. modelc = load_classifier(name='resnet50', n=2) # initialize
  73. modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
  74. elif onnx:
  75. check_requirements(('onnx', 'onnxruntime'))
  76. import onnxruntime
  77. session = onnxruntime.InferenceSession(w, None)
  78. else: # TensorFlow models
  79. check_requirements(('tensorflow>=2.4.1',))
  80. import tensorflow as tf
  81. if pb: # https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
  82. def wrap_frozen_graph(gd, inputs, outputs):
  83. x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped import
  84. return x.prune(tf.nest.map_structure(x.graph.as_graph_element, inputs),
  85. tf.nest.map_structure(x.graph.as_graph_element, outputs))
  86. graph_def = tf.Graph().as_graph_def()
  87. graph_def.ParseFromString(open(w, 'rb').read())
  88. frozen_func = wrap_frozen_graph(gd=graph_def, inputs="x:0", outputs="Identity:0")
  89. elif saved_model:
  90. model = tf.keras.models.load_model(w)
  91. elif tflite:
  92. interpreter = tf.lite.Interpreter(model_path=w) # load TFLite model
  93. interpreter.allocate_tensors() # allocate
  94. input_details = interpreter.get_input_details() # inputs
  95. output_details = interpreter.get_output_details() # outputs
  96. imgsz = check_img_size(imgsz, s=stride) # check image size
  97. # Dataloader
  98. if webcam:
  99. view_img = check_imshow()
  100. cudnn.benchmark = True # set True to speed up constant image size inference
  101. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  102. bs = len(dataset) # batch_size
  103. else:
  104. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
  105. bs = 1 # batch_size
  106. vid_path, vid_writer = [None] * bs, [None] * bs
  107. # Run inference
  108. if pt and device.type != 'cpu':
  109. model(torch.zeros(1, 3, *imgsz).to(device).type_as(next(model.parameters()))) # run once
  110. t0 = time.time()
  111. for path, img, im0s, vid_cap in dataset:
  112. if onnx:
  113. img = img.astype('float32')
  114. else:
  115. img = torch.from_numpy(img).to(device)
  116. img = img.half() if half else img.float() # uint8 to fp16/32
  117. img = img / 255.0 # 0 - 255 to 0.0 - 1.0
  118. if len(img.shape) == 3:
  119. img = img[None] # expand for batch dim
  120. # Inference
  121. t1 = time_sync()
  122. if pt:
  123. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  124. pred = model(img, augment=augment, visualize=visualize)[0]
  125. elif onnx:
  126. pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
  127. else: # tensorflow model (tflite, pb, saved_model)
  128. imn = img.permute(0, 2, 3, 1).cpu().numpy() # image in numpy
  129. if pb:
  130. pred = frozen_func(x=tf.constant(imn)).numpy()
  131. elif saved_model:
  132. pred = model(imn, training=False).numpy()
  133. elif tflite:
  134. if tfl_int8:
  135. scale, zero_point = input_details[0]['quantization']
  136. imn = (imn / scale + zero_point).astype(np.uint8)
  137. interpreter.set_tensor(input_details[0]['index'], imn)
  138. interpreter.invoke()
  139. pred = interpreter.get_tensor(output_details[0]['index'])
  140. if tfl_int8:
  141. scale, zero_point = output_details[0]['quantization']
  142. pred = (pred.astype(np.float32) - zero_point) * scale
  143. pred[..., 0] *= imgsz[1] # x
  144. pred[..., 1] *= imgsz[0] # y
  145. pred[..., 2] *= imgsz[1] # w
  146. pred[..., 3] *= imgsz[0] # h
  147. pred = torch.tensor(pred)
  148. # NMS
  149. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  150. t2 = time_sync()
  151. # Second-stage classifier (optional)
  152. if classify:
  153. pred = apply_classifier(pred, modelc, img, im0s)
  154. # Process predictions
  155. for i, det in enumerate(pred): # detections per image
  156. if webcam: # batch_size >= 1
  157. p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
  158. else:
  159. p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
  160. p = Path(p) # to Path
  161. save_path = str(save_dir / p.name) # img.jpg
  162. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  163. s += '%gx%g ' % img.shape[2:] # print string
  164. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  165. imc = im0.copy() if save_crop else im0 # for save_crop
  166. if len(det):
  167. # Rescale boxes from img_size to im0 size
  168. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  169. # Print results
  170. for c in det[:, -1].unique():
  171. n = (det[:, -1] == c).sum() # detections per class
  172. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  173. # Write results
  174. for *xyxy, conf, cls in reversed(det):
  175. if save_txt: # Write to file
  176. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  177. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  178. with open(txt_path + '.txt', 'a') as f:
  179. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  180. if save_img or save_crop or view_img: # Add bbox to image
  181. c = int(cls) # integer class
  182. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  183. im0 = plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_width=line_thickness)
  184. if save_crop:
  185. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  186. # Print time (inference + NMS)
  187. print(f'{s}Done. ({t2 - t1:.3f}s)')
  188. # Stream results
  189. if view_img:
  190. cv2.imshow(str(p), im0)
  191. cv2.waitKey(1) # 1 millisecond
  192. # Save results (image with detections)
  193. if save_img:
  194. if dataset.mode == 'image':
  195. cv2.imwrite(save_path, im0)
  196. else: # 'video' or 'stream'
  197. if vid_path[i] != save_path: # new video
  198. vid_path[i] = save_path
  199. if isinstance(vid_writer[i], cv2.VideoWriter):
  200. vid_writer[i].release() # release previous video writer
  201. if vid_cap: # video
  202. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  203. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  204. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  205. else: # stream
  206. fps, w, h = 30, im0.shape[1], im0.shape[0]
  207. save_path += '.mp4'
  208. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  209. vid_writer[i].write(im0)
  210. if save_txt or save_img:
  211. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  212. print(f"Results saved to {colorstr('bold', save_dir)}{s}")
  213. if update:
  214. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  215. print(f'Done. ({time.time() - t0:.3f}s)')
  216. def parse_opt():
  217. parser = argparse.ArgumentParser()
  218. parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
  219. parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
  220. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  221. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  222. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  223. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  224. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  225. parser.add_argument('--view-img', action='store_true', help='show results')
  226. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  227. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  228. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  229. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  230. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  231. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  232. parser.add_argument('--augment', action='store_true', help='augmented inference')
  233. parser.add_argument('--visualize', action='store_true', help='visualize features')
  234. parser.add_argument('--update', action='store_true', help='update all models')
  235. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  236. parser.add_argument('--name', default='exp', help='save results to project/name')
  237. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  238. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  239. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  240. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  241. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  242. parser.add_argument('--tfl-int8', action='store_true', help='INT8 quantized TFLite model')
  243. opt = parser.parse_args()
  244. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  245. return opt
  246. def main(opt):
  247. print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  248. check_requirements(exclude=('tensorboard', 'thop'))
  249. run(**vars(opt))
  250. if __name__ == "__main__":
  251. opt = parse_opt()
  252. main(opt)