caozibo commited on
Commit
3907c40
1 Parent(s): 5afb9e1

Upload detect.py

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