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

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

Comments

Loading...