CoolFace
Apppublic

Bai360/Cotton2

sourceHugging Faceopenrailupdated 3y agoView on Hugging Face
0likes
predict.py227 linesDownload Raw Back to classify
1# YOLOv5 🚀 by Ultralytics, GPL-3.0 license2"""3Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.4 5Usage - sources:6    $ python classify/predict.py --weights yolov5s-cls.pt --source 0                               # webcam7                                                                   img.jpg                         # image8                                                                   vid.mp4                         # video9                                                                   screen                          # screenshot10                                                                   path/                           # directory11                                                                   list.txt                        # list of images12                                                                   list.streams                    # list of streams13                                                                   'path/*.jpg'                    # glob14                                                                   'https://youtu.be/Zgi9g1ksQHc'  # YouTube15                                                                   'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream16 17Usage - formats:18    $ python classify/predict.py --weights yolov5s-cls.pt                 # PyTorch19                                           yolov5s-cls.torchscript        # TorchScript20                                           yolov5s-cls.onnx               # ONNX Runtime or OpenCV DNN with --dnn21                                           yolov5s-cls_openvino_model     # OpenVINO22                                           yolov5s-cls.engine             # TensorRT23                                           yolov5s-cls.mlmodel            # CoreML (macOS-only)24                                           yolov5s-cls_saved_model        # TensorFlow SavedModel25                                           yolov5s-cls.pb                 # TensorFlow GraphDef26                                           yolov5s-cls.tflite             # TensorFlow Lite27                                           yolov5s-cls_edgetpu.tflite     # TensorFlow Edge TPU28                                           yolov5s-cls_paddle_model       # PaddlePaddle29"""30 31import argparse32import os33import platform34import sys35from pathlib import Path36 37import torch38import torch.nn.functional as F39 40FILE = Path(__file__).resolve()41ROOT = FILE.parents[1]  # YOLOv5 root directory42if str(ROOT) not in sys.path:43    sys.path.append(str(ROOT))  # add ROOT to PATH44ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative45 46from models.common import DetectMultiBackend47from utils.augmentations import classify_transforms48from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams49from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,50                           increment_path, print_args, strip_optimizer)51from utils.plots import Annotator52from utils.torch_utils import select_device, smart_inference_mode53 54 55@smart_inference_mode()56def run(57        weights=ROOT / 'yolov5s-cls.pt',  # model.pt path(s)58        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)59        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path60        imgsz=(224, 224),  # inference size (height, width)61        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu62        view_img=False,  # show results63        save_txt=False,  # save results to *.txt64        nosave=False,  # do not save images/videos65        augment=False,  # augmented inference66        visualize=False,  # visualize features67        update=False,  # update all models68        project=ROOT / 'runs/predict-cls',  # save results to project/name69        name='exp',  # save results to project/name70        exist_ok=False,  # existing project/name ok, do not increment71        half=False,  # use FP16 half-precision inference72        dnn=False,  # use OpenCV DNN for ONNX inference73        vid_stride=1,  # video frame-rate stride74):75    source = str(source)76    save_img = not nosave and not source.endswith('.txt')  # save inference images77    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)78    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))79    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)80    screenshot = source.lower().startswith('screen')81    if is_url and is_file:82        source = check_file(source)  # download83 84    # Directories85    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run86    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir87 88    # Load model89    device = select_device(device)90    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)91    stride, names, pt = model.stride, model.names, model.pt92    imgsz = check_img_size(imgsz, s=stride)  # check image size93 94    # Dataloader95    bs = 1  # batch_size96    if webcam:97        view_img = check_imshow(warn=True)98        dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)99        bs = len(dataset)100    elif screenshot:101        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)102    else:103        dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)104    vid_path, vid_writer = [None] * bs, [None] * bs105 106    # Run inference107    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup108    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())109    for path, im, im0s, vid_cap, s in dataset:110        with dt[0]:111            im = torch.Tensor(im).to(model.device)112            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32113            if len(im.shape) == 3:114                im = im[None]  # expand for batch dim115 116        # Inference117        with dt[1]:118            results = model(im)119 120        # Post-process121        with dt[2]:122            pred = F.softmax(results, dim=1)  # probabilities123 124        # Process predictions125        for i, prob in enumerate(pred):  # per image126            seen += 1127            if webcam:  # batch_size >= 1128                p, im0, frame = path[i], im0s[i].copy(), dataset.count129                s += f'{i}: '130            else:131                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)132 133            p = Path(p)  # to Path134            save_path = str(save_dir / p.name)  # im.jpg135            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt136 137            s += '%gx%g ' % im.shape[2:]  # print string138            annotator = Annotator(im0, example=str(names), pil=True)139 140            # Print results141            top5i = prob.argsort(0, descending=True)[:5].tolist()  # top 5 indices142            s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "143 144            # Write results145            text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)146            if save_img or view_img:  # Add bbox to image147                annotator.text((32, 32), text, txt_color=(255, 255, 255))148            if save_txt:  # Write to file149                with open(f'{txt_path}.txt', 'a') as f:150                    f.write(text + '\n')151 152            # Stream results153            im0 = annotator.result()154            if view_img:155                if platform.system() == 'Linux' and p not in windows:156                    windows.append(p)157                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)158                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])159                cv2.imshow(str(p), im0)160                cv2.waitKey(1)  # 1 millisecond161 162            # Save results (image with detections)163            if save_img:164                if dataset.mode == 'image':165                    cv2.imwrite(save_path, im0)166                else:  # 'video' or 'stream'167                    if vid_path[i] != save_path:  # new video168                        vid_path[i] = save_path169                        if isinstance(vid_writer[i], cv2.VideoWriter):170                            vid_writer[i].release()  # release previous video writer171                        if vid_cap:  # video172                            fps = vid_cap.get(cv2.CAP_PROP_FPS)173                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))174                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))175                        else:  # stream176                            fps, w, h = 30, im0.shape[1], im0.shape[0]177                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos178                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))179                    vid_writer[i].write(im0)180 181        # Print time (inference-only)182        LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms")183 184    # Print results185    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image186    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)187    if save_txt or save_img:188        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''189        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")190    if update:191        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)192 193 194def parse_opt():195    parser = argparse.ArgumentParser()196    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')197    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')198    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')199    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')200    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')201    parser.add_argument('--view-img', action='store_true', help='show results')202    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')203    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')204    parser.add_argument('--augment', action='store_true', help='augmented inference')205    parser.add_argument('--visualize', action='store_true', help='visualize features')206    parser.add_argument('--update', action='store_true', help='update all models')207    parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')208    parser.add_argument('--name', default='exp', help='save results to project/name')209    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')210    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')211    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')212    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')213    opt = parser.parse_args()214    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand215    print_args(vars(opt))216    return opt217 218 219def main(opt):220    check_requirements(exclude=('tensorboard', 'thop'))221    run(**vars(opt))222 223 224if __name__ == "__main__":225    opt = parse_opt()226    main(opt)227