{"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":"## Ref\n* https://www.kaggle.com/steamedsheep/yolov5-is-all-you-need\n* https://www.kaggle.com/parapapapam/yolox-inference-tracking-on-cots-lb-0-539\n* https://www.kaggle.com/awsaf49/great-barrier-reef-yolov5-infer","metadata":{"execution":{"iopub.status.busy":"2022-01-28T23:48:48.560053Z","iopub.execute_input":"2022-01-28T23:48:48.560337Z","iopub.status.idle":"2022-01-28T23:48:48.591112Z","shell.execute_reply.started":"2022-01-28T23:48:48.560254Z","shell.execute_reply":"2022-01-28T23:48:48.589513Z"}}},{"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-01-14T06:11:48.179676Z","iopub.execute_input":"2022-01-14T06:11:48.18045Z","iopub.status.idle":"2022-01-14T06:11:49.690787Z","shell.execute_reply.started":"2022-01-14T06:11:48.18032Z","shell.execute_reply":"2022-01-14T06:11:49.689882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%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-01-14T06:11:49.694016Z","iopub.execute_input":"2022-01-14T06:11:49.694427Z","iopub.status.idle":"2022-01-14T06:13:04.132521Z","shell.execute_reply.started":"2022-01-14T06:11:49.694394Z","shell.execute_reply":"2022-01-14T06:13:04.131677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%cd /kaggle/working/","metadata":{"execution":{"iopub.status.busy":"2022-01-14T06:13:04.134251Z","iopub.execute_input":"2022-01-14T06:13:04.134764Z","iopub.status.idle":"2022-01-14T06:13:04.142843Z","shell.execute_reply.started":"2022-01-14T06:13:04.13472Z","shell.execute_reply":"2022-01-14T06:13:04.141947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\nfrom norfair import Detection, Tracker","metadata":{"execution":{"iopub.status.busy":"2022-01-14T06:13:04.145271Z","iopub.execute_input":"2022-01-14T06:13:04.145535Z","iopub.status.idle":"2022-01-14T06:13:07.771698Z","shell.execute_reply.started":"2022-01-14T06:13:04.145505Z","shell.execute_reply":"2022-01-14T06:13:07.770942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ROOT_DIR  = '/kaggle/input/tensorflow-great-barrier-reef/'\n# CKPT_PATH = '../input/yolov5m-rect-stratify-split/best(40).pt'\nIMG_SIZE  = 10000\nCONF      = 0.15\nIOU       = 0.45\nAUGMENT   = True\nFDA_aug = False","metadata":{"execution":{"iopub.status.busy":"2022-01-14T06:13:07.773004Z","iopub.execute_input":"2022-01-14T06:13:07.773286Z","iopub.status.idle":"2022-01-14T06:13:07.778435Z","shell.execute_reply.started":"2022-01-14T06:13:07.77325Z","shell.execute_reply":"2022-01-14T06:13:07.777507Z"},"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    \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\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","metadata":{"execution":{"iopub.status.busy":"2022-01-14T06:13:07.781789Z","iopub.execute_input":"2022-01-14T06:13:07.78207Z","iopub.status.idle":"2022-01-14T06:13:07.82181Z","shell.execute_reply.started":"2022-01-14T06:13:07.782035Z","shell.execute_reply":"2022-01-14T06:13:07.82103Z"},"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\n# def 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":{"execution":{"iopub.status.busy":"2022-01-14T06:13:07.825363Z","iopub.execute_input":"2022-01-14T06:13:07.825627Z","iopub.status.idle":"2022-01-14T06:13:07.836777Z","shell.execute_reply.started":"2022-01-14T06:13:07.825586Z","shell.execute_reply":"2022-01-14T06:13:07.835935Z"},"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-01-14T06:13:07.838117Z","iopub.execute_input":"2022-01-14T06:13:07.838422Z","iopub.status.idle":"2022-01-14T06:13:07.849004Z","shell.execute_reply.started":"2022-01-14T06:13:07.838394Z","shell.execute_reply":"2022-01-14T06:13:07.848293Z"},"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-01-14T06:13:07.850367Z","iopub.execute_input":"2022-01-14T06:13:07.851232Z","iopub.status.idle":"2022-01-14T06:13:07.863071Z","shell.execute_reply.started":"2022-01-14T06:13:07.851194Z","shell.execute_reply":"2022-01-14T06:13:07.862299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2022-01-14T06:13:07.866013Z","iopub.execute_input":"2022-01-14T06:13:07.866357Z","iopub.status.idle":"2022-01-14T06:13:07.895523Z","shell.execute_reply.started":"2022-01-14T06:13:07.86632Z","shell.execute_reply":"2022-01-14T06:13:07.894855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = torch.hub.load('../input/yolov5-lib-ds', \n                       'custom', \n                       path='../input/yolos-video-fold/yolov5s6_3000_b6_uflip_split91_f1_v12.pt',\n                       \n#                        path='../input/yolos-video-fold/2022_yolos_3600_f1_best.pt',\n                       source='local',\n                       force_reload=True)  # local repo\nmodel.conf = CONF","metadata":{"execution":{"iopub.status.busy":"2022-01-14T06:13:07.896977Z","iopub.execute_input":"2022-01-14T06:13:07.897322Z","iopub.status.idle":"2022-01-14T06:13:13.450312Z","shell.execute_reply.started":"2022-01-14T06:13:07.897284Z","shell.execute_reply":"2022-01-14T06:13:13.449509Z"},"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\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":{"execution":{"iopub.status.busy":"2022-01-14T06:13:13.452209Z","iopub.execute_input":"2022-01-14T06:13:13.452472Z","iopub.status.idle":"2022-01-14T06:13:18.836804Z","shell.execute_reply.started":"2022-01-14T06:13:13.452435Z","shell.execute_reply":"2022-01-14T06:13:18.836033Z"},"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-01-14T06:13:18.838052Z","iopub.execute_input":"2022-01-14T06:13:18.838542Z","iopub.status.idle":"2022-01-14T06:13:18.856915Z","shell.execute_reply.started":"2022-01-14T06:13:18.838498Z","shell.execute_reply":"2022-01-14T06:13:18.856075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}