Diff of /classify/predict.py [000000] .. [190ca4]

Switch to unified view

a b/classify/predict.py
1
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
"""
3
Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
4
5
Usage - sources:
6
    $ python classify/predict.py --weights yolov5s-cls.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 classify/predict.py --weights yolov5s-cls.pt                 # PyTorch
19
                                           yolov5s-cls.torchscript        # TorchScript
20
                                           yolov5s-cls.onnx               # ONNX Runtime or OpenCV DNN with --dnn
21
                                           yolov5s-cls_openvino_model     # OpenVINO
22
                                           yolov5s-cls.engine             # TensorRT
23
                                           yolov5s-cls.mlmodel            # CoreML (macOS-only)
24
                                           yolov5s-cls_saved_model        # TensorFlow SavedModel
25
                                           yolov5s-cls.pb                 # TensorFlow GraphDef
26
                                           yolov5s-cls.tflite             # TensorFlow Lite
27
                                           yolov5s-cls_edgetpu.tflite     # TensorFlow Edge TPU
28
                                           yolov5s-cls_paddle_model       # PaddlePaddle
29
"""
30
31
import argparse
32
import os
33
import platform
34
import sys
35
from pathlib import Path
36
37
import torch
38
import torch.nn.functional as F
39
40
FILE = Path(__file__).resolve()
41
ROOT = FILE.parents[1]  # 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
47
48
from models.common import DetectMultiBackend
49
from utils.augmentations import classify_transforms
50
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
51
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
52
                           increment_path, print_args, strip_optimizer)
53
from utils.torch_utils import select_device, smart_inference_mode
54
55
56
@smart_inference_mode()
57
def run(
58
        weights=ROOT / 'yolov5s-cls.pt',  # model.pt path(s)
59
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
60
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
61
        imgsz=(224, 224),  # inference size (height, width)
62
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
63
        view_img=False,  # show results
64
        save_txt=False,  # save results to *.txt
65
        nosave=False,  # do not save images/videos
66
        augment=False,  # augmented inference
67
        visualize=False,  # visualize features
68
        update=False,  # update all models
69
        project=ROOT / 'runs/predict-cls',  # 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
        half=False,  # use FP16 half-precision inference
73
        dnn=False,  # use OpenCV DNN for ONNX inference
74
        vid_stride=1,  # video frame-rate stride
75
):
76
    source = str(source)
77
    save_img = not nosave and not source.endswith('.txt')  # save inference images
78
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
79
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
80
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
81
    screenshot = source.lower().startswith('screen')
82
    if is_url and is_file:
83
        source = check_file(source)  # download
84
85
    # Directories
86
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
87
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir
88
89
    # Load model
90
    device = select_device(device)
91
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
92
    stride, names, pt = model.stride, model.names, model.pt
93
    imgsz = check_img_size(imgsz, s=stride)  # check image size
94
95
    # Dataloader
96
    bs = 1  # batch_size
97
    if webcam:
98
        view_img = check_imshow(warn=True)
99
        dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
100
        bs = len(dataset)
101
    elif screenshot:
102
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
103
    else:
104
        dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
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
    seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
110
    for path, im, im0s, vid_cap, s in dataset:
111
        with dt[0]:
112
            im = torch.Tensor(im).to(model.device)
113
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
114
            if len(im.shape) == 3:
115
                im = im[None]  # expand for batch dim
116
117
        # Inference
118
        with dt[1]:
119
            results = model(im)
120
121
        # Post-process
122
        with dt[2]:
123
            pred = F.softmax(results, dim=1)  # probabilities
124
125
        # Process predictions
126
        for i, prob in enumerate(pred):  # per image
127
            seen += 1
128
            if webcam:  # batch_size >= 1
129
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
130
                s += f'{i}: '
131
            else:
132
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
133
134
            p = Path(p)  # to Path
135
            save_path = str(save_dir / p.name)  # im.jpg
136
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
137
138
            s += '%gx%g ' % im.shape[2:]  # print string
139
            annotator = Annotator(im0, example=str(names), pil=True)
140
141
            # Print results
142
            top5i = prob.argsort(0, descending=True)[:5].tolist()  # top 5 indices
143
            s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
144
145
            # Write results
146
            text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)
147
            if save_img or view_img:  # Add bbox to image
148
                annotator.text([32, 32], text, txt_color=(255, 255, 255))
149
            if save_txt:  # Write to file
150
                with open(f'{txt_path}.txt', 'a') as f:
151
                    f.write(text + '\n')
152
153
            # Stream results
154
            im0 = annotator.result()
155
            if view_img:
156
                if platform.system() == 'Linux' and p not in windows:
157
                    windows.append(p)
158
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
159
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
160
                cv2.imshow(str(p), im0)
161
                cv2.waitKey(1)  # 1 millisecond
162
163
            # Save results (image with detections)
164
            if save_img:
165
                if dataset.mode == 'image':
166
                    cv2.imwrite(save_path, im0)
167
                else:  # 'video' or 'stream'
168
                    if vid_path[i] != save_path:  # new video
169
                        vid_path[i] = save_path
170
                        if isinstance(vid_writer[i], cv2.VideoWriter):
171
                            vid_writer[i].release()  # release previous video writer
172
                        if vid_cap:  # video
173
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
174
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
175
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
176
                        else:  # stream
177
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
178
                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
179
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
180
                    vid_writer[i].write(im0)
181
182
        # Print time (inference-only)
183
        LOGGER.info(f'{s}{dt[1].dt * 1E3:.1f}ms')
184
185
    # Print results
186
    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image
187
    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
188
    if save_txt or save_img:
189
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
190
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
191
    if update:
192
        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)
193
194
195
def parse_opt():
196
    parser = argparse.ArgumentParser()
197
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')
198
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
199
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
200
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')
201
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
202
    parser.add_argument('--view-img', action='store_true', help='show results')
203
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
204
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
205
    parser.add_argument('--augment', action='store_true', help='augmented inference')
206
    parser.add_argument('--visualize', action='store_true', help='visualize features')
207
    parser.add_argument('--update', action='store_true', help='update all models')
208
    parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')
209
    parser.add_argument('--name', default='exp', help='save results to project/name')
210
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
211
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
212
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
213
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
214
    opt = parser.parse_args()
215
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
216
    print_args(vars(opt))
217
    return opt
218
219
220
def main(opt):
221
    check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
222
    run(**vars(opt))
223
224
225
if __name__ == '__main__':
226
    opt = parse_opt()
227
    main(opt)