Team Ai
Apppublic

Aniaaaa/code_site

sourceHugging Faceupdated 4y agoView on Hugging Face
0likes
detect.py260 linesDownload Raw Back to root
1# YOLOv5 ๐Ÿš€ by Ultralytics, GPL-3.0 license2"""3Run inference on images, videos, directories, streams, etc.4 5Usage - sources:6    $ python path/to/detect.py --weights yolov5s.pt --source 0              # webcam7                                                             img.jpg        # image8                                                             vid.mp4        # video9                                                             path/          # directory10                                                             path/*.jpg     # glob11                                                             'https://youtu.be/Zgi9g1ksQHc'  # YouTube12                                                             'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream13 14Usage - formats:15    $ python path/to/detect.py --weights yolov5s.pt                 # PyTorch16                                         yolov5s.torchscript        # TorchScript17                                         yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn18                                         yolov5s.xml                # OpenVINO19                                         yolov5s.engine             # TensorRT20                                         yolov5s.mlmodel            # CoreML (macOS-only)21                                         yolov5s_saved_model        # TensorFlow SavedModel22                                         yolov5s.pb                 # TensorFlow GraphDef23                                         yolov5s.tflite             # TensorFlow Lite24                                         yolov5s_edgetpu.tflite     # TensorFlow Edge TPU25"""26 27import argparse28import os29import sys30from pathlib import Path31 32import torch33import torch.backends.cudnn as cudnn34 35FILE = Path(__file__).resolve()36ROOT = FILE.parents[0]  # YOLOv5 root directory37if str(ROOT) not in sys.path:38    sys.path.append(str(ROOT))  # add ROOT to PATH39ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative40from models.common import DetectMultiBackend41from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams42from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,43                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)44from utils.plots import Annotator, colors, save_one_box45from utils.torch_utils import select_device, time_sync46 47 48@torch.no_grad()49def run(50        weights=ROOT / 'yolov5s.pt',  # model.pt path(s)51        source=ROOT / 'data/images',  # file/dir/URL/glob, 0 for webcam52        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path53        imgsz=(640, 640),  # inference size (height, width)54        conf_thres=0.25,  # confidence threshold55        iou_thres=0.45,  # NMS IOU threshold56        max_det=1000,  # maximum detections per image57        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu58        view_img=False,  # show results59        save_txt=False,  # save results to *.txt60        save_conf=False,  # save confidences in --save-txt labels61        save_crop=False,  # save cropped prediction boxes62        nosave=False,  # do not save images/videos63        classes=None,  # filter by class: --class 0, or --class 0 2 364        agnostic_nms=False,  # class-agnostic NMS65        augment=False,  # augmented inference66        visualize=False,  # visualize features67        update=False,  # update all models68        project=ROOT / 'runs/detect',  # save results to project/name69        name='exp',  # save results to project/name70        exist_ok=False,  # existing project/name ok, do not increment71        line_thickness=3,  # bounding box thickness (pixels)72        hide_labels=False,  # hide labels73        hide_conf=False,  # hide confidences74        half=False,  # use FP16 half-precision inference75        dnn=False,  # use OpenCV DNN for ONNX inference76):77    source = str(source)78    save_img = not nosave and not source.endswith('.txt')  # save inference images79    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)80    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))81    webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)82    if is_url and is_file:83        source = check_file(source)  # download84 85    # Directories86    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run87    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir88 89    # Load model90    device = select_device(device)91    print(f'weights : {weights}, device : {device}')92    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)93    stride, names, pt = model.stride, model.names, model.pt94    imgsz = check_img_size(imgsz, s=stride)  # check image sizerun95 96    # Dataloader97    if webcam:98        view_img = check_imshow()99        cudnn.benchmark = True  # set True to speed up constant image size inference100        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)101        bs = len(dataset)  # batch_size102    else:103        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)104        bs = 1  # batch_size105    vid_path, vid_writer = [None] * bs, [None] * bs106 107    # Run inference108    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup109    seen, windows, dt = 0, [], [0.0, 0.0, 0.0]110    for path, im, im0s, vid_cap, s in dataset:111        t1 = time_sync()112        im = torch.from_numpy(im).to(device)113        im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32114        im /= 255  # 0 - 255 to 0.0 - 1.0115        if len(im.shape) == 3:116            im = im[None]  # expand for batch dim117        t2 = time_sync()118        dt[0] += t2 - t1119 120        # Inference121        visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False122        pred = model(im, augment=augment, visualize=visualize)123        t3 = time_sync()124        dt[1] += t3 - t2125 126        # NMS127        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)128        dt[2] += time_sync() - t3129 130        # Second-stage classifier (optional)131        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)132 133        # Process predictions134        for i, det in enumerate(pred):  # per image135            seen += 1136            if webcam:  # batch_size >= 1137                p, im0, frame = path[i], im0s[i].copy(), dataset.count138                s += f'{i}: '139            else:140                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)141 142            p = Path(p)  # to Path143            save_path = str(save_dir / p.name)  # im.jpg144            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt145            s += '%gx%g ' % im.shape[2:]  # print string146            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh147            imc = im0.copy() if save_crop else im0  # for save_crop148            annotator = Annotator(im0, line_width=line_thickness, example=str(names))149            if len(det):150                # Rescale boxes from img_size to im0 size151                det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()152 153                # Print results154                for c in det[:, -1].unique():155                    n = (det[:, -1] == c).sum()  # detections per class156                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string157 158                # Write results159                for *xyxy, conf, cls in reversed(det):160                    if save_txt:  # Write to file161                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh162                        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format163                        with open(f'{txt_path}.txt', 'a') as f:164                            f.write(('%g ' * len(line)).rstrip() % line + '\n')165 166                    if save_img or save_crop or view_img:  # Add bbox to image167                        c = int(cls)  # integer class168                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')169                        annotator.box_label(xyxy, label, color=colors(c, True))170                    if save_crop:171                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)172 173            # Stream results174            im0 = annotator.result()175            if view_img:176                if p not in windows:177                    windows.append(p)178                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)179                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])180                cv2.imshow(str(p), im0)181                cv2.waitKey(1)  # 1 millisecond182 183            # Save results (image with detections)184            if save_img:185                if dataset.mode == 'image':186                    cv2.imwrite(save_path, im0)187                else:  # 'video' or 'stream'188                    if vid_path[i] != save_path:  # new video189                        vid_path[i] = save_path190                        if isinstance(vid_writer[i], cv2.VideoWriter):191                            vid_writer[i].release()  # release previous video writer192                        if vid_cap:  # video193                            fps = vid_cap.get(cv2.CAP_PROP_FPS)194                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))195                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))196                        else:  # stream197                            fps, w, h = 30, im0.shape[1], im0.shape[0]198                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos199                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))200                    vid_writer[i].write(im0)201 202        # Print time (inference-only)203        LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')204 205    # Print results206    t = tuple(x / seen * 1E3 for x in dt)  # speeds per image207    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)208    if save_txt or save_img:209        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''210        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")211    if update:212        strip_optimizer(weights)  # update model (to fix SourceChangeWarning)213 214 215def parse_opt():216    parser = argparse.ArgumentParser()217    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')218    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')219    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')220    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')221    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')222    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')223    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')224    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')225    parser.add_argument('--view-img', action='store_true', help='show results')226    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')227    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')228    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')229    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')230    parser.add_argument('--classes', nargs='+', type=int, default=(0, 1, 2, 3, 5, 7, 9, 11), help='filter by class: --classes 0, or --classes 0 2 3')231    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')232    parser.add_argument('--augment', action='store_true', help='augmented inference')233    parser.add_argument('--visualize', action='store_true', help='visualize features')234    parser.add_argument('--update', action='store_true', help='update all models')235    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')236    parser.add_argument('--name', default='exp', help='save results to project/name')237    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')238    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')239    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')240    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')241    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')242    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')243    opt = parser.parse_args()244    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand245    print_args(vars(opt))246 247    return opt248 249 250def main(opt):251    print(f"wtf opt {opt}")252    check_requirements(exclude=('tensorboard', 'thop'))253    run(**vars(opt))254 255 256if __name__ == "__main__":257    opt = parse_opt()258    print(f"wtf opt {opt}")259    main(opt)260