Diff of /hubconf.py [000000] .. [190ca4]

Switch to unified view

a b/hubconf.py
1
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
"""
3
PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5
4
5
Usage:
6
    import torch
7
    model = torch.hub.load('ultralytics/yolov5', 'yolov5s')  # official model
8
    model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s')  # from branch
9
    model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt')  # custom/local model
10
    model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local')  # local repo
11
"""
12
13
import torch
14
15
16
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
17
    """Creates or loads a YOLOv5 model
18
19
    Arguments:
20
        name (str): model name 'yolov5s' or path 'path/to/best.pt'
21
        pretrained (bool): load pretrained weights into the model
22
        channels (int): number of input channels
23
        classes (int): number of model classes
24
        autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
25
        verbose (bool): print all information to screen
26
        device (str, torch.device, None): device to use for model parameters
27
28
    Returns:
29
        YOLOv5 model
30
    """
31
    from pathlib import Path
32
33
    from models.common import AutoShape, DetectMultiBackend
34
    from models.experimental import attempt_load
35
    from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
36
    from utils.downloads import attempt_download
37
    from utils.general import LOGGER, ROOT, check_requirements, intersect_dicts, logging
38
    from utils.torch_utils import select_device
39
40
    if not verbose:
41
        LOGGER.setLevel(logging.WARNING)
42
    check_requirements(ROOT / 'requirements.txt', exclude=('opencv-python', 'tensorboard', 'thop'))
43
    name = Path(name)
44
    path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name  # checkpoint path
45
    try:
46
        device = select_device(device)
47
        if pretrained and channels == 3 and classes == 80:
48
            try:
49
                model = DetectMultiBackend(path, device=device, fuse=autoshape)  # detection model
50
                if autoshape:
51
                    if model.pt and isinstance(model.model, ClassificationModel):
52
                        LOGGER.warning('WARNING ⚠️ YOLOv5 ClassificationModel is not yet AutoShape compatible. '
53
                                       'You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224).')
54
                    elif model.pt and isinstance(model.model, SegmentationModel):
55
                        LOGGER.warning('WARNING ⚠️ YOLOv5 SegmentationModel is not yet AutoShape compatible. '
56
                                       'You will not be able to run inference with this model.')
57
                    else:
58
                        model = AutoShape(model)  # for file/URI/PIL/cv2/np inputs and NMS
59
            except Exception:
60
                model = attempt_load(path, device=device, fuse=False)  # arbitrary model
61
        else:
62
            cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0]  # model.yaml path
63
            model = DetectionModel(cfg, channels, classes)  # create model
64
            if pretrained:
65
                ckpt = torch.load(attempt_download(path), map_location=device)  # load
66
                csd = ckpt['model'].float().state_dict()  # checkpoint state_dict as FP32
67
                csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors'])  # intersect
68
                model.load_state_dict(csd, strict=False)  # load
69
                if len(ckpt['model'].names) == classes:
70
                    model.names = ckpt['model'].names  # set class names attribute
71
        if not verbose:
72
            LOGGER.setLevel(logging.INFO)  # reset to default
73
        return model.to(device)
74
75
    except Exception as e:
76
        help_url = 'https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading'
77
        s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
78
        raise Exception(s) from e
79
80
81
def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
82
    # YOLOv5 custom or local model
83
    return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
84
85
86
def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
87
    # YOLOv5-nano model https://github.com/ultralytics/yolov5
88
    return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
89
90
91
def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
92
    # YOLOv5-small model https://github.com/ultralytics/yolov5
93
    return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
94
95
96
def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
97
    # YOLOv5-medium model https://github.com/ultralytics/yolov5
98
    return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
99
100
101
def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
102
    # YOLOv5-large model https://github.com/ultralytics/yolov5
103
    return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
104
105
106
def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
107
    # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
108
    return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
109
110
111
def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
112
    # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
113
    return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
114
115
116
def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
117
    # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
118
    return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
119
120
121
def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
122
    # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
123
    return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
124
125
126
def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
127
    # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
128
    return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
129
130
131
def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
132
    # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
133
    return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
134
135
136
if __name__ == '__main__':
137
    import argparse
138
    from pathlib import Path
139
140
    import numpy as np
141
    from PIL import Image
142
143
    from utils.general import cv2, print_args
144
145
    # Argparser
146
    parser = argparse.ArgumentParser()
147
    parser.add_argument('--model', type=str, default='yolov5s', help='model name')
148
    opt = parser.parse_args()
149
    print_args(vars(opt))
150
151
    # Model
152
    model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
153
    # model = custom(path='path/to/model.pt')  # custom
154
155
    # Images
156
    imgs = [
157
        'data/images/zidane.jpg',  # filename
158
        Path('data/images/zidane.jpg'),  # Path
159
        'https://ultralytics.com/images/zidane.jpg',  # URI
160
        cv2.imread('data/images/bus.jpg')[:, :, ::-1],  # OpenCV
161
        Image.open('data/images/bus.jpg'),  # PIL
162
        np.zeros((320, 640, 3))]  # numpy
163
164
    # Inference
165
    results = model(imgs, size=320)  # batched inference
166
167
    # Results
168
    results.print()
169
    results.save()