{"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":"markdown","source":"## Reference - https://www.kaggle.com/yamqwe/great-barrier-reef-yolox-yolov5-ensemble","metadata":{}},{"cell_type":"code","source":"import warnings; warnings.filterwarnings(\"ignore\")\n\nimport os\nimport cv2\nimport ast\nimport sys\nimport glob\nimport torch\nimport shutil\nimport importlib\nimport traceback\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\nsys.path.append('../input/tensorflow-great-barrier-reef')\ntqdm.pandas()\n\nfrom PIL import Image\nfrom IPython.display import display\nfrom tqdm.notebook import tqdm\ntqdm.pandas()\n","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:24:59.274218Z","iopub.execute_input":"2022-02-14T05:24:59.274817Z","iopub.status.idle":"2022-02-14T05:25:00.927621Z","shell.execute_reply.started":"2022-02-14T05:24:59.274727Z","shell.execute_reply":"2022-02-14T05:25:00.926880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Install YoloX","metadata":{}},{"cell_type":"code","source":"%cp -r /kaggle/input/yolox-cots-models /kaggle/working/\n%cd /kaggle/working/yolox-cots-models/yolox-dep","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:25:00.929462Z","iopub.execute_input":"2022-02-14T05:25:00.929714Z","iopub.status.idle":"2022-02-14T05:25:17.888092Z","shell.execute_reply.started":"2022-02-14T05:25:00.929680Z","shell.execute_reply":"2022-02-14T05:25:17.887067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install YOLOX required modules\n!pip install pip-21.3.1-py3-none-any.whl -f ./ --no-index\n!pip install loguru-0.5.3-py3-none-any.whl -f ./ --no-index\n!pip install ninja-1.10.2.3-py2.py3-none-manylinux_2_5_x86_64.manylinux1_x86_64.whl -f ./ --no-index\n!pip install onnx-1.8.1-cp37-cp37m-manylinux2010_x86_64.whl -f ./ --no-index\n!pip install onnxruntime-1.8.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl -f ./ --no-index\n!pip install onnxoptimizer-0.2.6-cp37-cp37m-manylinux2014_x86_64.whl -f ./ --no-index\n!pip install thop-0.0.31.post2005241907-py3-none-any.whl -f ./ --no-index\n!pip install tabulate-0.8.9-py3-none-any.whl -f ./ --no-index","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:25:17.890183Z","iopub.execute_input":"2022-02-14T05:25:17.890796Z","iopub.status.idle":"2022-02-14T05:26:24.952053Z","shell.execute_reply.started":"2022-02-14T05:25:17.890753Z","shell.execute_reply":"2022-02-14T05:26:24.951215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install YOLOX\n%cd /kaggle/working/yolox-cots-models/YOLOX\n!pip install -r requirements.txt\n!pip install -v -e . ","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-14T05:26:24.956015Z","iopub.execute_input":"2022-02-14T05:26:24.956243Z","iopub.status.idle":"2022-02-14T05:27:45.841643Z","shell.execute_reply.started":"2022-02-14T05:26:24.956215Z","shell.execute_reply":"2022-02-14T05:27:45.840568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install CocoAPI tool\n%cd /kaggle/working/yolox-cots-models/yolox-dep/cocoapi/PythonAPI\n!make\n!make install\n!python setup.py install","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-02-14T05:27:45.844717Z","iopub.execute_input":"2022-02-14T05:27:45.845287Z","iopub.status.idle":"2022-02-14T05:28:11.583409Z","shell.execute_reply.started":"2022-02-14T05:27:45.845237Z","shell.execute_reply":"2022-02-14T05:28:11.582478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pycocotools","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:28:11.585896Z","iopub.execute_input":"2022-02-14T05:28:11.586430Z","iopub.status.idle":"2022-02-14T05:28:11.592296Z","shell.execute_reply.started":"2022-02-14T05:28:11.586380Z","shell.execute_reply":"2022-02-14T05:28:11.591429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:28:11.593910Z","iopub.execute_input":"2022-02-14T05:28:11.594224Z","iopub.status.idle":"2022-02-14T05:29:27.354625Z","shell.execute_reply.started":"2022-02-14T05:28:11.594184Z","shell.execute_reply":"2022-02-14T05:29:27.353665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## YoloX","metadata":{}},{"cell_type":"code","source":"%cd /kaggle/working/yolox-cots-models/YOLOX\n\n# CHECKPOINT_FILE = '/kaggle/input/cotsyoloxse40ap2534stratifiedk/YOLOX_outputs/cots_config/best_ckpt.pth'\nCHECKPOINT_FILE = '/kaggle/working/yolox-cots-models/yx_l_003.pth'","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:27.356612Z","iopub.execute_input":"2022-02-14T05:29:27.356889Z","iopub.status.idle":"2022-02-14T05:29:27.366838Z","shell.execute_reply.started":"2022-02-14T05:29:27.356851Z","shell.execute_reply":"2022-02-14T05:29:27.366057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"config_file_template = '''\n\n#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) Megvii, Inc. and its affiliates.\n\nimport os\n\nfrom yolox.exp import Exp as MyExp\n\n\nclass Exp(MyExp):\n    def __init__(self):\n        super(Exp, self).__init__()\n        self.depth = 1\n        self.width = 1\n        self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n        self.num_classes = 1\n\n'''\n\nwith open('cots_config.py', 'w') as f:\n    f.write(config_file_template)","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:27.368508Z","iopub.execute_input":"2022-02-14T05:29:27.369022Z","iopub.status.idle":"2022-02-14T05:29:27.374906Z","shell.execute_reply.started":"2022-02-14T05:29:27.368986Z","shell.execute_reply":"2022-02-14T05:29:27.374021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from yolox.utils import postprocess\nfrom yolox.data.data_augment import ValTransform\n\nCOCO_CLASSES = (\n  \"starfish\",\n)\n\n# get YOLOX experiment\ncurrent_exp = importlib.import_module('cots_config')\nexp = current_exp.Exp()\n\n# set inference parameters\ntest_size = (800, 1280)\nnum_classes = 1\nconfthre = 0.2\nnmsthre = 0.2\n\n\n# get YOLOX model\nyolox_model = exp.get_model()\nyolox_model.cuda()\nyolox_model.eval()\n\n# get custom trained checkpoint\nckpt_file = CHECKPOINT_FILE\nckpt = torch.load(ckpt_file, map_location=\"cpu\")\nyolox_model.load_state_dict(ckpt[\"model\"])","metadata":{"_kg_hide-input":false,"execution":{"iopub.status.busy":"2022-02-14T05:29:27.379157Z","iopub.execute_input":"2022-02-14T05:29:27.379406Z","iopub.status.idle":"2022-02-14T05:29:31.775375Z","shell.execute_reply.started":"2022-02-14T05:29:27.379375Z","shell.execute_reply":"2022-02-14T05:29:31.774534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def yolox_inference(img, model, test_size): \n    bboxes = []\n    bbclasses = []\n    scores = []\n    \n    preproc = ValTransform(legacy = False)\n\n    tensor_img, _ = preproc(img, None, test_size)\n    tensor_img = torch.from_numpy(tensor_img).unsqueeze(0)\n    tensor_img = tensor_img.float()\n    tensor_img = tensor_img.cuda()\n\n    with torch.no_grad():\n        outputs = model(tensor_img)\n        outputs = postprocess(\n                    outputs, num_classes, confthre,\n                    nmsthre, class_agnostic=True\n                )\n\n    if outputs[0] is None:\n        return [], [], []\n    \n    outputs = outputs[0].cpu()\n    bboxes = outputs[:, 0:4]\n\n    bboxes /= min(test_size[0] / img.shape[0], test_size[1] / img.shape[1])\n    bbclasses = outputs[:, 6]\n    scores = outputs[:, 4] * outputs[:, 5]\n    \n    return bboxes, bbclasses, scores","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:31.776956Z","iopub.execute_input":"2022-02-14T05:29:31.777489Z","iopub.status.idle":"2022-02-14T05:29:31.787579Z","shell.execute_reply.started":"2022-02-14T05:29:31.777446Z","shell.execute_reply":"2022-02-14T05:29:31.786789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def draw_yolox_predictions(img, bboxes, scores, bbclasses, confthre, classes_dict):\n    for i in range(len(bboxes)):\n            box = bboxes[i]\n            cls_id = int(bbclasses[i])\n            score = scores[i]\n            if score < confthre:\n                continue\n            x0 = int(box[0])\n            y0 = int(box[1])\n            x1 = int(box[2])\n            y1 = int(box[3])\n\n            cv2.rectangle(img, (x0, y0), (x1, y1), (0, 255, 0), 2)\n            cv2.putText(img, '{}:{:.1f}%'.format(classes_dict[cls_id], score * 100), (x0, y0 - 3), cv2.FONT_HERSHEY_PLAIN, 0.8, (0,255,0), thickness = 1)\n    return img","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:31.788748Z","iopub.execute_input":"2022-02-14T05:29:31.789425Z","iopub.status.idle":"2022-02-14T05:29:31.803427Z","shell.execute_reply.started":"2022-02-14T05:29:31.789387Z","shell.execute_reply":"2022-02-14T05:29:31.802257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## YoloV5","metadata":{}},{"cell_type":"code","source":"ROOT_DIR  = '/kaggle/input/tensorflow-great-barrier-reef/'\nCKPT_PATH = '/kaggle/input/yolov5m6/best(1).pt'\nIMG_SIZE  = 6000\nCONF      = 0.01\nIOU       = 0.4\nAUGMENT   = True","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:31.804909Z","iopub.execute_input":"2022-02-14T05:29:31.805469Z","iopub.status.idle":"2022-02-14T05:29:31.812337Z","shell.execute_reply.started":"2022-02-14T05:29:31.805427Z","shell.execute_reply":"2022-02-14T05:29:31.811492Z"},"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-14T05:29:31.815517Z","iopub.execute_input":"2022-02-14T05:29:31.816120Z","iopub.status.idle":"2022-02-14T05:29:31.821287Z","shell.execute_reply.started":"2022-02-14T05:29:31.816077Z","shell.execute_reply":"2022-02-14T05:29:31.820394Z"},"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))\ndf['num_bbox'] = df['annotations'].progress_apply(lambda x: len(x))\ndata = (df.num_bbox>0).value_counts()/len(df)*100","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:31.822846Z","iopub.execute_input":"2022-02-14T05:29:31.823495Z","iopub.status.idle":"2022-02-14T05:29:48.039447Z","shell.execute_reply.started":"2022-02-14T05:29:31.823455Z","shell.execute_reply":"2022-02-14T05:29:48.037587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]/ image_height\n    w = bboxes[..., 2] - bboxes[..., 0]\n    h = bboxes[..., 3] - bboxes[..., 1]\n    bboxes[..., 0] = bboxes[..., 0] + w/2\n    bboxes[..., 1] = bboxes[..., 1] + h/2\n    bboxes[..., 2] = w\n    bboxes[..., 3] = h\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    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\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    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    # normolizinig\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]/ image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]/ image_height\n    # converstion (xmin, ymin) => (xmid, ymid)\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]/2\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    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n    # denormalizing\n    bboxes[..., [0, 2]]= bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]]= bboxes[..., [1, 3]]* image_height\n    # converstion (xmid, ymid) => (xmin, ymin)\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\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\ndef load_image(image_path):\n    return cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\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-14T05:29:48.040964Z","iopub.execute_input":"2022-02-14T05:29:48.041545Z","iopub.status.idle":"2022-02-14T05:29:48.082076Z","shell.execute_reply.started":"2022-02-14T05:29:48.041505Z","shell.execute_reply":"2022-02-14T05:29:48.081244Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:48.083092Z","iopub.execute_input":"2022-02-14T05:29:48.084545Z","iopub.status.idle":"2022-02-14T05:29:48.765702Z","shell.execute_reply.started":"2022-02-14T05:29:48.084513Z","shell.execute_reply":"2022-02-14T05:29:48.764972Z"},"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":{"execution":{"iopub.status.busy":"2022-02-14T05:29:48.766955Z","iopub.execute_input":"2022-02-14T05:29:48.767212Z","iopub.status.idle":"2022-02-14T05:29:49.095526Z","shell.execute_reply.started":"2022-02-14T05:29:48.767179Z","shell.execute_reply":"2022-02-14T05:29:49.094506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_model(ckpt_path, conf=0.15, iou=0.20):\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":{"execution":{"iopub.status.busy":"2022-02-14T05:29:49.097865Z","iopub.execute_input":"2022-02-14T05:29:49.098359Z","iopub.status.idle":"2022-02-14T05:29:49.105272Z","shell.execute_reply.started":"2022-02-14T05:29:49.098298Z","shell.execute_reply":"2022-02-14T05:29:49.104369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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', bbox_colors = None):\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 if bbox_colors is None else bbox_colors,\n                           bbox_format = bbox_format,\n                           line_thickness = 2)\n    return Image.fromarray(img).resize((800, 400))","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:49.107233Z","iopub.execute_input":"2022-02-14T05:29:49.107505Z","iopub.status.idle":"2022-02-14T05:29:49.122759Z","shell.execute_reply.started":"2022-02-14T05:29:49.107471Z","shell.execute_reply":"2022-02-14T05:29:49.121900Z"},"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            if score > 0.15:\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        if last_detected_frame_id + 1 != frame_id:  # Track only one frame forward\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\n\n","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:49.124485Z","iopub.execute_input":"2022-02-14T05:29:49.125052Z","iopub.status.idle":"2022-02-14T05:29:49.136211Z","shell.execute_reply.started":"2022-02-14T05:29:49.125014Z","shell.execute_reply":"2022-02-14T05:29:49.135454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:49.137800Z","iopub.execute_input":"2022-02-14T05:29:49.138281Z","iopub.status.idle":"2022-02-14T05:29:49.150291Z","shell.execute_reply.started":"2022-02-14T05:29:49.138245Z","shell.execute_reply":"2022-02-14T05:29:49.149485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Ensembling + Tracking on Train","metadata":{}},{"cell_type":"code","source":"import sys; sys.path.append('/kaggle/input/weightedboxesfusion/')","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:49.153267Z","iopub.execute_input":"2022-02-14T05:29:49.154104Z","iopub.status.idle":"2022-02-14T05:29:49.158870Z","shell.execute_reply.started":"2022-02-14T05:29:49.154064Z","shell.execute_reply":"2022-02-14T05:29:49.158160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = load_model(CKPT_PATH, conf=CONF, iou=IOU)","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:49.160239Z","iopub.execute_input":"2022-02-14T05:29:49.160642Z","iopub.status.idle":"2022-02-14T05:29:57.136204Z","shell.execute_reply.started":"2022-02-14T05:29:49.160607Z","shell.execute_reply":"2022-02-14T05:29:57.135460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def run_wbf(bboxes, confs, image_size=512, iou_thr=0.2, skip_box_thr=0.001, weights=None):\n    boxes =  [bbox/(image_size-1) for bbox in bboxes]\n    scores = [conf for conf in confs]    \n    labels = [np.ones(conf.shape[0]) for conf in confs]\n    boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr)\n    boxes = boxes*(image_size-1)\n    return boxes, scores, labels\n\nfrom ensemble_boxes import *","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:57.137756Z","iopub.execute_input":"2022-02-14T05:29:57.138331Z","iopub.status.idle":"2022-02-14T05:29:57.167211Z","shell.execute_reply.started":"2022-02-14T05:29:57.138274Z","shell.execute_reply":"2022-02-14T05:29:57.166570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# TEST_IMAGE_PATH = \"/kaggle/input/tensorflow-great-barrier-reef/train_images/video_0/9674.jpg\"\n\n# from ensemble_boxes import *\n\n# def run_wbf(bboxes, confs, image_size=512, iou_thr=0.2, skip_box_thr=0.001, weights=None):\n#     boxes =  [bbox/(image_size-1) for bbox in bboxes]\n#     scores = [conf for conf in confs]    \n#     labels = [np.ones(conf.shape[0]) for conf in confs]\n#     boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr)\n#     boxes = boxes*(image_size-1)\n#     return boxes, scores, labels\n\n# model = load_model(CKPT_PATH, conf=CONF, iou=IOU)\n# image_paths = df[df.num_bbox>1].sample(3).image_path.tolist()\n\n# 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\n# frame_id =0\n# for idx, path in enumerate(image_paths):\n#     img = cv2.imread(path)[...,::-1]\n    \n#     bboxes_1, bbclasses, scores = yolox_inference(img[...,::-1], yolox_model, test_size)        \n#     bboxes_2, confis = predict(model, img, size=IMG_SIZE, augment=AUGMENT)        \n#     pred_1, pred_2 = voc2coco(bboxes_1.detach().numpy(),img.shape[1],img.shape[2]).astype(int), bboxes_2\n#     print(pred_1)\n#     print(pred_2)\n#     print(scores)\n#     print(confis)\n#     if len(pred_1) > 0 and len(pred_2) > 0: boxes, scores, labels = run_wbf([pred_1, pred_2], [scores, confis], image_size = IMG_SIZE)\n#     elif len(pred_1) > 0: boxes, scores = bboxes_1.detach().numpy(), scores\n#     elif len(pred_2) > 0: boxes, scores = bboxes_2.detach().numpy(), confis\n        \n#     predictions = tracking_function(tracker, frame_id, boxes, scores)\n    \n#     if frame_id < 7:\n#         if len(predictions)>0:\n#             box = [list(map(int,box.split(' ')[1:])) for box in predictions]\n#         else:\n#             box = []\n#         print('\\n Tracking')\n#         display(show_img(img, box, bbox_format='coco'))\n\n#     frame_id += 1   \n#     print('\\nEnsemble (WBF) Predictions: ')\n#     display(show_img(img, boxes, bbox_format='coco'))\n#     print(\"******************************************************************\")\n    \n#     if idx>5:\n#         break","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:57.168466Z","iopub.execute_input":"2022-02-14T05:29:57.168721Z","iopub.status.idle":"2022-02-14T05:29:57.174518Z","shell.execute_reply.started":"2022-02-14T05:29:57.168688Z","shell.execute_reply":"2022-02-14T05:29:57.173467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tracker1 = 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)\ntracker2 = 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)\ntracker3 = 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)","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:57.175977Z","iopub.execute_input":"2022-02-14T05:29:57.176551Z","iopub.status.idle":"2022-02-14T05:29:57.184551Z","shell.execute_reply.started":"2022-02-14T05:29:57.176507Z","shell.execute_reply":"2022-02-14T05:29:57.183689Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"frame_id_1 = 0\nframe_id_2 = 0 \nframe_id_3 = 0\n\nimage_paths = df[df.num_bbox>1].sample(100).image_path.tolist()\nfor idx, path in enumerate(image_paths):\n    img = cv2.imread(path)[...,::-1]\n    conf1 = []\n    conf2 = []\n    tmp1 = []\n    tmp2 = []\n    bboxes_1, bbclasses, scores = yolox_inference(img[...,::-1], yolox_model, test_size)  \n    bboxes_1 = voc2coco(bboxes_1.detach().numpy(),img.shape[1],img.shape[2]).astype(int) #change to coco\n#     scores = scores.detach().numpy().reshape((1,len(scores)))[0]\n    \n    bboxes_2, confis = predict(model, img, size=IMG_SIZE, augment=AUGMENT)\n#     print(bboxes_1)\n    \n    pred_1 =  tracking_function(tracker1, frame_id_1, bboxes_1, scores)\n    pred_2 =  tracking_function(tracker2, frame_id_2, bboxes_2, confis)\n#     print(pred_1)\n#     print(pred_2)\n    \n    box1 = [list(map(int,box.split(' ')[1:])) for box in pred_1]\n    box2 = [list(map(int,box.split(' ')[1:])) for box in pred_2]\n\n    \n    for box in pred_1:\n        conf1.append(float(box.split(' ')[0]))\n    conf1 = np.asarray(conf1)\n    for box in pred_2:\n        conf2.append(float(box.split(' ')[0]))\n    conf2 = np.asarray(conf2)\n#     print(conf1)\n#     print(conf2)\n\n    for i in box1:\n        a = []\n        for j in i :\n            a.append(j)\n        c = np.asarray(a)\n        tmp1.append(c)\n    box1 = np.asarray(tmp1)\n    \n    for i in box2:\n        a = []\n        for j in i :\n            a.append(j)\n        c = np.asarray(a)\n        tmp2.append(c)\n    box2 = np.asarray(tmp2)\n#     print(box1)\n#     print(box2)\n\n    boxes, scores, labels = run_wbf([box1,box2], [conf1,conf2], image_size = 512)\n#     print(boxes)\n    predictions = tracking_function(tracker3, frame_id_3, boxes, scores)\n#     print(predictions)\n    \n    print('\\nEnsemble (WBF) Predictions: ')\n    display(show_img(img, boxes, bbox_format='coco'))\n    \n    if frame_id_1 < 7:\n        if len(predictions)>0:\n            box = [list(map(int,box.split(' ')[1:])) for box in predictions]\n        else:\n            box = []\n        print('\\n Tracking')\n        display(show_img(img, box, bbox_format='coco'))\n    print('--------------------------------------')\n    frame_id_1 += 1   \n    frame_id_2 += 1\n    frame_id_3 += 1\n    \n    if idx>5:\n        break","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:29:57.189262Z","iopub.execute_input":"2022-02-14T05:29:57.189790Z","iopub.status.idle":"2022-02-14T05:30:07.275845Z","shell.execute_reply.started":"2022-02-14T05:29:57.189761Z","shell.execute_reply":"2022-02-14T05:30:07.275185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submit Prediction","metadata":{}},{"cell_type":"code","source":"%cd /kaggle/working/\nimport greatbarrierreef\n\nenv = greatbarrierreef.make_env()   # initialize the environment\niter_test = env.iter_test()  ","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:30:07.277040Z","iopub.execute_input":"2022-02-14T05:30:07.277404Z","iopub.status.idle":"2022-02-14T05:30:07.305988Z","shell.execute_reply.started":"2022-02-14T05:30:07.277368Z","shell.execute_reply":"2022-02-14T05:30:07.305044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tracker1 = 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)\ntracker2 = 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)\ntracker3 = 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)","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:30:07.307300Z","iopub.execute_input":"2022-02-14T05:30:07.307783Z","iopub.status.idle":"2022-02-14T05:30:07.313966Z","shell.execute_reply.started":"2022-02-14T05:30:07.307742Z","shell.execute_reply":"2022-02-14T05:30:07.313085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_dict = {\n    'id': [],\n    'prediction_string': [],\n}\nframe_id_1 = 0 \nframe_id_2 = 0 \nframe_id_3 = 0\nfor (image_np, pred_df) in iter_test:\n    \n    conf1 = []\n    conf2 = []\n    tmp1 = []\n    tmp2 = []   \n    \n    bboxes_1, bbclasses, scores = yolox_inference(image_np[...,::-1], yolox_model, test_size)\n    bboxes_2, confis = predict(model, image_np, size=IMG_SIZE, augment=AUGMENT)  \n    print(bboxes_1)\n    print(bboxes_2)\n    if len(bboxes_1) > 0 and len(bboxes_2) > 0: \n        bboxes_1, bboxes_2 = voc2coco(bboxes_1.detach().numpy(), image_np.shape[1],image_np.shape[2]).astype(int), bboxes_2\n        pred_1 =  tracking_function(tracker1, frame_id_1, bboxes_1, scores)\n        pred_2 =  tracking_function(tracker2, frame_id_2, bboxes_2, confis)\n\n        box1 = [list(map(int,box.split(' ')[1:])) for box in pred_1]\n        box2 = [list(map(int,box.split(' ')[1:])) for box in pred_2]\n\n\n        for box in pred_1:\n            conf1.append(float(box.split(' ')[0]))\n        conf1 = np.asarray(conf1)\n        for box in pred_2:\n            conf2.append(float(box.split(' ')[0]))\n        conf2 = np.asarray(conf2)\n    #     print(conf1)\n    #     print(conf2)\n\n        for i in box1:\n            a = []\n            for j in i :\n                a.append(j)\n            c = np.asarray(a)\n            tmp1.append(c)\n        box1 = np.asarray(tmp1)\n\n        for i in box2:\n            a = []\n            for j in i :\n                a.append(j)\n            c = np.asarray(a)\n            tmp2.append(c)\n        box2 = np.asarray(tmp2)\n    #     print(box1)\n    #     print(box2)\n\n        bboxes, scores, labels = run_wbf([box1,box2], [conf1,conf2], image_size = IMG_SIZE)\n#         bboxes, scores, labels = run_wbf([pred_1, pred_2], [scores, confis], image_size = IMG_SIZE)\n    elif len(bboxes_1) > 0: bboxes, scores = voc2coco(bboxes_1.detach().numpy(), image_np.shape[1], image_np.shape[2]).astype(int), scores        \n    elif len(bboxes_2) > 0: bboxes, scores = bboxes_2, confis        \n    else: bboxes = []\n\n    predictions = tracking_function(tracker3, frame_id_3, bboxes, scores)\n#     predictions = tracking_function(tracker, frame_id, bboxes, scores)\n    \n    prediction_str = ' '.join(predictions)\n    pred_df['annotations'] = prediction_str\n    env.predict(pred_df)\n    if frame_id_1 < 3:\n        if len(predictions)>0:\n            box = [list(map(int,box.split(' ')[1:])) for box in predictions]\n        else:\n            box = []\n        display(show_img(image_np, box, bbox_format='coco'))\n#     print('Prediction:', pred_df)\n    frame_id_1 += 1\n    frame_id_2 += 1\n    frame_id_3 += 1","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:30:07.315800Z","iopub.execute_input":"2022-02-14T05:30:07.316129Z","iopub.status.idle":"2022-02-14T05:30:11.184648Z","shell.execute_reply.started":"2022-02-14T05:30:07.316094Z","shell.execute_reply":"2022-02-14T05:30:11.183726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df = pd.read_csv('submission.csv')\nsub_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-14T05:30:11.186128Z","iopub.execute_input":"2022-02-14T05:30:11.186812Z","iopub.status.idle":"2022-02-14T05:30:11.201693Z","shell.execute_reply.started":"2022-02-14T05:30:11.186780Z","shell.execute_reply":"2022-02-14T05:30:11.200851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}