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
  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. from pathlib import Path
  10. import cv2
  11. import numpy as np
  12. import torch
  13. import torch.backends.cudnn as cudnn
  14. FILE = Path(__file__).resolve()
  15. sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
  16. from models.experimental import attempt_load
  17. from utils.datasets import LoadStreams, LoadImages
  18. from utils.general import check_img_size, check_imshow, check_requirements, check_suffix, colorstr, is_ascii, \
  19. non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, \
  20. save_one_box
  21. from utils.plots import Annotator, colors
  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. ):
  49. save_img = not nosave and not source.endswith('.txt') # save inference images
  50. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  51. ('rtsp://', 'rtmp://', 'http://', 'https://'))
  52. # Directories
  53. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  54. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  55. # Initialize
  56. set_logging()
  57. device = select_device(device)
  58. half &= device.type != 'cpu' # half precision only supported on CUDA
  59. # Load model
  60. w = weights[0] if isinstance(weights, list) else weights
  61. classify, suffix, suffixes = False, Path(w).suffix.lower(), ['.pt', '.onnx', '.tflite', '.pb', '']
  62. check_suffix(w, suffixes) # check weights have acceptable suffix
  63. pt, onnx, tflite, pb, saved_model = (suffix == x for x in suffixes) # backend booleans
  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. int8 = input_details[0]['dtype'] == np.uint8 # is TFLite quantized uint8 model
  97. imgsz = check_img_size(imgsz, s=stride) # check image size
  98. ascii = is_ascii(names) # names are ascii (use PIL for UTF-8)
  99. # Dataloader
  100. if webcam:
  101. view_img = check_imshow()
  102. cudnn.benchmark = True # set True to speed up constant image size inference
  103. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  104. bs = len(dataset) # batch_size
  105. else:
  106. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
  107. bs = 1 # batch_size
  108. vid_path, vid_writer = [None] * bs, [None] * bs
  109. # Run inference
  110. if pt and device.type != 'cpu':
  111. model(torch.zeros(1, 3, *imgsz).to(device).type_as(next(model.parameters()))) # run once
  112. dt, seen = [0.0, 0.0, 0.0], 0
  113. for path, img, im0s, vid_cap in dataset:
  114. t1 = time_sync()
  115. if onnx:
  116. img = img.astype('float32')
  117. else:
  118. img = torch.from_numpy(img).to(device)
  119. img = img.half() if half else img.float() # uint8 to fp16/32
  120. img = img / 255.0 # 0 - 255 to 0.0 - 1.0
  121. if len(img.shape) == 3:
  122. img = img[None] # expand for batch dim
  123. t2 = time_sync()
  124. dt[0] += t2 - t1
  125. # Inference
  126. if pt:
  127. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  128. pred = model(img, augment=augment, visualize=visualize)[0]
  129. elif onnx:
  130. pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
  131. else: # tensorflow model (tflite, pb, saved_model)
  132. imn = img.permute(0, 2, 3, 1).cpu().numpy() # image in numpy
  133. if pb:
  134. pred = frozen_func(x=tf.constant(imn)).numpy()
  135. elif saved_model:
  136. pred = model(imn, training=False).numpy()
  137. elif tflite:
  138. if int8:
  139. scale, zero_point = input_details[0]['quantization']
  140. imn = (imn / scale + zero_point).astype(np.uint8) # de-scale
  141. interpreter.set_tensor(input_details[0]['index'], imn)
  142. interpreter.invoke()
  143. pred = interpreter.get_tensor(output_details[0]['index'])
  144. if int8:
  145. scale, zero_point = output_details[0]['quantization']
  146. pred = (pred.astype(np.float32) - zero_point) * scale # re-scale
  147. pred[..., 0] *= imgsz[1] # x
  148. pred[..., 1] *= imgsz[0] # y
  149. pred[..., 2] *= imgsz[1] # w
  150. pred[..., 3] *= imgsz[0] # h
  151. pred = torch.tensor(pred)
  152. t3 = time_sync()
  153. dt[1] += t3 - t2
  154. # NMS
  155. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  156. dt[2] += time_sync() - t3
  157. # Second-stage classifier (optional)
  158. if classify:
  159. pred = apply_classifier(pred, modelc, img, im0s)
  160. # Process predictions
  161. for i, det in enumerate(pred): # per image
  162. seen += 1
  163. if webcam: # batch_size >= 1
  164. p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
  165. else:
  166. p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
  167. p = Path(p) # to Path
  168. save_path = str(save_dir / p.name) # img.jpg
  169. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  170. s += '%gx%g ' % img.shape[2:] # print string
  171. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  172. imc = im0.copy() if save_crop else im0 # for save_crop
  173. annotator = Annotator(im0, line_width=line_thickness, pil=not ascii)
  174. if len(det):
  175. # Rescale boxes from img_size to im0 size
  176. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  177. # Print results
  178. for c in det[:, -1].unique():
  179. n = (det[:, -1] == c).sum() # detections per class
  180. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  181. # Write results
  182. for *xyxy, conf, cls in reversed(det):
  183. if save_txt: # Write to file
  184. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  185. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  186. with open(txt_path + '.txt', 'a') as f:
  187. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  188. if save_img or save_crop or view_img: # Add bbox to image
  189. c = int(cls) # integer class
  190. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  191. annotator.box_label(xyxy, label, color=colors(c, True))
  192. if save_crop:
  193. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  194. # Print time (inference-only)
  195. print(f'{s}Done. ({t3 - t2:.3f}s)')
  196. # Stream results
  197. im0 = annotator.result()
  198. if view_img:
  199. cv2.imshow(str(p), im0)
  200. cv2.waitKey(1) # 1 millisecond
  201. # Save results (image with detections)
  202. if save_img:
  203. if dataset.mode == 'image':
  204. cv2.imwrite(save_path, im0)
  205. else: # 'video' or 'stream'
  206. if vid_path[i] != save_path: # new video
  207. vid_path[i] = save_path
  208. if isinstance(vid_writer[i], cv2.VideoWriter):
  209. vid_writer[i].release() # release previous video writer
  210. if vid_cap: # video
  211. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  212. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  213. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  214. else: # stream
  215. fps, w, h = 30, im0.shape[1], im0.shape[0]
  216. save_path += '.mp4'
  217. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  218. vid_writer[i].write(im0)
  219. # Print results
  220. t = tuple(x / seen * 1E3 for x in dt) # speeds per image
  221. print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
  222. if save_txt or save_img:
  223. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  224. print(f"Results saved to {colorstr('bold', save_dir)}{s}")
  225. if update:
  226. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  227. def parse_opt():
  228. parser = argparse.ArgumentParser()
  229. parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model path(s)')
  230. parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
  231. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  232. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  233. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  234. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  235. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  236. parser.add_argument('--view-img', action='store_true', help='show results')
  237. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  238. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  239. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  240. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  241. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  242. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  243. parser.add_argument('--augment', action='store_true', help='augmented inference')
  244. parser.add_argument('--visualize', action='store_true', help='visualize features')
  245. parser.add_argument('--update', action='store_true', help='update all models')
  246. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  247. parser.add_argument('--name', default='exp', help='save results to project/name')
  248. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  249. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  250. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  251. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  252. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  253. opt = parser.parse_args()
  254. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  255. return opt
  256. def main(opt):
  257. print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  258. check_requirements(exclude=('tensorboard', 'thop'))
  259. run(**vars(opt))
  260. if __name__ == "__main__":
  261. opt = parse_opt()
  262. main(opt)
Tip!

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

Comments

Loading...