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 11 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
  1. """Run inference with a YOLOv5 model on images, videos, directories, streams
  2. Usage:
  3. $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640
  4. """
  5. import argparse
  6. import sys
  7. import time
  8. from pathlib import Path
  9. import cv2
  10. import torch
  11. import torch.backends.cudnn as cudnn
  12. FILE = Path(__file__).absolute()
  13. sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
  14. from models.experimental import attempt_load
  15. from utils.datasets import LoadStreams, LoadImages
  16. from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \
  17. apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
  18. from utils.plots import colors, plot_one_box
  19. from utils.torch_utils import select_device, load_classifier, time_sync
  20. @torch.no_grad()
  21. def run(weights='yolov5s.pt', # model.pt path(s)
  22. source='data/images', # file/dir/URL/glob, 0 for webcam
  23. imgsz=640, # inference size (pixels)
  24. conf_thres=0.25, # confidence threshold
  25. iou_thres=0.45, # NMS IOU threshold
  26. max_det=1000, # maximum detections per image
  27. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  28. view_img=False, # show results
  29. save_txt=False, # save results to *.txt
  30. save_conf=False, # save confidences in --save-txt labels
  31. save_crop=False, # save cropped prediction boxes
  32. nosave=False, # do not save images/videos
  33. classes=None, # filter by class: --class 0, or --class 0 2 3
  34. agnostic_nms=False, # class-agnostic NMS
  35. augment=False, # augmented inference
  36. visualize=False, # visualize features
  37. update=False, # update all models
  38. project='runs/detect', # save results to project/name
  39. name='exp', # save results to project/name
  40. exist_ok=False, # existing project/name ok, do not increment
  41. line_thickness=3, # bounding box thickness (pixels)
  42. hide_labels=False, # hide labels
  43. hide_conf=False, # hide confidences
  44. half=False, # use FP16 half-precision inference
  45. ):
  46. save_img = not nosave and not source.endswith('.txt') # save inference images
  47. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  48. ('rtsp://', 'rtmp://', 'http://', 'https://'))
  49. # Directories
  50. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  51. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  52. # Initialize
  53. set_logging()
  54. device = select_device(device)
  55. half &= device.type != 'cpu' # half precision only supported on CUDA
  56. # Load model
  57. model = attempt_load(weights, map_location=device) # load FP32 model
  58. stride = int(model.stride.max()) # model stride
  59. imgsz = check_img_size(imgsz, s=stride) # check image size
  60. names = model.module.names if hasattr(model, 'module') else model.names # get class names
  61. if half:
  62. model.half() # to FP16
  63. # Second-stage classifier
  64. classify = False
  65. if classify:
  66. modelc = load_classifier(name='resnet50', n=2) # initialize
  67. modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
  68. # Dataloader
  69. if webcam:
  70. view_img = check_imshow()
  71. cudnn.benchmark = True # set True to speed up constant image size inference
  72. dataset = LoadStreams(source, img_size=imgsz, stride=stride)
  73. bs = len(dataset) # batch_size
  74. else:
  75. dataset = LoadImages(source, img_size=imgsz, stride=stride)
  76. bs = 1 # batch_size
  77. vid_path, vid_writer = [None] * bs, [None] * bs
  78. # Run inference
  79. if device.type != 'cpu':
  80. model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
  81. t0 = time.time()
  82. for path, img, im0s, vid_cap in dataset:
  83. img = torch.from_numpy(img).to(device)
  84. img = img.half() if half else img.float() # uint8 to fp16/32
  85. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  86. if img.ndimension() == 3:
  87. img = img.unsqueeze(0)
  88. # Inference
  89. t1 = time_sync()
  90. pred = model(img,
  91. augment=augment,
  92. visualize=increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False)[0]
  93. # Apply NMS
  94. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  95. t2 = time_sync()
  96. # Apply Classifier
  97. if classify:
  98. pred = apply_classifier(pred, modelc, img, im0s)
  99. # Process detections
  100. for i, det in enumerate(pred): # detections per image
  101. if webcam: # batch_size >= 1
  102. p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
  103. else:
  104. p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
  105. p = Path(p) # to Path
  106. save_path = str(save_dir / p.name) # img.jpg
  107. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  108. s += '%gx%g ' % img.shape[2:] # print string
  109. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  110. imc = im0.copy() if save_crop else im0 # for save_crop
  111. if len(det):
  112. # Rescale boxes from img_size to im0 size
  113. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  114. # Print results
  115. for c in det[:, -1].unique():
  116. n = (det[:, -1] == c).sum() # detections per class
  117. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  118. # Write results
  119. for *xyxy, conf, cls in reversed(det):
  120. if save_txt: # Write to file
  121. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  122. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  123. with open(txt_path + '.txt', 'a') as f:
  124. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  125. if save_img or save_crop or view_img: # Add bbox to image
  126. c = int(cls) # integer class
  127. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  128. plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness)
  129. if save_crop:
  130. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  131. # Print time (inference + NMS)
  132. print(f'{s}Done. ({t2 - t1:.3f}s)')
  133. # Stream results
  134. if view_img:
  135. cv2.imshow(str(p), im0)
  136. cv2.waitKey(1) # 1 millisecond
  137. # Save results (image with detections)
  138. if save_img:
  139. if dataset.mode == 'image':
  140. cv2.imwrite(save_path, im0)
  141. else: # 'video' or 'stream'
  142. if vid_path[i] != save_path: # new video
  143. vid_path[i] = save_path
  144. if isinstance(vid_writer[i], cv2.VideoWriter):
  145. vid_writer[i].release() # release previous video writer
  146. if vid_cap: # video
  147. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  148. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  149. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  150. else: # stream
  151. fps, w, h = 30, im0.shape[1], im0.shape[0]
  152. save_path += '.mp4'
  153. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  154. vid_writer[i].write(im0)
  155. if save_txt or save_img:
  156. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  157. print(f"Results saved to {save_dir}{s}")
  158. if update:
  159. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  160. print(f'Done. ({time.time() - t0:.3f}s)')
  161. def parse_opt():
  162. parser = argparse.ArgumentParser()
  163. parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
  164. parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
  165. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
  166. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  167. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  168. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  169. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  170. parser.add_argument('--view-img', action='store_true', help='show results')
  171. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  172. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  173. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  174. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  175. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  176. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  177. parser.add_argument('--augment', action='store_true', help='augmented inference')
  178. parser.add_argument('--visualize', action='store_true', help='visualize features')
  179. parser.add_argument('--update', action='store_true', help='update all models')
  180. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  181. parser.add_argument('--name', default='exp', help='save results to project/name')
  182. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  183. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  184. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  185. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  186. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  187. opt = parser.parse_args()
  188. return opt
  189. def main(opt):
  190. print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  191. check_requirements(exclude=('tensorboard', 'thop'))
  192. run(**vars(opt))
  193. if __name__ == "__main__":
  194. opt = parse_opt()
  195. main(opt)
Tip!

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

Comments

Loading...