Ultrajonic commited on
Commit
11b029f
·
1 Parent(s): d57a286

Upload detect.py

Browse files
Files changed (1) hide show
  1. detect.py +252 -0
detect.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Run inference on images, videos, directories, streams, etc.
4
+
5
+ Usage - sources:
6
+ $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
7
+ img.jpg # image
8
+ vid.mp4 # video
9
+ path/ # directory
10
+ path/*.jpg # glob
11
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
12
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
13
+
14
+ Usage - formats:
15
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
16
+ yolov5s.torchscript # TorchScript
17
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
18
+ yolov5s.xml # OpenVINO
19
+ yolov5s.engine # TensorRT
20
+ yolov5s.mlmodel # CoreML (macOS-only)
21
+ yolov5s_saved_model # TensorFlow SavedModel
22
+ yolov5s.pb # TensorFlow GraphDef
23
+ yolov5s.tflite # TensorFlow Lite
24
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
25
+ """
26
+
27
+ import argparse
28
+ import os
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ import torch
33
+ import torch.backends.cudnn as cudnn
34
+
35
+ FILE = Path(__file__).resolve()
36
+ ROOT = FILE.parents[0] # YOLOv5 root directory
37
+ if str(ROOT) not in sys.path:
38
+ sys.path.append(str(ROOT)) # add ROOT to PATH
39
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
40
+
41
+ from models.common import DetectMultiBackend
42
+ from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
43
+ from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
44
+ increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
45
+ from utils.plots import Annotator, colors, save_one_box
46
+ from utils.torch_utils import select_device, time_sync
47
+
48
+
49
+ @torch.no_grad()
50
+ def run(
51
+ weights=ROOT / 'yolov5s.pt', # model.pt path(s)
52
+ source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
53
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
54
+ imgsz=(640, 640), # inference size (height, width)
55
+ conf_thres=0.25, # confidence threshold
56
+ iou_thres=0.45, # NMS IOU threshold
57
+ max_det=1000, # maximum detections per image
58
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
59
+ view_img=False, # show results
60
+ save_txt=False, # save results to *.txt
61
+ save_conf=False, # save confidences in --save-txt labels
62
+ save_crop=False, # save cropped prediction boxes
63
+ nosave=False, # do not save images/videos
64
+ classes=None, # filter by class: --class 0, or --class 0 2 3
65
+ agnostic_nms=False, # class-agnostic NMS
66
+ augment=False, # augmented inference
67
+ visualize=False, # visualize features
68
+ update=False, # update all models
69
+ project=ROOT / 'runs/detect', # save results to project/name
70
+ name='exp', # save results to project/name
71
+ exist_ok=False, # existing project/name ok, do not increment
72
+ line_thickness=3, # bounding box thickness (pixels)
73
+ hide_labels=False, # hide labels
74
+ hide_conf=False, # hide confidences
75
+ half=False, # use FP16 half-precision inference
76
+ dnn=False, # use OpenCV DNN for ONNX inference
77
+ ):
78
+ source = str(source)
79
+ save_img = not nosave and not source.endswith('.txt') # save inference images
80
+ is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
81
+ is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
82
+ webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
83
+ if is_url and is_file:
84
+ source = check_file(source) # download
85
+
86
+ # Directories
87
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
88
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
89
+
90
+ # Load model
91
+ device = select_device(device)
92
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
93
+ stride, names, pt = model.stride, model.names, model.pt
94
+ imgsz = check_img_size(imgsz, s=stride) # check image size
95
+
96
+ # Dataloader
97
+ if webcam:
98
+ view_img = check_imshow()
99
+ cudnn.benchmark = True # set True to speed up constant image size inference
100
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
101
+ bs = len(dataset) # batch_size
102
+ else:
103
+ dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
104
+ bs = 1 # batch_size
105
+ vid_path, vid_writer = [None] * bs, [None] * bs
106
+
107
+ # Run inference
108
+ model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
109
+ dt, seen = [0.0, 0.0, 0.0], 0
110
+ for path, im, im0s, vid_cap, s in dataset:
111
+ t1 = time_sync()
112
+ im = torch.from_numpy(im).to(device)
113
+ im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
114
+ im /= 255 # 0 - 255 to 0.0 - 1.0
115
+ if len(im.shape) == 3:
116
+ im = im[None] # expand for batch dim
117
+ t2 = time_sync()
118
+ dt[0] += t2 - t1
119
+
120
+ # Inference
121
+ visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
122
+ pred = model(im, augment=augment, visualize=visualize)
123
+ t3 = time_sync()
124
+ dt[1] += t3 - t2
125
+
126
+ # NMS
127
+ pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
128
+ dt[2] += time_sync() - t3
129
+
130
+ # Second-stage classifier (optional)
131
+ # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
132
+
133
+ # Process predictions
134
+ for i, det in enumerate(pred): # per image
135
+ seen += 1
136
+ if webcam: # batch_size >= 1
137
+ p, im0, frame = path[i], im0s[i].copy(), dataset.count
138
+ s += f'{i}: '
139
+ else:
140
+ p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
141
+
142
+ p = Path(p) # to Path
143
+ save_path = str(save_dir / p.name) # im.jpg
144
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
145
+ s += '%gx%g ' % im.shape[2:] # print string
146
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
147
+ imc = im0.copy() if save_crop else im0 # for save_crop
148
+ annotator = Annotator(im0, line_width=line_thickness, example=str(names))
149
+ if len(det):
150
+ # Rescale boxes from img_size to im0 size
151
+ det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
152
+
153
+ # Print results
154
+ for c in det[:, -1].unique():
155
+ n = (det[:, -1] == c).sum() # detections per class
156
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
157
+
158
+ # Write results
159
+ for *xyxy, conf, cls in reversed(det):
160
+ if save_txt: # Write to file
161
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
162
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
163
+ with open(txt_path + '.txt', 'a') as f:
164
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
165
+
166
+ if save_img or save_crop or view_img: # Add bbox to image
167
+ c = int(cls) # integer class
168
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
169
+ annotator.box_label(xyxy, label, color=colors(c, True))
170
+ if save_crop:
171
+ save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
172
+
173
+ # Stream results
174
+ im0 = annotator.result()
175
+ if view_img:
176
+ cv2.imshow(str(p), im0)
177
+ cv2.waitKey(1) # 1 millisecond
178
+
179
+ # Save results (image with detections)
180
+ if save_img:
181
+ if dataset.mode == 'image':
182
+ cv2.imwrite(save_path, im0)
183
+ else: # 'video' or 'stream'
184
+ if vid_path[i] != save_path: # new video
185
+ vid_path[i] = save_path
186
+ if isinstance(vid_writer[i], cv2.VideoWriter):
187
+ vid_writer[i].release() # release previous video writer
188
+ if vid_cap: # video
189
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
190
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
191
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
192
+ else: # stream
193
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
194
+ save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
195
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
196
+ vid_writer[i].write(im0)
197
+
198
+ # Print time (inference-only)
199
+ LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
200
+
201
+ # Print results
202
+ t = tuple(x / seen * 1E3 for x in dt) # speeds per image
203
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
204
+ if save_txt or save_img:
205
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
206
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
207
+ if update:
208
+ strip_optimizer(weights) # update model (to fix SourceChangeWarning)
209
+
210
+
211
+ def parse_opt():
212
+ parser = argparse.ArgumentParser()
213
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
214
+ parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
215
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
216
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
217
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
218
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
219
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
220
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
221
+ parser.add_argument('--view-img', action='store_true', help='show results')
222
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
223
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
224
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
225
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
226
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
227
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
228
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
229
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
230
+ parser.add_argument('--update', action='store_true', help='update all models')
231
+ parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
232
+ parser.add_argument('--name', default='exp', help='save results to project/name')
233
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
234
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
235
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
236
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
237
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
238
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
239
+ opt = parser.parse_args()
240
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
241
+ print_args(vars(opt))
242
+ return opt
243
+
244
+
245
+ def main(opt):
246
+ check_requirements(exclude=('tensorboard', 'thop'))
247
+ run(**vars(opt))
248
+
249
+
250
+ if __name__ == "__main__":
251
+ opt = parse_opt()
252
+ main(opt)