{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install /kaggle/input/packages/webcolors-1.11.1-py3-none-any.whl","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os, sys\nsys.path.insert(0, \"/kaggle/input/yaefficientdetpytorch/Yet-Another-EfficientDet-Pytorch\")\nimport torch\nimport numpy as np \nimport cv2\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom backbone import EfficientDetBackbone\nfrom efficientdet.utils import BBoxTransform, ClipBoxes\nfrom utils.utils import preprocess, postprocess, invert_affine\nfrom torch.backends import cudnn\nfrom torch.utils.data import Dataset, DataLoader\nfrom glob import glob","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_ROOT_PATH = '../input/global-wheat-detection/test'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"compound_coef = 4\nforce_input_size = None\ntest_images = [path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]\ntest_images_paths = [os.path.join(DATA_ROOT_PATH, f\"{img}.jpg\") for img in test_images]\n# img_path = [os.path.join(INPUT_DIR, \"test\", img_path) for img_path in os.listdir(os.path.join(INPUT_DIR, \"test\"))]\n# IMG_PATH = os.path.join(CONFIG.CFG.DATA.BASE, \"test\", \"2fd875eaa.jpg\")\n\nthreshold = 0.2\niou_threshold = 0.2\n\nuse_cuda = True\nuse_float16 = False\ncudnn.fastest = True\ncudnn.benchmark = True\n\nobj_list = ['wheat']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%capture\n# tf bilinear interpolation is different from any other's, just make do\ninput_sizes = [512, 640, 768, 896, 1024, 1280, 1280, 1536]\ninput_size = input_sizes[compound_coef] if force_input_size is None else force_input_size\n\nmodel = EfficientDetBackbone(compound_coef=compound_coef, num_classes=len(obj_list),\n\n                             # replace this part with your project's anchor config\n                             ratios=[(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)],\n                             scales=[2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)])\n\nmodel.load_state_dict(torch.load('/kaggle/input/efficientdet4/efficientdet-d4_26_36000.pth'))\nmodel.requires_grad_(False)\nmodel.eval()\nif use_cuda:\n    model = model.cuda()\nif use_float16:\n    model = model.half()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = []\nm = 0\nfor k in range(0, len(test_images_paths), 3):\n    ori_imgs, framed_imgs, framed_metas = preprocess(*test_images_paths[k:k+3], max_size=input_size)\n\n    if use_cuda:\n        x = torch.stack([torch.from_numpy(fi).cuda() for fi in framed_imgs], 0)\n    else:\n        x = torch.stack([torch.from_numpy(fi) for fi in framed_imgs], 0)\n\n    x = x.to(torch.float32 if not use_float16 else torch.float16).permute(0, 3, 1, 2)\n    \n    with torch.no_grad():\n        features, regression, classification, anchors = model(x)\n        \n        regressBoxes = BBoxTransform()\n        clipBoxes = ClipBoxes()\n        \n        out = postprocess(x,\n                         anchors, regression, classification,\n                         regressBoxes, clipBoxes,\n                         threshold, iou_threshold)\n    out = invert_affine(framed_metas, out)\n    \n    for i in range(len(ori_imgs)):\n        result = {\n            'image_id': test_images_paths[m].split('/')[-1][:-4],\n            'PredictionString': ''\n        }\n        \n        if len(out[i]['rois']) == 0:\n            results.append(result)\n        else:\n            pred_strings = []\n\n            for j in range(len(out[i]['rois'])):\n                (x1, y1, x2, y2) = out[i]['rois'][j].astype(np.int)\n                score = float(out[i]['scores'][j])\n                pred_strings.append(\"{0:.4f} {1} {2} {3} {4}\".format(score, x1, y1, x2-x1, y2-y1))\n            result['PredictionString'] = \" \".join(pred_strings)\n            results.append(result)\n        m += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}