Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

detect.py 15 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...