1 line
15 KiB
Plaintext
Vendored
1 line
15 KiB
Plaintext
Vendored
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyOXFHc2xvoxJ7m00QoFZhde"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":1,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":235},"id":"zmkKG8v8f3Hx","executionInfo":{"status":"error","timestamp":1675163073561,"user_tz":-60,"elapsed":4279,"user":{"displayName":"marti Xooo","userId":"17000102553335328898"}},"outputId":"819779e2-d89b-49a4-bb60-c873c1b841ce"},"outputs":[{"output_type":"error","ename":"NameError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)","\u001b[0;32m<ipython-input-1-4ff1ecfd1ccc>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mFILE\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mPath\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m__file__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mresolve\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0mROOT\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mFILE\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mparents\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;31m# YOLOv5 root directory\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mROOT\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32min\u001b[0m \u001b[0msys\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mNameError\u001b[0m: name '__file__' is not defined"]}],"source":["\n","import argparse\n","import os\n","import platform\n","import sys\n","from pathlib import Path\n","\n","import torch\n","\n","FILE = Path(__file__).resolve()\n","ROOT = FILE.parents[0] # YOLOv5 root directory\n","if str(ROOT) not in sys.path:\n"," sys.path.append(str(ROOT)) # add ROOT to PATH\n","ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative\n","\n","from models.common import DetectMultiBackend\n","from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams\n","from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,\n"," increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)\n","from utils.plots import Annotator, colors, save_one_box\n","from utils.torch_utils import select_device, smart_inference_mode\n","\n","\n","@smart_inference_mode()\n","def run(\n"," weights=ROOT / 'yolov5s.pt', # model path or triton URL\n"," source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)\n"," data=ROOT / 'data/coco128.yaml', # dataset.yaml path\n"," imgsz=(640, 640), # inference size (height, width)\n"," conf_thres=0.25, # confidence threshold\n"," iou_thres=0.45, # NMS IOU threshold\n"," max_det=1000, # maximum detections per image\n"," device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu\n"," view_img=False, # show results\n"," save_txt=False, # save results to *.txt\n"," save_conf=False, # save confidences in --save-txt labels\n"," save_crop=False, # save cropped prediction boxes\n"," nosave=False, # do not save images/videos\n"," classes=None, # filter by class: --class 0, or --class 0 2 3\n"," agnostic_nms=False, # class-agnostic NMS\n"," augment=False, # augmented inference\n"," visualize=False, # visualize features\n"," update=False, # update all models\n"," project=ROOT / 'runs/detect', # save results to project/name\n"," name='exp', # save results to project/name\n"," exist_ok=False, # existing project/name ok, do not increment\n"," line_thickness=3, # bounding box thickness (pixels)\n"," hide_labels=False, # hide labels\n"," hide_conf=False, # hide confidences\n"," half=False, # use FP16 half-precision inference\n"," dnn=False, # use OpenCV DNN for ONNX inference\n"," vid_stride=1, # video frame-rate stride\n","):\n"," source = str(source)\n"," save_img = not nosave and not source.endswith('.txt') # save inference images\n"," is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)\n"," is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))\n"," webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)\n"," screenshot = source.lower().startswith('screen')\n"," if is_url and is_file:\n"," source = check_file(source) # download\n","\n"," # Directories\n"," save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run\n"," (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir\n","\n"," # Load model\n"," device = select_device(device)\n"," model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)\n"," stride, names, pt = model.stride, model.names, model.pt\n"," imgsz = check_img_size(imgsz, s=stride) # check image size\n","\n"," # Dataloader\n"," bs = 1 # batch_size\n"," if webcam:\n"," view_img = check_imshow(warn=True)\n"," dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)\n"," bs = len(dataset)\n"," elif screenshot:\n"," dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)\n"," else:\n"," dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)\n"," vid_path, vid_writer = [None] * bs, [None] * bs\n","\n"," # Run inference\n"," model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup\n"," seen, windows, dt = 0, [], (Profile(), Profile(), Profile())\n"," for path, im, im0s, vid_cap, s in dataset:\n"," with dt[0]:\n"," im = torch.from_numpy(im).to(model.device)\n"," im = im.half() if model.fp16 else im.float() # uint8 to fp16/32\n"," im /= 255 # 0 - 255 to 0.0 - 1.0\n"," if len(im.shape) == 3:\n"," im = im[None] # expand for batch dim\n","\n"," # Inference\n"," with dt[1]:\n"," visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False\n"," pred = model(im, augment=augment, visualize=visualize)\n","\n"," # NMS\n"," with dt[2]:\n"," pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)\n","\n"," # Second-stage classifier (optional)\n"," # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)\n","\n"," # Process predictions\n"," for i, det in enumerate(pred): # per image\n"," seen += 1\n"," if webcam: # batch_size >= 1\n"," p, im0, frame = path[i], im0s[i].copy(), dataset.count\n"," s += f'{i}: '\n"," else:\n"," p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)\n","\n"," p = Path(p) # to Path\n"," save_path = str(save_dir / p.name) # im.jpg\n"," txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt\n"," s += '%gx%g ' % im.shape[2:] # print string\n"," gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh\n"," imc = im0.copy() if save_crop else im0 # for save_crop\n"," annotator = Annotator(im0, line_width=line_thickness, example=str(names))\n"," if len(det):\n"," # Rescale boxes from img_size to im0 size\n"," det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()\n","\n"," # Print results\n"," for c in det[:, 5].unique():\n"," n = (det[:, 5] == c).sum() # detections per class\n"," s += f\"{n} {names[int(c)]}{'s' * (n > 1)}, \" # add to string\n","\n"," # Write results\n"," for *xyxy, conf, cls in reversed(det):\n"," if save_txt: # Write to file\n"," xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh\n"," line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format\n"," with open(f'{txt_path}.txt', 'a') as f:\n"," f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n","\n"," if save_img or save_crop or view_img: # Add bbox to image\n"," c = int(cls) # integer class\n"," label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')\n"," annotator.box_label(xyxy, label, color=colors(c, True))\n"," if save_crop:\n"," save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)\n","\n"," # Stream results\n"," im0 = annotator.result()\n"," if view_img:\n"," if platform.system() == 'Linux' and p not in windows:\n"," windows.append(p)\n"," cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)\n"," cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])\n"," cv2.imshow(str(p), im0)\n"," cv2.waitKey(1) # 1 millisecond\n","\n"," # Save results (image with detections)\n"," if save_img:\n"," if dataset.mode == 'image':\n"," cv2.imwrite(save_path, im0)\n"," else: # 'video' or 'stream'\n"," if vid_path[i] != save_path: # new video\n"," vid_path[i] = save_path\n"," if isinstance(vid_writer[i], cv2.VideoWriter):\n"," vid_writer[i].release() # release previous video writer\n"," if vid_cap: # video\n"," fps = vid_cap.get(cv2.CAP_PROP_FPS)\n"," w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n"," h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n"," else: # stream\n"," fps, w, h = 30, im0.shape[1], im0.shape[0]\n"," save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos\n"," vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))\n"," vid_writer[i].write(im0)\n","\n"," # Print time (inference-only)\n"," LOGGER.info(f\"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms\")\n","\n"," # Print results\n"," t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image\n"," LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)\n"," if save_txt or save_img:\n"," s = f\"\\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}\" if save_txt else ''\n"," LOGGER.info(f\"Results saved to {colorstr('bold', save_dir)}{s}\")\n"," if update:\n"," strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)\n","\n","\n","def parse_opt():\n"," parser = argparse.ArgumentParser()\n"," parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')\n"," parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')\n"," parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')\n"," parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')\n"," parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')\n"," parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')\n"," parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')\n"," parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n"," parser.add_argument('--view-img', action='store_true', help='show results')\n"," parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')\n"," parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')\n"," parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')\n"," parser.add_argument('--nosave', action='store_true', help='do not save images/videos')\n"," parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')\n"," parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')\n"," parser.add_argument('--augment', action='store_true', help='augmented inference')\n"," parser.add_argument('--visualize', action='store_true', help='visualize features')\n"," parser.add_argument('--update', action='store_true', help='update all models')\n"," parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')\n"," parser.add_argument('--name', default='exp', help='save results to project/name')\n"," parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')\n"," parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')\n"," parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')\n"," parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')\n"," parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')\n"," parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')\n"," parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')\n"," opt = parser.parse_args()\n"," opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand\n"," print_args(vars(opt))\n"," return opt\n","\n","\n","def main(opt):\n"," check_requirements(exclude=('tensorboard', 'thop'))\n"," run(**vars(opt))\n","\n","\n","if __name__ == \"__main__\":\n"," opt = parse_opt()\n"," main(opt)"]}]} |