|
1 | 1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 | 2 | """
|
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. |
4 | 4 |
|
5 | 5 | 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 |
10 | 13 |
|
11 | 14 | Usage - formats:
|
12 | 15 | $ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
|
|
23 | 26 |
|
24 | 27 | import argparse
|
25 | 28 | import os
|
| 29 | +import platform |
26 | 30 | import sys
|
27 | 31 | from pathlib import Path
|
28 | 32 |
|
| 33 | +import torch.backends.cudnn as cudnn |
29 | 34 | import torch.nn.functional as F
|
30 | 35 |
|
31 | 36 | FILE = Path(__file__).resolve()
|
|
36 | 41 |
|
37 | 42 | from models.common import DetectMultiBackend
|
38 | 43 | 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 |
41 | 48 | from utils.torch_utils import select_device, smart_inference_mode
|
42 | 49 |
|
43 | 50 |
|
44 | 51 | @smart_inference_mode()
|
45 | 52 | def run(
|
46 | 53 | 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) |
49 | 57 | 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 |
50 | 67 | half=False, # use FP16 half-precision inference
|
51 | 68 | 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 |
55 | 69 | ):
|
56 | 70 | source = str(source)
|
| 71 | + save_img = not nosave and not source.endswith('.txt') # save inference images |
57 | 72 | is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
58 | 73 | is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
| 74 | + webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) |
59 | 75 | if is_url and is_file:
|
60 | 76 | source = check_file(source) # download
|
61 | 77 |
|
62 |
| - dt = Profile(), Profile(), Profile() |
63 |
| - device = select_device(device) |
64 |
| - |
65 | 78 | # Directories
|
66 | 79 | 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 |
68 | 81 |
|
69 | 82 | # 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: |
75 | 103 | 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 |
78 | 108 |
|
79 | 109 | # Inference
|
80 | 110 | with dt[1]:
|
81 | 111 | results = model(im)
|
82 | 112 |
|
83 | 113 | # Post-process
|
84 | 114 | 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") |
91 | 171 |
|
92 | 172 | # 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) |
98 | 180 |
|
99 | 181 |
|
100 | 182 | def parse_opt():
|
101 | 183 | parser = argparse.ArgumentParser()
|
102 | 184 | 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') |
105 | 188 | 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') |
106 | 198 | parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
107 | 199 | 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') |
111 | 200 | opt = parser.parse_args()
|
| 201 | + opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand |
112 | 202 | print_args(vars(opt))
|
113 | 203 | return opt
|
114 | 204 |
|
|
0 commit comments