k20hcmus/FishEye8K
3
1import argparse2import os3import platform4import sys5from pathlib import Path6import pandas as pd7import torch8 9FILE = Path(__file__).resolve()10ROOT = FILE.parents[0] # YOLO root directory11if str(ROOT) not in sys.path:12 sys.path.append(str(ROOT)) # add ROOT to PATH13ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative14 15from models.common import DetectMultiBackend16from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams17from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,18 increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)19from utils.plots import Annotator, colors, save_one_box20from utils.torch_utils import select_device, smart_inference_mode21 22 23def convert_to_int(tensor):24 return tensor.type(torch.int16).item()25 26@smart_inference_mode()27def run(28 weights=ROOT / 'yolo.pt', # model path or triton URL29 source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)30 data=ROOT / 'data/coco.yaml', # dataset.yaml path31 imgsz=(640, 640), # inference size (height, width)32 conf_thres=0.25, # confidence threshold33 iou_thres=0.45, # NMS IOU threshold34 max_det=1000, # maximum detections per image35 device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu36 view_img=False, # show results37 save_txt=False, # save results to *.txt38 save_conf=False, # save confidences in --save-txt labels39 save_crop=False, # save cropped prediction boxes40 nosave=False, # do not save images/videos41 classes=None, # filter by class: --class 0, or --class 0 2 342 agnostic_nms=False, # class-agnostic NMS43 augment=False, # augmented inference44 visualize=False, # visualize features45 update=False, # update all models46 project=ROOT / 'runs/detect', # save results to project/name47 name='exp', # save results to project/name48 exist_ok=False, # existing project/name ok, do not increment49 line_thickness=2, # bounding box thickness (pixels)50 hide_labels=False, # hide labels51 hide_conf=False, # hide confidences52 half=False, # use FP16 half-precision inference53 dnn=False, # use OpenCV DNN for ONNX inference54 vid_stride=1, # video frame-rate stride55):56 source = str(source)57 save_img = not nosave and not source.endswith('.txt') # save inference images58 is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)59 is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))60 webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)61 screenshot = source.lower().startswith('screen')62 if is_url and is_file:63 source = check_file(source) # download64 65 # Directories66 save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run67 (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir68 69 # Load model70 device = select_device(device)71 model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)72 stride, names, pt = model.stride, model.names, model.pt73 imgsz = check_img_size(imgsz, s=stride) # check image size74 75 # Dataloader76 bs = 1 # batch_size77 if webcam:78 view_img = check_imshow(warn=True)79 dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)80 bs = len(dataset)81 elif screenshot:82 dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)83 else:84 dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)85 vid_path, vid_writer = [None] * bs, [None] * bs86 87 # Run inference88 model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup89 seen, windows, dt = 0, [], (Profile(), Profile(), Profile())90 frame_counts = [] 91 for path, im, im0s, vid_cap, s in dataset:92 with dt[0]:93 im = torch.from_numpy(im).to(model.device)94 im = im.half() if model.fp16 else im.float() # uint8 to fp16/3295 im /= 255 # 0 - 255 to 0.0 - 1.096 if len(im.shape) == 3:97 im = im[None] # expand for batch dim98 99 # Inference100 with dt[1]:101 visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False102 pred = model(im, augment=augment, visualize=visualize)103 104 105 # NMS106 with dt[2]:107 pred = pred[0][1] if isinstance(pred[0], list) else pred[0] # single model or ensemble108 pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)109 110 111 # Second-stage classifier (optional)112 # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)113 counts = {}114 115 # Process predictions116 for i, det in enumerate(pred): # per image117 seen += 1118 if webcam: # batch_size >= 1119 p, im0, frame = path[i], im0s[i].copy(), dataset.count120 s += f'{i}: '121 else:122 p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)123 124 p = Path(p) # to Path125 save_path = str(save_dir / p.name) # im.jpg126 txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt127 s += '%gx%g ' % im.shape[2:] # print string128 gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh129 imc = im0.copy() if save_crop else im0 # for save_crop130 annotator = Annotator(im0, line_width=line_thickness, example=str(names))131 if len(det):132 # Rescale boxes from img_size to im0 size133 det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()134 135 # Print results136 for c in det[:, 5].unique():137 n = (det[:, 5] == c).sum() # detections per class138 s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string139 counts[names[int(c)]] = n140 141 # Write results142 for *xyxy, conf, cls in reversed(det):143 if save_txt: # Write to file144 xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh145 line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format146 with open(f'{txt_path}.txt', 'a') as f:147 f.write(('%g ' * len(line)).rstrip() % line + '\n')148 149 if save_img or save_crop or view_img: # Add bbox to image150 c = int(cls) # integer class151 label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')152 annotator.box_label(xyxy, label, color=colors(c, True))153 if save_crop:154 save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)155 label_name = names[int(cls)] 156 # Stream results157 im0 = annotator.result()158 if view_img:159 if platform.system() == 'Linux' and p not in windows:160 windows.append(p)161 cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)162 cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])163 cv2.imshow(str(p), im0)164 cv2.waitKey(1) # 1 millisecond165 166 # Save results (image with detections)167 if save_img:168 if dataset.mode == 'image':169 cv2.imwrite(save_path, im0)170 else: # 'video' or 'stream'171 if vid_path[i] != save_path: # new video172 vid_path[i] = save_path173 if isinstance(vid_writer[i], cv2.VideoWriter):174 vid_writer[i].release() # release previous video writer175 if vid_cap: # video176 fps = vid_cap.get(cv2.CAP_PROP_FPS)177 w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))178 h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))179 else: # stream180 fps, w, h = 30, im0.shape[1], im0.shape[0]181 save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos182 vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('m','p','4','v'), fps, (w, h))183 vid_writer[i].write(im0)184 185 # Print time (inference-only)186 187 LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")188 frame_counts.append((frame, counts)) # Append the counts for each frame189 transformed_data = []190 191 # Iterate over frame_counts and transform each entry into a row in the DataFrame192 for frame, counts_dict in frame_counts:193 for label, count in counts_dict.items():194 transformed_data.append((frame, label.capitalize(), count))195 196 # Create a DataFrame from the transformed data197 df = pd.DataFrame(transformed_data, columns=['frame', 'label', 'count'])198 199 # Convert count column from tensors to integers200 df['count'] = df['count'].apply(convert_to_int)201 202 counts_df = pd.DataFrame(counts.items(), columns=['label', 'count'])203 counts_df['count'] = counts_df['count'].apply(convert_to_int)204 counts_df['label'] = counts_df['label'].astype(str) 205 #vid_writer.release()206 # Print results207 t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image208 LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)209 if save_txt or save_img:210 s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''211 LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")212 if update:213 strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)214 return save_path, counts_df, df215 216def parse_opt():217 parser = argparse.ArgumentParser()218 parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolo.pt', help='model path or triton URL')219 parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')220 parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')221 parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')222 parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')223 parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')224 parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')225 parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')226 parser.add_argument('--view-img', action='store_true', help='show results')227 parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')228 parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')229 parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')230 parser.add_argument('--nosave', action='store_true', help='do not save images/videos')231 parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')232 parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')233 parser.add_argument('--augment', action='store_true', help='augmented inference')234 parser.add_argument('--visualize', action='store_true', help='visualize features')235 parser.add_argument('--update', action='store_true', help='update all models')236 parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')237 parser.add_argument('--name', default='exp', help='save results to project/name')238 parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')239 parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')240 parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')241 parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')242 parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')243 parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')244 parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')245 opt = parser.parse_args()246 opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand247 print_args(vars(opt))248 return opt249 250 251def main(opt):252 check_requirements(exclude=('tensorboard', 'thop'))253 run(**vars(opt))254 255 256if __name__ == "__main__":257 opt = parse_opt()258 main(opt)259 260 