Skip to content

Commit 51c9f92

Browse files
authored
Streaming Classification support (#9106)
* Streaming Classification support * Streaming Classification support * Streaming Classification support
1 parent 48e56d3 commit 51c9f92

File tree

3 files changed

+131
-40
lines changed

3 files changed

+131
-40
lines changed

classify/predict.py

Lines changed: 129 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
22
"""
3-
Run YOLOv5 classification inference on images, videos, directories, and globs.
3+
Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
44
55
Usage - sources:
6-
$ python classify/predict.py --weights yolov5s.pt --source img.jpg # image
7-
vid.mp4 # video
8-
path/ # directory
9-
'path/*.jpg' # glob
6+
$ python classify/predict.py --weights yolov5s-cls.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
1013
1114
Usage - formats:
1215
$ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
@@ -23,9 +26,11 @@
2326

2427
import argparse
2528
import os
29+
import platform
2630
import sys
2731
from pathlib import Path
2832

33+
import torch.backends.cudnn as cudnn
2934
import torch.nn.functional as F
3035

3136
FILE = Path(__file__).resolve()
@@ -36,79 +41,164 @@
3641

3742
from models.common import DetectMultiBackend
3843
from utils.augmentations import classify_transforms
39-
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages
40-
from utils.general import LOGGER, Profile, check_file, check_requirements, colorstr, increment_path, print_args
44+
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
45+
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
46+
increment_path, print_args, strip_optimizer)
47+
from utils.plots import Annotator
4148
from utils.torch_utils import select_device, smart_inference_mode
4249

4350

4451
@smart_inference_mode()
4552
def run(
4653
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
47-
source=ROOT / 'data/images', # file/dir/URL/glob
48-
imgsz=224, # inference size
54+
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
55+
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
56+
imgsz=(224, 224), # inference size (height, width)
4957
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
58+
view_img=False, # show results
59+
save_txt=False, # save results to *.txt
60+
nosave=False, # do not save images/videos
61+
augment=False, # augmented inference
62+
visualize=False, # visualize features
63+
update=False, # update all models
64+
project=ROOT / 'runs/predict-cls', # save results to project/name
65+
name='exp', # save results to project/name
66+
exist_ok=False, # existing project/name ok, do not increment
5067
half=False, # use FP16 half-precision inference
5168
dnn=False, # use OpenCV DNN for ONNX inference
52-
project=ROOT / 'runs/predict-cls', # save to project/name
53-
name='exp', # save to project/name
54-
exist_ok=False, # existing project/name ok, do not increment
5569
):
5670
source = str(source)
71+
save_img = not nosave and not source.endswith('.txt') # save inference images
5772
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
5873
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
74+
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
5975
if is_url and is_file:
6076
source = check_file(source) # download
6177

62-
dt = Profile(), Profile(), Profile()
63-
device = select_device(device)
64-
6578
# Directories
6679
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
67-
save_dir.mkdir(parents=True, exist_ok=True) # make dir
80+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
6881

6982
# Load model
70-
model = DetectMultiBackend(weights, device=device, dnn=dnn, fp16=half)
71-
model.warmup(imgsz=(1, 3, imgsz, imgsz)) # warmup
72-
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz))
73-
for seen, (path, im, im0s, vid_cap, s) in enumerate(dataset):
74-
# Image
83+
device = select_device(device)
84+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
85+
stride, names, pt = model.stride, model.names, model.pt
86+
imgsz = check_img_size(imgsz, s=stride) # check image size
87+
88+
# Dataloader
89+
if webcam:
90+
view_img = check_imshow()
91+
cudnn.benchmark = True # set True to speed up constant image size inference
92+
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]))
93+
bs = len(dataset) # batch_size
94+
else:
95+
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]))
96+
bs = 1 # batch_size
97+
vid_path, vid_writer = [None] * bs, [None] * bs
98+
99+
# Run inference
100+
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
101+
seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
102+
for path, im, im0s, vid_cap, s in dataset:
75103
with dt[0]:
76-
im = im.unsqueeze(0).to(device)
77-
im = im.half() if model.fp16 else im.float()
104+
im = im.to(device)
105+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
106+
if len(im.shape) == 3:
107+
im = im[None] # expand for batch dim
78108

79109
# Inference
80110
with dt[1]:
81111
results = model(im)
82112

83113
# Post-process
84114
with dt[2]:
85-
p = F.softmax(results, dim=1) # probabilities
86-
i = p.argsort(1, descending=True)[:, :5].squeeze().tolist() # top 5 indices
87-
# if save:
88-
# imshow_cls(im, f=save_dir / Path(path).name, verbose=True)
89-
LOGGER.info(
90-
f"{s}{imgsz}x{imgsz} {', '.join(f'{model.names[j]} {p[0, j]:.2f}' for j in i)}, {dt[1].dt * 1E3:.1f}ms")
115+
pred = F.softmax(results, dim=1) # probabilities
116+
117+
# Process predictions
118+
for i, prob in enumerate(pred): # per image
119+
seen += 1
120+
if webcam: # batch_size >= 1
121+
p, im0 = path[i], im0s[i].copy()
122+
s += f'{i}: '
123+
else:
124+
p, im0 = path, im0s.copy()
125+
126+
p = Path(p) # to Path
127+
save_path = str(save_dir / p.name) # im.jpg
128+
s += '%gx%g ' % im.shape[2:] # print string
129+
annotator = Annotator(im0, example=str(names), pil=True)
130+
131+
# Print results
132+
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
133+
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
134+
135+
# Write results
136+
if save_img or view_img: # Add bbox to image
137+
text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)
138+
annotator.text((64, 64), text, txt_color=(255, 255, 255))
139+
140+
# Stream results
141+
im0 = annotator.result()
142+
if view_img:
143+
if platform.system() == 'Linux' and p not in windows:
144+
windows.append(p)
145+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
146+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
147+
cv2.imshow(str(p), im0)
148+
cv2.waitKey(1) # 1 millisecond
149+
150+
# Save results (image with detections)
151+
if save_img:
152+
if dataset.mode == 'image':
153+
cv2.imwrite(save_path, im0)
154+
else: # 'video' or 'stream'
155+
if vid_path[i] != save_path: # new video
156+
vid_path[i] = save_path
157+
if isinstance(vid_writer[i], cv2.VideoWriter):
158+
vid_writer[i].release() # release previous video writer
159+
if vid_cap: # video
160+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
161+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
162+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
163+
else: # stream
164+
fps, w, h = 30, im0.shape[1], im0.shape[0]
165+
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
166+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
167+
vid_writer[i].write(im0)
168+
169+
# Print time (inference-only)
170+
LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms")
91171

92172
# Print results
93-
t = tuple(x.t / (seen + 1) * 1E3 for x in dt) # speeds per image
94-
shape = (1, 3, imgsz, imgsz)
95-
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms post-process per image at shape {shape}' % t)
96-
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
97-
return p
173+
t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
174+
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
175+
if save_txt or save_img:
176+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
177+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
178+
if update:
179+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
98180

99181

100182
def parse_opt():
101183
parser = argparse.ArgumentParser()
102184
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')
103-
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob')
104-
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=224, help='train, val image size (pixels)')
185+
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
186+
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
187+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')
105188
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
189+
parser.add_argument('--view-img', action='store_true', help='show results')
190+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
191+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
192+
parser.add_argument('--augment', action='store_true', help='augmented inference')
193+
parser.add_argument('--visualize', action='store_true', help='visualize features')
194+
parser.add_argument('--update', action='store_true', help='update all models')
195+
parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')
196+
parser.add_argument('--name', default='exp', help='save results to project/name')
197+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
106198
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
107199
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
108-
parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save to project/name')
109-
parser.add_argument('--name', default='exp', help='save to project/name')
110-
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
111200
opt = parser.parse_args()
201+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
112202
print_args(vars(opt))
113203
return opt
114204

detect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
22
"""
3-
Run YOLOv5 detection inference on images, videos, directories, streams, etc.
3+
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
44
55
Usage - sources:
66
$ python detect.py --weights yolov5s.pt --source 0 # webcam

utils/augmentations.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,4 +344,5 @@ def classify_albumentations(augment=True,
344344

345345
def classify_transforms(size=224):
346346
# Transforms to apply if albumentations not installed
347+
assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'
347348
return T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])

0 commit comments

Comments
 (0)