{"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":"test_images_paths","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_14_20235.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":"class WheatDataset(Dataset):\n    def __init__(self, img_paths):\n        self.img_paths = img_paths\n    \n    def __len__(self):\n        return len(self.img_paths)\n    \n    def __getitem__(self, idx):\n        curr_img = self.img_paths[idx]\n        _, framed_img, framed_meta = preprocess(curr_img, max_size=input_size)\n        return {\n            \"image\": torch.from_numpy(framed_img[0]).to(torch.float32 if not use_float16 else torch.float16),\n            \"framed_meta\": torch.tensor(list(framed_meta[0])),\n            \"image_id\": curr_img.split(\"/\")[-1][:-4]\n        }","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dataset = WheatDataset(test_images_paths)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data_loader = DataLoader(\n    test_dataset,\n    batch_size=2,\n    drop_last=False,\n    shuffle=False,\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = []\nwith torch.no_grad():\n    for img in test_data_loader:\n        images = img['image'].permute(0, 3, 1, 2).cuda()\n        framed_meta = img['framed_meta']\n        image_id = img['image_id']\n        \n        features, regression, classification, anchors = model(images)\n\n        regressBoxes = BBoxTransform()\n        clipBoxes = ClipBoxes()\n\n        out = postprocess(images,\n                          anchors, regression, classification,\n                          regressBoxes, clipBoxes,\n                          threshold, iou_threshold)\n        out = invert_affine(framed_meta, out)\n        \n        for i, out_dict in enumerate(out):\n            if len(out_dict['rois']) == 0:\n                result = {\n                    'image_id': image_id[i],\n                    'PredictionString': \"\"\n                }\n                results.append(result)\n            else:            \n                result = {\n                    'image_id': image_id[i],\n                    'PredictionString': \"\"\n                }\n                \n                pred_strings = []\n                \n                for j in range(len(out_dict['rois'])):\n                    score = float(out_dict['scores'][j])\n                    (x1, y1, x2, y2) = out_dict['rois'][j].astype(np.int)\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)","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}