CoolFace
Apppublic

k20hcmus/FishEye8K

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
3likes
detect_deepsort.py343 linesDownload Raw Back to root
1import argparse2import os3import platform4import sys5from pathlib import Path6import math7import torch8import numpy as np9import re10from deep_sort_pytorch.utils.parser import get_config11from deep_sort_pytorch.deep_sort import DeepSort12import pandas as pd13from collections import deque14FILE = Path(__file__).resolve()15ROOT = FILE.parents[0]  # YOLO root directory16if str(ROOT) not in sys.path:17    sys.path.append(str(ROOT))  # add ROOT to PATH18ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative19 20from models.common import DetectMultiBackend21from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams22from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,23                           increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)24from utils.plots import Annotator, colors, save_one_box25from utils.torch_utils import select_device, smart_inference_mode26 27def initialize_deepsort():28    # Create the Deep SORT configuration object and load settings from the YAML file29    cfg_deep = get_config()30    cfg_deep.merge_from_file("deep_sort_pytorch/configs/deep_sort.yaml")31 32    # Initialize the DeepSort tracker33    deepsort = DeepSort(cfg_deep.DEEPSORT.REID_CKPT,34                        max_dist=cfg_deep.DEEPSORT.MAX_DIST,35                        # min_confidence  parameter sets the minimum tracking confidence required for an object detection to be considered in the tracking process36                        min_confidence=cfg_deep.DEEPSORT.MIN_CONFIDENCE,37                        #nms_max_overlap specifies the maximum allowed overlap between bounding boxes during non-maximum suppression (NMS)38                        nms_max_overlap=cfg_deep.DEEPSORT.NMS_MAX_OVERLAP,39                        #max_iou_distance parameter defines the maximum intersection-over-union (IoU) distance between object detections40                        max_iou_distance=cfg_deep.DEEPSORT.MAX_IOU_DISTANCE,41                        # Max_age: If an object's tracking ID is lost (i.e., the object is no longer detected), this parameter determines how many frames the tracker should wait before assigning a new id42                        max_age=cfg_deep.DEEPSORT.MAX_AGE, n_init=cfg_deep.DEEPSORT.N_INIT,43                        #nn_budget: It sets the budget for the nearest-neighbor search.44                        nn_budget=cfg_deep.DEEPSORT.NN_BUDGET,45                        use_cuda=False46        )47 48    return deepsort49 50deepsort = initialize_deepsort()51data_deque = {}52def classNames():53    cocoClassNames = ["Bus", "Bike", "Car", "Pedestrian", "Truck"54                  ]55    return cocoClassNames56className = classNames()57# def convert_to_int(x):58#     if isinstance(x, str):59#         # Extract numeric value from tensor string using regular expressions60#         match = re.match(r'tensor\((\d+)\)', x)61#         if match:62#             return int(match.group(1))63#     return x64def colorLabels(classid):65    if classid == 0: #Bus66        color = (0, 0, 255)67    elif classid == 1: #Bike  250, 247, 068        color = (255, 148, 0) # BGR (247, 0, 250)69    elif classid == 2: #Car 70        color = (0, 255, 10)71    elif classid == 3: #Pedestrian72        color = (0, 247, 250) 73    else: #Truck74        color = (235,0,255)   75    return tuple(color)76 77def convert_to_int(tensor):78    return tensor.type(torch.int16).item()79 80def draw_boxes(frame, bbox_xyxy, draw_trails, identities=None, categories=None, offset=(0,0)):81    height, width, _ = frame.shape82    for key in list(data_deque):83      if key not in identities:84        data_deque.pop(key)85 86    for i, box in enumerate(bbox_xyxy):87        x1, y1, x2, y2 = [int(i) for i in box]88        x1 += offset[0]89        y1 += offset[0]90        x2 += offset[0]91        y2 += offset[0]92        #Find the center point of the bounding box93        center = int((x1+x2)/2), int((y1+y2)/2)94        cat = int(categories[i]) if categories is not None else 095        color = colorLabels(cat)96        #color = [255,0,0]#compute_color_labels(cat)97        id = int(identities[i]) if identities is not  None else 098        # create new buffer for new object99        if id not in data_deque:100          data_deque[id] = deque(maxlen= 64)101        data_deque[id].appendleft(center)102        cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)103        # name = className[cat]104        # label = str(id) + ":" + name105        # text_size = cv2.getTextSize(label, 0, fontScale=0.5, thickness=2)[0]106        # c2 = x1 + text_size[0], y1 - text_size[1] - 3107        # cv2.rectangle(frame, (x1, y1), c2, color, -1)108        # cv2.putText(frame, label, (x1, y1 - 2), 0, 0.5, [255, 255, 255], thickness=1, lineType=cv2.LINE_AA)109        cv2.circle(frame,center, 2, (0,255,0), cv2.FILLED)110        if draw_trails:111              # draw trail112              for i in range(1, len(data_deque[id])):113                  # check if on buffer value is none114                  if data_deque[id][i - 1] is None or data_deque[id][i] is None:115                      continue116                  # generate dynamic thickness of trails117                  thickness = int(np.sqrt(64 / float(i + i)) * 1.5)118                  # draw trails119                  cv2.line(frame, data_deque[id][i - 1], data_deque[id][i], color, thickness)    120    return frame121 122@smart_inference_mode()123def run_deepsort(124        weights=ROOT / 'yolo.pt',  # model path or triton URL125        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)126        data=ROOT / 'data/coco.yaml',  # dataset.yaml path127        imgsz=(640, 640),  # inference size (height, width)128        conf_thres=0.25,  # confidence threshold129        iou_thres=0.45,  # NMS IOU threshold130        max_det=1000,  # maximum detections per image131        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu132        view_img=False,  # show results133        nosave=False,  # do not save images/videos134        classes=None,  # filter by class: --class 0, or --class 0 2 3135        agnostic_nms=False,  # class-agnostic NMS136        augment=False,  # augmented inference137        visualize=False,  # visualize features138        update=False,  # update all models139        project=ROOT / 'runs/detect',  # save results to project/name140        name='exp',  # save results to project/name141        exist_ok=False,  # existing project/name ok, do not increment142        half=False,  # use FP16 half-precision inference143        dnn=False,  # use OpenCV DNN for ONNX inference144        vid_stride=1,  # video frame-rate stride145        draw_trails = False,146):147    source = str(source)148    save_img = not nosave and not source.endswith('.txt')  # save inference images149    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)150    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))151    webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)152    screenshot = source.lower().startswith('screen')153    if is_url and is_file:154        source = check_file(source)  # download155 156    # Directories157    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run158    save_dir.mkdir(parents=True, exist_ok=True)  # make dir159 160    # Load model161    device = select_device(device)162    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)163    stride, names, pt = model.stride, model.names, model.pt164    imgsz = check_img_size(imgsz, s=stride)  # check image size165 166    # Dataloader167    bs = 1  # batch_size168    if webcam:169        view_img = check_imshow(warn=True)170        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)171        bs = len(dataset)172    elif screenshot:173        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)174    else:175        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)176    vid_path, vid_writer = [None] * bs, [None] * bs177 178    # Run inference179    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmup180    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())181    frame_counts = []  182    for path, im, im0s, vid_cap, s in dataset:183        with dt[0]:184            im = torch.from_numpy(im).to(model.device)185            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32186            im /= 255  # 0 - 255 to 0.0 - 1.0187            if len(im.shape) == 3:188                im = im[None]  # expand for batch dim189 190        # Inference191        with dt[1]:192            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False193            pred = model(im, augment=augment, visualize=visualize)194            # pred = pred[0][1]195 196        # NMS197        with dt[2]:198            pred = pred[0][1] if isinstance(pred[0], list) else pred[0]  # single model or ensemble199            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)200 201        # Second-stage classifier (optional)202        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)203        counts = {}204        # Process predictions205        for i, det in enumerate(pred):  # per image206            seen += 1207            if webcam:  # batch_size >= 1208                p, im0, frame = path[i], im0s[i].copy(), dataset.count209                s += f'{i}: '210            else:211                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)212 213            p = Path(p)  # to Path214            save_path = str(save_dir / p.name)  # im.jpg215            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt216            s += '%gx%g ' % im.shape[2:]  # print string217            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh218            ims = im0.copy()219            if len(det):220                # Rescale boxes from img_size to im0 size221                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()222 223                # Print results224                for c in det[:, 5].unique():225                    n = (det[:, 5] == c).sum()  # detections per class226                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string227                    counts[names[int(c)]] = n228                xywh_bboxs = []229                confs = []230                oids = []231                outputs = []232                # Write results233                for *xyxy, conf, cls in reversed(det):234                    x1, y1, x2, y2 = xyxy235                    x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)236                    #Find the Center Coordinates for each of the detected object237                    cx, cy = int((x1+x2)/2), int((y1+y2)/2)238                    #Find the Width and Height of the Boundng box239                    bbox_width = abs(x1-x2)240                    bbox_height = abs(y1-y2)241                    xcycwh = [cx, cy, bbox_width, bbox_height]242                    xywh_bboxs.append(xcycwh)243                    conf = math.ceil(conf*100)/100244                    confs.append(conf)245                    classNameInt = int(cls)246                    oids.append(classNameInt)247                xywhs = torch.tensor(xywh_bboxs)248                confss = torch.tensor(confs)    249                outputs = deepsort.update(xywhs, confss, oids, ims)250                if len(outputs) > 0:251                    bbox_xyxy = outputs[:, :4]252                    identities = outputs[:, -2]253                    object_id = outputs[:, -1]254                    draw_boxes(ims, bbox_xyxy, draw_trails, identities, object_id)255 256            # Stream results257            if view_img:258                if platform.system() == 'Linux' and p not in windows:259                    windows.append(p)260                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)261                    cv2.resizeWindow(str(p), ims.shape[1], ims.shape[0])262                cv2.imshow(str(p), ims)263                cv2.waitKey(1)  # 1 millisecond264            # Save results (image with detections)265            if save_img:266                if vid_path[i] != save_path:  # new video267                    vid_path[i] = save_path268                    if isinstance(vid_writer[i], cv2.VideoWriter):269                        vid_writer[i].release()  # release previous video writer270                    if vid_cap:  # video271                        fps = vid_cap.get(cv2.CAP_PROP_FPS)272                        w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))273                        h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))274                    else:  # stream275                        fps, w, h = 30, ims.shape[1], ims.shape[0]276                    save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos277                    vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('m','p','4','v'), fps, (w, h))278                vid_writer[i].write(ims)279 280        # Print time (inference-only)281        LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")282        frame_counts.append((frame, counts))  # Append the counts for each frame283    transformed_data = []284 285    # Iterate over frame_counts and transform each entry into a row in the DataFrame286    for frame, counts_dict in frame_counts:287        for label, count in counts_dict.items():288            transformed_data.append((frame, label.capitalize(), count))289 290    # Create a DataFrame from the transformed data291    df = pd.DataFrame(transformed_data, columns=['frame', 'label', 'count'])292 293    # Convert count column from tensors to integers294    df['count'] = df['count'].apply(convert_to_int)295 296    counts_df = pd.DataFrame(counts.items(), columns=['label', 'count'])297    counts_df['count'] = counts_df['count'].apply(convert_to_int)298    counts_df['label'] = counts_df['label'].astype(str)  299 300    if update:301        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)302    return save_path, counts_df, df 303 304 305def parse_opt():306    parser = argparse.ArgumentParser()307    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolo.pt', help='model path or triton URL')308    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')309    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')310    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')311    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')312    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')313    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')314    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')315    parser.add_argument('--view-img', action='store_true', help='show results')316    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')317    parser.add_argument('--draw-trails', action='store_true', help='do not drawtrails')318    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')319    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')320    parser.add_argument('--augment', action='store_true', help='augmented inference')321    parser.add_argument('--visualize', action='store_true', help='visualize features')322    parser.add_argument('--update', action='store_true', help='update all models')323    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')324    parser.add_argument('--name', default='exp', help='save results to project/name')325    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')326    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')327    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')328    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')329    opt = parser.parse_args()330    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand331    print_args(vars(opt))332    return opt333 334 335def main(opt):336    # check_requirements(exclude=('tensorboard', 'thop'))337    run_deepsort(**vars(opt))338 339 340 341if __name__ == "__main__":342    opt = parse_opt()343    main(opt)