{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# !pip install -q imagesize\n# !pip install -qU wandb\n# !add-apt-repository ppa:ubuntu-toolchain-r/test -y\n# !apt-get update\n# !apt-get upgrade libstdc++6 -y","metadata":{"_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:14:33.647964Z","iopub.execute_input":"2022-02-13T10:14:33.648278Z","iopub.status.idle":"2022-02-13T10:14:33.669640Z","shell.execute_reply.started":"2022-02-13T10:14:33.648195Z","shell.execute_reply":"2022-02-13T10:14:33.668968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#  Yolov5 + tracking ~ 51++ score.\nMy notebook was combined ideas from great notebook [Awsaf](https://www.kaggle.com/awsaf49/great-barrier-reef-yolov5-infer) and [Aleksandr Snorkin](https://www.kaggle.com/parapapapam/yolox-inference-tracking-on-cots-lb-0-539).\nData was prepared from my previous notebook [data prepare](https://www.kaggle.com/sentrankim/fast-augmentation-by-albumentation-multi-process) + tuning parameter -> So that my notebook was significant improve score on public LB that only used yolov5 algorithm ( yolov5m )\n","metadata":{}},{"cell_type":"code","source":"# norfair dependencies\n%cd /kaggle/input/norfair031py3/\n!pip install commonmark-0.9.1-py2.py3-none-any.whl -f ./ --no-index\n!pip install rich-9.13.0-py3-none-any.whl\n\n!mkdir /kaggle/working/tmp\n!cp -r /kaggle/input/norfair031py3/filterpy-1.4.5/filterpy-1.4.5/ /kaggle/working/tmp/\n%cd /kaggle/working/tmp/filterpy-1.4.5/\n!pip install .\n!rm -rf /kaggle/working/tmp\n\n# norfair\n%cd /kaggle/input/norfair031py3/\n!pip install norfair-0.3.1-py3-none-any.whl -f ./ --no-index\n%cd ..","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:14:33.671614Z","iopub.execute_input":"2022-02-13T10:14:33.671876Z","iopub.status.idle":"2022-02-13T10:15:49.066945Z","shell.execute_reply.started":"2022-02-13T10:14:33.671841Z","shell.execute_reply":"2022-02-13T10:15:49.066097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !cp -r ../input/wbf-ensemble ./\n# %cd wbf-ensemble\n# !pip install setup.py\n# %cd ..","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:15:49.068304Z","iopub.execute_input":"2022-02-13T10:15:49.068597Z","iopub.status.idle":"2022-02-13T10:15:49.072792Z","shell.execute_reply.started":"2022-02-13T10:15:49.068568Z","shell.execute_reply":"2022-02-13T10:15:49.072098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import sys \n# sys.path.append('../input/wbf-ensemble')\n#from ensemble_boxes import *","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:15:49.074193Z","iopub.execute_input":"2022-02-13T10:15:49.074728Z","iopub.status.idle":"2022-02-13T10:15:49.083305Z","shell.execute_reply.started":"2022-02-13T10:15:49.074692Z","shell.execute_reply":"2022-02-13T10:15:49.082567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 📚 Import Libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nfrom tqdm.notebook import tqdm\ntqdm.pandas()\nimport pandas as pd\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport glob\nimport shutil\nimport sys\nsys.path.append('../input/tensorflow-great-barrier-reef')\nimport torch\nfrom PIL import Image\nimport ast\nimport albumentations as albu","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-02-13T10:15:49.087699Z","iopub.execute_input":"2022-02-13T10:15:49.088184Z","iopub.status.idle":"2022-02-13T10:15:52.516323Z","shell.execute_reply.started":"2022-02-13T10:15:49.088147Z","shell.execute_reply":"2022-02-13T10:15:52.515567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT_DIR  = '/kaggle/input/tensorflow-great-barrier-reef/'\nCKPT_PATH = '/kaggle/input/yolov5m6-20-1664-fold1/best(14).pt'\nIMG_SIZE  = int(1664*1.7)\nCONF      = 0.4\nIOU       = 0.5\nAUGMENT   = False\nFDA_aug = False","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:15:52.517753Z","iopub.execute_input":"2022-02-13T10:15:52.520049Z","iopub.status.idle":"2022-02-13T10:15:52.525195Z","shell.execute_reply.started":"2022-02-13T10:15:52.520011Z","shell.execute_reply":"2022-02-13T10:15:52.524265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_path(row):\n    row['image_path'] = f'{ROOT_DIR}/train_images/video_{row.video_id}/{row.video_frame}.jpg'\n    return row","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:15:52.526529Z","iopub.execute_input":"2022-02-13T10:15:52.527076Z","iopub.status.idle":"2022-02-13T10:15:52.539307Z","shell.execute_reply.started":"2022-02-13T10:15:52.527037Z","shell.execute_reply":"2022-02-13T10:15:52.538607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train Data\ndf = pd.read_csv(f'{ROOT_DIR}/train.csv')\ndf = df.progress_apply(get_path, axis=1)\ndf['annotations'] = df['annotations'].progress_apply(lambda x: ast.literal_eval(x))\ndisplay(df.head(2))","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:15:52.540647Z","iopub.execute_input":"2022-02-13T10:15:52.541032Z","iopub.status.idle":"2022-02-13T10:16:08.019983Z","shell.execute_reply.started":"2022-02-13T10:15:52.540998Z","shell.execute_reply":"2022-02-13T10:16:08.019151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FDA_reference = df[df['annotations']!='[]']","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:08.021374Z","iopub.execute_input":"2022-02-13T10:16:08.021653Z","iopub.status.idle":"2022-02-13T10:16:08.037598Z","shell.execute_reply.started":"2022-02-13T10:16:08.021618Z","shell.execute_reply":"2022-02-13T10:16:08.036911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FDA_trans = albu.FDA(FDA_reference['image_path'].values)","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:08.040020Z","iopub.execute_input":"2022-02-13T10:16:08.040457Z","iopub.status.idle":"2022-02-13T10:16:08.044674Z","shell.execute_reply.started":"2022-02-13T10:16:08.040410Z","shell.execute_reply":"2022-02-13T10:16:08.043959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Number of BBoxes","metadata":{}},{"cell_type":"code","source":"df['num_bbox'] = df['annotations'].progress_apply(lambda x: len(x))\ndata = (df.num_bbox>0).value_counts()/len(df)*100\nprint(f\"No BBox: {data[0]:0.2f}% | With BBox: {data[1]:0.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:08.046242Z","iopub.execute_input":"2022-02-13T10:16:08.046934Z","iopub.status.idle":"2022-02-13T10:16:08.147899Z","shell.execute_reply.started":"2022-02-13T10:16:08.046822Z","shell.execute_reply":"2022-02-13T10:16:08.147031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🔨 Helper","metadata":{}},{"cell_type":"code","source":"def voc2yolo(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    voc  => [x1, y1, x2, y1]\n    yolo => [xmid, ymid, w, h] (normalized)\n    \"\"\"\n    \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]/ image_height\n    \n    w = bboxes[..., 2] - bboxes[..., 0]\n    h = bboxes[..., 3] - bboxes[..., 1]\n    \n    bboxes[..., 0] = bboxes[..., 0] + w/2\n    bboxes[..., 1] = bboxes[..., 1] + h/2\n    bboxes[..., 2] = w\n    bboxes[..., 3] = h\n    \n    return bboxes\n\ndef yolo2voc(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    voc  => [x1, y1, x2, y1]\n    \n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n    \n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n    \n    return bboxes\n\ndef coco2yolo(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    coco => [xmin, ymin, w, h]\n    yolo => [xmid, ymid, w, h] (normalized)\n    \"\"\"\n    \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    # normolizinig\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]/ image_height\n    \n    # converstion (xmin, ymin) => (xmid, ymid)\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]/2\n    \n    return bboxes\n\ndef yolo2coco(bboxes, image_height=720, image_width=1280):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    coco => [xmin, ymin, w, h]\n    \n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    \n    # denormalizing\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]* image_height\n    \n    # converstion (xmid, ymid) => (xmin, ymin) \n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    \n    return bboxes\n\ndef voc2coco(bboxes, image_height=720, image_width=1280):\n    bboxes  = voc2yolo(bboxes, image_height, image_width)\n    bboxes  = yolo2coco(bboxes, image_height, image_width)\n    return bboxes\n\n\ndef load_image(image_path):\n    return cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None):\n    # Plots one bounding box on image img\n    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness\n    color = color or [random.randint(0, 255) for _ in range(3)]\n    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n    if label:\n        tf = max(tl - 1, 1)  # font thickness\n        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled\n        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\ndef draw_bboxes(img, bboxes, classes, class_ids, colors = None, show_classes = None, bbox_format = 'yolo', class_name = False, line_thickness = 2):  \n     \n    image = img.copy()\n    show_classes = classes if show_classes is None else show_classes\n    colors = (0, 255 ,0) if colors is None else colors\n    \n    if bbox_format == 'yolo':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes:\n            \n                x1 = round(float(bbox[0])*image.shape[1])\n                y1 = round(float(bbox[1])*image.shape[0])\n                w  = round(float(bbox[2])*image.shape[1]/2) #w/2 \n                h  = round(float(bbox[3])*image.shape[0]/2)\n\n                voc_bbox = (x1-w, y1-h, x1+w, y1+h)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(get_label(cls)),\n                             line_thickness = line_thickness)\n            \n    elif bbox_format == 'coco':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes:            \n                x1 = int(round(bbox[0]))\n                y1 = int(round(bbox[1]))\n                w  = int(round(bbox[2]))\n                h  = int(round(bbox[3]))\n\n                voc_bbox = (x1, y1, x1+w, y1+h)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(cls_id),\n                             line_thickness = line_thickness)\n\n    elif bbox_format == 'voc_pascal':\n        \n        for idx in range(len(bboxes)):  \n            \n            bbox  = bboxes[idx]\n            cls   = classes[idx]\n            cls_id = class_ids[idx]\n            color = colors[cls_id] if type(colors) is list else colors\n            \n            if cls in show_classes: \n                x1 = int(round(bbox[0]))\n                y1 = int(round(bbox[1]))\n                x2 = int(round(bbox[2]))\n                y2 = int(round(bbox[3]))\n                voc_bbox = (x1, y1, x2, y2)\n                plot_one_box(voc_bbox, \n                             image,\n                             color = color,\n                             label = cls if class_name else str(cls_id),\n                             line_thickness = line_thickness)\n    else:\n        raise ValueError('wrong bbox format')\n\n    return image\n\ndef get_bbox(annots):\n    bboxes = [list(annot.values()) for annot in annots]\n    return bboxes\n\ndef get_imgsize(row):\n    row['width'], row['height'] = imagesize.get(row['image_path'])\n    return row\n\nnp.random.seed(32)\ncolors = [(np.random.randint(255), np.random.randint(255), np.random.randint(255))\\\n          for idx in range(1)]","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:08.149417Z","iopub.execute_input":"2022-02-13T10:16:08.149876Z","iopub.status.idle":"2022-02-13T10:16:08.187224Z","shell.execute_reply.started":"2022-02-13T10:16:08.149840Z","shell.execute_reply":"2022-02-13T10:16:08.186464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"##############################################################\n#                      Tracking helpers                      #\n##############################################################\n\nimport numpy as np\nfrom norfair import Detection, Tracker\n\n# Helper to convert bbox in format [x_min, y_min, x_max, y_max, score] to norfair.Detection class\ndef to_norfair(detects, frame_id):\n    result = []\n    for x_min, y_min, x_max, y_max, score in detects:\n        xc, yc = (x_min + x_max) / 2, (y_min + y_max) / 2\n        w, h = x_max - x_min, y_max - y_min\n        result.append(Detection(points=np.array([xc, yc]), scores=np.array([score]), data=np.array([w, h, frame_id])))\n        \n    return result\n\n# Euclidean distance function to match detections on this frame with tracked_objects from previous frames\ndef euclidean_distance(detection, tracked_object):\n    return np.linalg.norm(detection.points - tracked_object.estimate)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:08.188825Z","iopub.execute_input":"2022-02-13T10:16:08.189169Z","iopub.status.idle":"2022-02-13T10:16:08.244643Z","shell.execute_reply.started":"2022-02-13T10:16:08.189108Z","shell.execute_reply":"2022-02-13T10:16:08.243897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir -p /root/.config/Ultralytics\n!cp /kaggle/input/yolov5-font/Arial.ttf /root/.config/Ultralytics/","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:08.247743Z","iopub.execute_input":"2022-02-13T10:16:08.247995Z","iopub.status.idle":"2022-02-13T10:16:09.601861Z","shell.execute_reply.started":"2022-02-13T10:16:08.247968Z","shell.execute_reply":"2022-02-13T10:16:09.600789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_model(ckpt_path, conf=0.25, iou=0.50):\n    model = torch.hub.load('/kaggle/input/yolov5-lib-ds',\n                           'custom',\n                           path=ckpt_path,\n                           source='local',\n                           force_reload=True)  # local repo\n    model.conf = conf  # NMS confidence threshold\n    model.iou  = iou  # NMS IoU threshold\n    model.classes = None   # (optional list) filter by class, i.e. = [0, 15, 16] for persons, cats and dogs\n    model.multi_label = False  # NMS multiple labels per box\n    model.max_det = 1000  # maximum number of detections per image\n    return model","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:09.603544Z","iopub.execute_input":"2022-02-13T10:16:09.603834Z","iopub.status.idle":"2022-02-13T10:16:09.609926Z","shell.execute_reply.started":"2022-02-13T10:16:09.603793Z","shell.execute_reply":"2022-02-13T10:16:09.609148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🔭 Inference","metadata":{}},{"cell_type":"markdown","source":"## Helper","metadata":{}},{"cell_type":"code","source":"def predict(model, img, size=768, augment=False):\n    height, width = img.shape[:2]\n    results = model(img, size=size, augment=augment)  # custom inference size\n    preds   = results.pandas().xyxy[0]\n    bboxes  = preds[['xmin','ymin','xmax','ymax']].values\n    if len(bboxes):\n        bboxes  = voc2coco(bboxes,height,width).astype(int)\n        confs   = preds.confidence.values\n        return bboxes, confs\n    else:\n        return [],[]\n    \ndef format_prediction(bboxes, confs):\n    annot = ''\n    if len(bboxes)>0:\n        for idx in range(len(bboxes)):\n            xmin, ymin, w, h = bboxes[idx]\n            conf             = confs[idx]\n            annot += f'{conf} {xmin} {ymin} {w} {h}'\n            annot +=' '\n        annot = annot.strip(' ')\n    return annot\n\ndef show_img(img, bboxes, bbox_format='yolo'):\n    names  = ['starfish']*len(bboxes)\n    labels = [0]*len(bboxes)\n    img    = draw_bboxes(img = img,\n                           bboxes = bboxes, \n                           classes = names,\n                           class_ids = labels,\n                           class_name = True, \n                           colors = colors, \n                           bbox_format = bbox_format,\n                           line_thickness = 2)\n    return Image.fromarray(img).resize((800, 400))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:09.611487Z","iopub.execute_input":"2022-02-13T10:16:09.611962Z","iopub.status.idle":"2022-02-13T10:16:09.627116Z","shell.execute_reply.started":"2022-02-13T10:16:09.611923Z","shell.execute_reply":"2022-02-13T10:16:09.626244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def tracking_function(tracker, frame_id, bboxes, scores):\n    \n    detects = []\n    predictions = []\n    \n    if len(scores)>0:\n        for i in range(len(bboxes)):\n            box = bboxes[i]\n            score = scores[i]\n            x_min = int(box[0])\n            y_min = int(box[1])\n            bbox_width = int(box[2])\n            bbox_height = int(box[3])\n            detects.append([x_min, y_min, x_min+bbox_width, y_min+bbox_height, score])\n            predictions.append('{:.2f} {} {} {} {}'.format(score, x_min, y_min, bbox_width, bbox_height))\n#             print(predictions[:-1])\n    # Update tracks using detects from current frame\n    tracked_objects = tracker.update(detections=to_norfair(detects, frame_id))\n    for tobj in tracked_objects:\n        bbox_width, bbox_height, last_detected_frame_id = tobj.last_detection.data\n        if last_detected_frame_id == frame_id:  # Skip objects that were detected on current frame\n            continue\n        # Add objects that have no detections on current frame to predictions\n        xc, yc = tobj.estimate[0]\n        x_min, y_min = int(round(xc - bbox_width / 2)), int(round(yc - bbox_height / 2))\n        score = tobj.last_detection.scores[0]\n\n        predictions.append('{:.2f} {} {} {} {}'.format(score, x_min, y_min, bbox_width, bbox_height))\n        \n    return predictions","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:09.630742Z","iopub.execute_input":"2022-02-13T10:16:09.632991Z","iopub.status.idle":"2022-02-13T10:16:09.644324Z","shell.execute_reply.started":"2022-02-13T10:16:09.632950Z","shell.execute_reply":"2022-02-13T10:16:09.643566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Run Inference on **Train**","metadata":{}},{"cell_type":"code","source":"def CLAHE(image):\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    equalized = clahe.apply(gray)\n    return equalized\ndef Gamma_enhancement(image):\n    gamma = 1/0.6\n    R = 255.0\n    return (R * np.power(image.astype(np.uint32)/R, gamma)).astype(np.uint8)\n","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:09.646455Z","iopub.execute_input":"2022-02-13T10:16:09.647418Z","iopub.status.idle":"2022-02-13T10:16:09.655479Z","shell.execute_reply.started":"2022-02-13T10:16:09.647315Z","shell.execute_reply":"2022-02-13T10:16:09.654654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tracker = Tracker(\n    distance_function=euclidean_distance, \n    distance_threshold=30,\n    hit_inertia_min=3,\n    hit_inertia_max=6,\n    initialization_delay=1,\n)\n\nmodel = load_model(CKPT_PATH, conf=CONF, iou=IOU)\nimage_paths = df[df.num_bbox>1].sample(100).image_path.tolist()\nframe_id = 0\nfor idx, path in enumerate(image_paths):\n    img = cv2.imread(path)[...,::-1]\n    if FDA_aug:\n        img = FDA_trans(image=img)['image']\n    bboxes, confis = predict(model, img, size=IMG_SIZE, augment=AUGMENT)\n    predict_box = tracking_function(tracker, frame_id, bboxes, confis)\n\n    if len(predict_box)>0:\n        box = [list(map(int,box.split(' ')[1:])) for box in predict_box]\n    else:\n        box = []\n    display(show_img(img, box, bbox_format='coco'))\n    if idx>5:\n        break\n    frame_id += 1","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:09.656983Z","iopub.execute_input":"2022-02-13T10:16:09.657610Z","iopub.status.idle":"2022-02-13T10:16:22.829243Z","shell.execute_reply.started":"2022-02-13T10:16:09.657572Z","shell.execute_reply":"2022-02-13T10:16:22.828483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Init `Env`","metadata":{}},{"cell_type":"code","source":"import greatbarrierreef\nenv = greatbarrierreef.make_env()# initialize the environment\niter_test = env.iter_test()      # an iterator which loops over the test set and sample submission","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:22.830777Z","iopub.execute_input":"2022-02-13T10:16:22.831143Z","iopub.status.idle":"2022-02-13T10:16:22.862069Z","shell.execute_reply.started":"2022-02-13T10:16:22.831108Z","shell.execute_reply":"2022-02-13T10:16:22.861297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd ../working","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:22.864819Z","iopub.execute_input":"2022-02-13T10:16:22.865038Z","iopub.status.idle":"2022-02-13T10:16:22.871098Z","shell.execute_reply.started":"2022-02-13T10:16:22.865014Z","shell.execute_reply":"2022-02-13T10:16:22.870180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Run Inference on **Test**","metadata":{}},{"cell_type":"code","source":"tracker = Tracker(\n    distance_function=euclidean_distance, \n    distance_threshold=30,\n    hit_inertia_min=3,\n    hit_inertia_max=6,\n    initialization_delay=1,\n)\n\nmodel = load_model(CKPT_PATH, conf=CONF, iou=IOU)\n\nframe_id =0\nfor idx, (img, pred_df) in enumerate(tqdm(iter_test)):\n    if FDA_aug:\n        img = FDA_trans(image=img)['image']\n    bboxes, confs  = predict(model, img, size=IMG_SIZE, augment=AUGMENT)\n\n    predictions = tracking_function(tracker, frame_id, bboxes, confs)\n    \n    prediction_str = ' '.join(predictions)\n    pred_df['annotations'] = prediction_str\n    env.predict(pred_df)\n    if frame_id < 3:\n        if len(predict_box)>0:\n            box = [list(map(int,box.split(' ')[1:])) for box in predictions]\n        else:\n            box = []\n        display(show_img(img, box, bbox_format='coco'))\n#     print('Prediction:', pred_df)\n    frame_id += 1\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-13T10:16:22.872904Z","iopub.execute_input":"2022-02-13T10:16:22.873811Z","iopub.status.idle":"2022-02-13T10:16:24.902359Z","shell.execute_reply.started":"2022-02-13T10:16:22.873774Z","shell.execute_reply":"2022-02-13T10:16:24.901434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 👀 Check Submission","metadata":{}},{"cell_type":"code","source":"sub_df = pd.read_csv('submission.csv')\nsub_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-13T10:16:24.904191Z","iopub.execute_input":"2022-02-13T10:16:24.904480Z","iopub.status.idle":"2022-02-13T10:16:24.917934Z","shell.execute_reply.started":"2022-02-13T10:16:24.904443Z","shell.execute_reply":"2022-02-13T10:16:24.917339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Please Upvote if you find this Helpful","metadata":{}}]}