a b/segment/predict.py
1
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
"""
3
Run YOLOv5 segmentation inference on images, videos, directories, streams, etc.
4
5
Usage - sources:
6
    $ python segment/predict.py --weights yolov5s-seg.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 segment/predict.py --weights yolov5s-seg.pt                 # PyTorch
19
                                          yolov5s-seg.torchscript        # TorchScript
20
                                          yolov5s-seg.onnx               # ONNX Runtime or OpenCV DNN with --dnn
21
                                          yolov5s-seg_openvino_model     # OpenVINO
22
                                          yolov5s-seg.engine             # TensorRT
23
                                          yolov5s-seg.mlmodel            # CoreML (macOS-only)
24
                                          yolov5s-seg_saved_model        # TensorFlow SavedModel
25
                                          yolov5s-seg.pb                 # TensorFlow GraphDef
26
                                          yolov5s-seg.tflite             # TensorFlow Lite
27
                                          yolov5s-seg_edgetpu.tflite     # TensorFlow Edge TPU
28
                                          yolov5s-seg_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
39
FILE = Path(__file__).resolve()
40
ROOT = FILE.parents[1]  # YOLOv5 root directory
41
if str(ROOT) not in sys.path:
42
    sys.path.append(str(ROOT))  # add ROOT to PATH
43
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative
44
45
from ultralytics.utils.plotting import Annotator, colors, save_one_box
46
47
from models.common import DetectMultiBackend
48
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
49
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
50
                           increment_path, non_max_suppression, print_args, scale_boxes, scale_segments,
51
                           strip_optimizer)
52
from utils.segment.general import masks2segments, process_mask, process_mask_native
53
from utils.torch_utils import select_device, smart_inference_mode
54
55
56
@smart_inference_mode()
57
def run(
58
    weights=ROOT / 'yolov5s-seg.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=(640, 640),  # inference size (height, width)
62
    conf_thres=0.25,  # confidence threshold
63
    iou_thres=0.45,  # NMS IOU threshold
64
    max_det=1000,  # maximum detections per image
65
    device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
66
    view_img=False,  # show results
67
    save_txt=False,  # save results to *.txt
68
    save_conf=False,  # save confidences in --save-txt labels
69
    save_crop=False,  # save cropped prediction boxes
70
    nosave=False,  # do not save images/videos
71
    classes=None,  # filter by class: --class 0, or --class 0 2 3
72
    agnostic_nms=False,  # class-agnostic NMS
73
    augment=False,  # augmented inference
74
    visualize=False,  # visualize features
75
    update=False,  # update all models
76
    project=ROOT / 'runs/predict-seg',  # save results to project/name
77
    name='exp',  # save results to project/name
78
    exist_ok=False,  # existing project/name ok, do not increment
79
    line_thickness=3,  # bounding box thickness (pixels)
80
    hide_labels=False,  # hide labels
81
    hide_conf=False,  # hide confidences
82
    half=False,  # use FP16 half-precision inference
83
    dnn=False,  # use OpenCV DNN for ONNX inference
84
    vid_stride=1,  # video frame-rate stride
85
    retina_masks=False,
86
):
87
    source = str(source)
88
    save_img = not nosave and not source.endswith('.txt')  # save inference images
89
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
90
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
91
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
92
    screenshot = source.lower().startswith('screen')
93
    if is_url and is_file:
94
        source = check_file(source)  # download
95
96
    # Directories
97
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
98
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir
99
100
    # Load model
101
    device = select_device(device)
102
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
103
    stride, names, pt = model.stride, model.names, model.pt
104
    imgsz = check_img_size(imgsz, s=stride)  # check image size
105
106
    # Dataloader
107
    bs = 1  # batch_size
108
    if webcam:
109
        view_img = check_imshow(warn=True)
110
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
111
        bs = len(dataset)
112
    elif screenshot:
113
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
114
    else:
115
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
116
    vid_path, vid_writer = [None] * bs, [None] * bs
117
118
    # Run inference
119
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup
120
    seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
121
    for path, im, im0s, vid_cap, s in dataset:
122
        with dt[0]:
123
            im = torch.from_numpy(im).to(model.device)
124
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
125
            im /= 255  # 0 - 255 to 0.0 - 1.0
126
            if len(im.shape) == 3:
127
                im = im[None]  # expand for batch dim
128
129
        # Inference
130
        with dt[1]:
131
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
132
            pred, proto = model(im, augment=augment, visualize=visualize)[:2]
133
134
        # NMS
135
        with dt[2]:
136
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det, nm=32)
137
138
        # Second-stage classifier (optional)
139
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
140
141
        # Process predictions
142
        for i, det in enumerate(pred):  # per image
143
            seen += 1
144
            if webcam:  # batch_size >= 1
145
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
146
                s += f'{i}: '
147
            else:
148
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
149
150
            p = Path(p)  # to Path
151
            save_path = str(save_dir / p.name)  # im.jpg
152
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
153
            s += '%gx%g ' % im.shape[2:]  # print string
154
            imc = im0.copy() if save_crop else im0  # for save_crop
155
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
156
            if len(det):
157
                if retina_masks:
158
                    # scale bbox first the crop masks
159
                    det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()  # rescale boxes to im0 size
160
                    masks = process_mask_native(proto[i], det[:, 6:], det[:, :4], im0.shape[:2])  # HWC
161
                else:
162
                    masks = process_mask(proto[i], det[:, 6:], det[:, :4], im.shape[2:], upsample=True)  # HWC
163
                    det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()  # rescale boxes to im0 size
164
165
                # Segments
166
                if save_txt:
167
                    segments = [
168
                        scale_segments(im0.shape if retina_masks else im.shape[2:], x, im0.shape, normalize=True)
169
                        for x in reversed(masks2segments(masks))]
170
171
                # Print results
172
                for c in det[:, 5].unique():
173
                    n = (det[:, 5] == c).sum()  # detections per class
174
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string
175
176
                # Mask plotting
177
                annotator.masks(
178
                    masks,
179
                    colors=[colors(x, True) for x in det[:, 5]],
180
                    im_gpu=torch.as_tensor(im0, dtype=torch.float16).to(device).permute(2, 0, 1).flip(0).contiguous() /
181
                    255 if retina_masks else im[i])
182
183
                # Write results
184
                for j, (*xyxy, conf, cls) in enumerate(reversed(det[:, :6])):
185
                    if save_txt:  # Write to file
186
                        seg = segments[j].reshape(-1)  # (n,2) to (n*2)
187
                        line = (cls, *seg, conf) if save_conf else (cls, *seg)  # label format
188
                        with open(f'{txt_path}.txt', 'a') as f:
189
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')
190
191
                    if save_img or save_crop or view_img:  # Add bbox to image
192
                        c = int(cls)  # integer class
193
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
194
                        annotator.box_label(xyxy, label, color=colors(c, True))
195
                        # annotator.draw.polygon(segments[j], outline=colors(c, True), width=3)
196
                    if save_crop:
197
                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
198
199
            # Stream results
200
            im0 = annotator.result()
201
            if view_img:
202
                if platform.system() == 'Linux' and p not in windows:
203
                    windows.append(p)
204
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
205
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
206
                cv2.imshow(str(p), im0)
207
                if cv2.waitKey(1) == ord('q'):  # 1 millisecond
208
                    exit()
209
210
            # Save results (image with detections)
211
            if save_img:
212
                if dataset.mode == 'image':
213
                    cv2.imwrite(save_path, im0)
214
                else:  # 'video' or 'stream'
215
                    if vid_path[i] != save_path:  # new video
216
                        vid_path[i] = save_path
217
                        if isinstance(vid_writer[i], cv2.VideoWriter):
218
                            vid_writer[i].release()  # release previous video writer
219
                        if vid_cap:  # video
220
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
221
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
222
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
223
                        else:  # stream
224
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
225
                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
226
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
227
                    vid_writer[i].write(im0)
228
229
        # Print time (inference-only)
230
        LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
231
232
    # Print results
233
    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image
234
    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
235
    if save_txt or save_img:
236
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
237
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
238
    if update:
239
        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)
240
241
242
def parse_opt():
243
    parser = argparse.ArgumentParser()
244
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-seg.pt', help='model path(s)')
245
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
246
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
247
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
248
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
249
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
250
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
251
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
252
    parser.add_argument('--view-img', action='store_true', help='show results')
253
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
254
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
255
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
256
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
257
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
258
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
259
    parser.add_argument('--augment', action='store_true', help='augmented inference')
260
    parser.add_argument('--visualize', action='store_true', help='visualize features')
261
    parser.add_argument('--update', action='store_true', help='update all models')
262
    parser.add_argument('--project', default=ROOT / 'runs/predict-seg', help='save results to project/name')
263
    parser.add_argument('--name', default='exp', help='save results to project/name')
264
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
265
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
266
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
267
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
268
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
269
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
270
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
271
    parser.add_argument('--retina-masks', action='store_true', help='whether to plot masks in native resolution')
272
    opt = parser.parse_args()
273
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
274
    print_args(vars(opt))
275
    return opt
276
277
278
def main(opt):
279
    check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
280
    run(**vars(opt))
281
282
283
if __name__ == '__main__':
284
    opt = parse_opt()
285
    main(opt)