glenn-jocher
commited on
Commit
•
66cf5c2
1
Parent(s):
a9553c0
Refactor detect.py arguments (#3559)
Browse files* Refactor detect.py arguments
@SkalskiP
@KalenMike
* unused ok
* comment arguments
detect.py
CHANGED
@@ -15,20 +15,42 @@ from utils.torch_utils import select_device, load_classifier, time_synchronized
|
|
15 |
|
16 |
|
17 |
@torch.no_grad()
|
18 |
-
def detect(
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
22 |
('rtsp://', 'rtmp://', 'http://', 'https://'))
|
23 |
|
24 |
# Directories
|
25 |
-
save_dir = increment_path(Path(
|
26 |
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
27 |
|
28 |
# Initialize
|
29 |
set_logging()
|
30 |
-
device = select_device(
|
31 |
-
half
|
32 |
|
33 |
# Load model
|
34 |
model = attempt_load(weights, map_location=device) # load FP32 model
|
@@ -66,11 +88,10 @@ def detect(opt):
|
|
66 |
|
67 |
# Inference
|
68 |
t1 = time_synchronized()
|
69 |
-
pred = model(img, augment=
|
70 |
|
71 |
# Apply NMS
|
72 |
-
pred = non_max_suppression(pred,
|
73 |
-
max_det=opt.max_det)
|
74 |
t2 = time_synchronized()
|
75 |
|
76 |
# Apply Classifier
|
@@ -89,7 +110,7 @@ def detect(opt):
|
|
89 |
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
|
90 |
s += '%gx%g ' % img.shape[2:] # print string
|
91 |
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
92 |
-
imc = im0.copy() if
|
93 |
if len(det):
|
94 |
# Rescale boxes from img_size to im0 size
|
95 |
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
@@ -103,15 +124,15 @@ def detect(opt):
|
|
103 |
for *xyxy, conf, cls in reversed(det):
|
104 |
if save_txt: # Write to file
|
105 |
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
106 |
-
line = (cls, *xywh, conf) if
|
107 |
with open(txt_path + '.txt', 'a') as f:
|
108 |
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
109 |
|
110 |
-
if save_img or
|
111 |
c = int(cls) # integer class
|
112 |
-
label = None if
|
113 |
-
plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=
|
114 |
-
if
|
115 |
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
|
116 |
|
117 |
# Print time (inference + NMS)
|
@@ -145,19 +166,22 @@ def detect(opt):
|
|
145 |
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
146 |
print(f"Results saved to {save_dir}{s}")
|
147 |
|
|
|
|
|
|
|
148 |
print(f'Done. ({time.time() - t0:.3f}s)')
|
149 |
|
150 |
|
151 |
if __name__ == '__main__':
|
152 |
parser = argparse.ArgumentParser()
|
153 |
parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
|
154 |
-
parser.add_argument('--source', type=str, default='data/images', help='
|
155 |
-
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
|
156 |
-
parser.add_argument('--conf-thres', type=float, default=0.25, help='
|
157 |
-
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold
|
158 |
-
parser.add_argument('--max-det', type=int, default=1000, help='maximum
|
159 |
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
160 |
-
parser.add_argument('--view-img', action='store_true', help='
|
161 |
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
162 |
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
163 |
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
|
@@ -177,9 +201,4 @@ if __name__ == '__main__':
|
|
177 |
print(opt)
|
178 |
check_requirements(exclude=('tensorboard', 'thop'))
|
179 |
|
180 |
-
|
181 |
-
for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
|
182 |
-
detect(opt=opt)
|
183 |
-
strip_optimizer(opt.weights)
|
184 |
-
else:
|
185 |
-
detect(opt=opt)
|
|
|
15 |
|
16 |
|
17 |
@torch.no_grad()
|
18 |
+
def detect(weights='yolov5s.pt', # model.pt path(s)
|
19 |
+
source='data/images', # file/dir/URL/glob, 0 for webcam
|
20 |
+
imgsz=640, # inference size (pixels)
|
21 |
+
conf_thres=0.25, # confidence threshold
|
22 |
+
iou_thres=0.45, # NMS IOU threshold
|
23 |
+
max_det=1000, # maximum detections per image
|
24 |
+
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
25 |
+
view_img=False, # show results
|
26 |
+
save_txt=False, # save results to *.txt
|
27 |
+
save_conf=False, # save confidences in --save-txt labels
|
28 |
+
save_crop=False, # save cropped prediction boxes
|
29 |
+
nosave=False, # do not save images/videos
|
30 |
+
classes=None, # filter by class: --class 0, or --class 0 2 3
|
31 |
+
agnostic_nms=False, # class-agnostic NMS
|
32 |
+
augment=False, # augmented inference
|
33 |
+
update=False, # update all models
|
34 |
+
project='runs/detect', # save results to project/name
|
35 |
+
name='exp', # save results to project/name
|
36 |
+
exist_ok=False, # existing project/name ok, do not increment
|
37 |
+
line_thickness=3, # bounding box thickness (pixels)
|
38 |
+
hide_labels=False, # hide labels
|
39 |
+
hide_conf=False, # hide confidences
|
40 |
+
half=False, # use FP16 half-precision inference
|
41 |
+
):
|
42 |
+
save_img = not nosave and not source.endswith('.txt') # save inference images
|
43 |
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
44 |
('rtsp://', 'rtmp://', 'http://', 'https://'))
|
45 |
|
46 |
# Directories
|
47 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
48 |
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
49 |
|
50 |
# Initialize
|
51 |
set_logging()
|
52 |
+
device = select_device(device)
|
53 |
+
half &= device.type != 'cpu' # half precision only supported on CUDA
|
54 |
|
55 |
# Load model
|
56 |
model = attempt_load(weights, map_location=device) # load FP32 model
|
|
|
88 |
|
89 |
# Inference
|
90 |
t1 = time_synchronized()
|
91 |
+
pred = model(img, augment=augment)[0]
|
92 |
|
93 |
# Apply NMS
|
94 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
|
|
95 |
t2 = time_synchronized()
|
96 |
|
97 |
# Apply Classifier
|
|
|
110 |
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
|
111 |
s += '%gx%g ' % img.shape[2:] # print string
|
112 |
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
113 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
114 |
if len(det):
|
115 |
# Rescale boxes from img_size to im0 size
|
116 |
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
|
|
124 |
for *xyxy, conf, cls in reversed(det):
|
125 |
if save_txt: # Write to file
|
126 |
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
127 |
+
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
|
128 |
with open(txt_path + '.txt', 'a') as f:
|
129 |
f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
130 |
|
131 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
132 |
c = int(cls) # integer class
|
133 |
+
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
|
134 |
+
plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness)
|
135 |
+
if save_crop:
|
136 |
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
|
137 |
|
138 |
# Print time (inference + NMS)
|
|
|
166 |
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
167 |
print(f"Results saved to {save_dir}{s}")
|
168 |
|
169 |
+
if update:
|
170 |
+
strip_optimizer(weights) # update model (to fix SourceChangeWarning)
|
171 |
+
|
172 |
print(f'Done. ({time.time() - t0:.3f}s)')
|
173 |
|
174 |
|
175 |
if __name__ == '__main__':
|
176 |
parser = argparse.ArgumentParser()
|
177 |
parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
|
178 |
+
parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
|
179 |
+
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
|
180 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
|
181 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IOU threshold')
|
182 |
+
parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
|
183 |
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
184 |
+
parser.add_argument('--view-img', action='store_true', help='show results')
|
185 |
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
186 |
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
187 |
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
|
|
|
201 |
print(opt)
|
202 |
check_requirements(exclude=('tensorboard', 'thop'))
|
203 |
|
204 |
+
detect(**vars(opt))
|
|
|
|
|
|
|
|
|
|