{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-02T06:49:31.305143Z","iopub.execute_input":"2022-09-02T06:49:31.305555Z","iopub.status.idle":"2022-09-02T06:49:31.330657Z","shell.execute_reply.started":"2022-09-02T06:49:31.305473Z","shell.execute_reply":"2022-09-02T06:49:31.329512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.insert(0, \"../input/omegaconf222py3/omegaconf-2.2.2-py3-none-any.whl\")\nsys.path.insert(0, \"../input/weightedboexsfusion\")\nsys.path.insert(0,'../input/effdet')\nsys.path.insert(0,'../input/timm-pytorch-image-models/pytorch-image-models-master')\n# sys.path.insert(0,'../input/antlr4/dist/antlr4-python3-runtime-4.9.2.tar')","metadata":{"execution":{"iopub.status.busy":"2022-09-02T06:49:31.333464Z","iopub.execute_input":"2022-09-02T06:49:31.333855Z","iopub.status.idle":"2022-09-02T06:49:31.339578Z","shell.execute_reply.started":"2022-09-02T06:49:31.333819Z","shell.execute_reply":"2022-09-02T06:49:31.338396Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --no-deps '../input/pycocotools/pycocotools-2.0.4-cp37-cp37m-linux_x86_64.whl' > /dev/null\n!pip install --no-deps '../input/antlr4/dist/antlr4-python3-runtime-4.9.3.tar' > /dev/null","metadata":{"execution":{"iopub.status.busy":"2022-09-02T06:49:31.373869Z","iopub.execute_input":"2022-09-02T06:49:31.374861Z","iopub.status.idle":"2022-09-02T06:50:17.825658Z","shell.execute_reply.started":"2022-09-02T06:49:31.374804Z","shell.execute_reply":"2022-09-02T06:50:17.824521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd \nimport numpy as np \nimport seaborn as sns\nimport matplotlib.pyplot as plt \nimport cv2 as cv \nimport os \nimport torch \nfrom  torch import nn\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset,DataLoader\nfrom torch import optim\nfrom torchvision import transforms\nfrom torch.utils.data import random_split\nfrom tqdm import tqdm\nfrom albumentations.pytorch import ToTensorV2\nfrom matplotlib import patches\nimport os\nfrom bs4 import BeautifulSoup\nimport json\nimport re\nfrom effdet import create_model","metadata":{"execution":{"iopub.status.busy":"2022-09-02T06:50:17.829995Z","iopub.execute_input":"2022-09-02T06:50:17.830313Z","iopub.status.idle":"2022-09-02T06:50:24.444352Z","shell.execute_reply.started":"2022-09-02T06:50:17.830283Z","shell.execute_reply":"2022-09-02T06:50:24.443197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv('../input/global-wheat-detection/sample_submission.csv')\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nimage_list = sample['image_id']","metadata":{"execution":{"iopub.status.busy":"2022-09-02T06:50:24.445940Z","iopub.execute_input":"2022-09-02T06:50:24.446724Z","iopub.status.idle":"2022-09-02T06:50:24.527505Z","shell.execute_reply.started":"2022-09-02T06:50:24.446687Z","shell.execute_reply":"2022-09-02T06:50:24.526527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class WheatDataset(Dataset):\n    def __init__(self, image_list, image_dir, transforms=None):\n        super().__init__()\n\n        self.image_ids = image_list\n        self.df = image_list\n        self.image_dir = image_dir\n        self.transforms = transforms\n        \n    def __getitem__(self, index: int):\n        image_id = self.image_ids[index]\n        image = cv.imread(f'{self.image_dir}/{image_id}.jpg', cv.IMREAD_COLOR)\n        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n        if self.transforms:\n            sample = {'image': image}\n            sample = self.transforms(**sample)\n            image = sample['image']\n        return image,image_id\n\n    def __len__(self) -> int:\n        return len(self.image_ids)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T06:50:24.531658Z","iopub.execute_input":"2022-09-02T06:50:24.533766Z","iopub.status.idle":"2022-09-02T06:50:24.541669Z","shell.execute_reply.started":"2022-09-02T06:50:24.533736Z","shell.execute_reply":"2022-09-02T06:50:24.540768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 512\ntest_aug = A.Compose([A.Resize(IMAGE_SIZE,IMAGE_SIZE ,p = 1.0),ToTensorV2()])\ntest_data= WheatDataset(image_list,'../input/global-wheat-detection/test',test_aug)\ntest_loader =DataLoader(test_data,batch_size=10,shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T06:50:24.544702Z","iopub.execute_input":"2022-09-02T06:50:24.545146Z","iopub.status.idle":"2022-09-02T06:50:24.553218Z","shell.execute_reply.started":"2022-09-02T06:50:24.545110Z","shell.execute_reply":"2022-09-02T06:50:24.552274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_model(\"efficientdet_d0\" , bench_task='predict' , num_classes= 1 , image_size=(IMAGE_SIZE,IMAGE_SIZE),pretrained=False,pretrained_backbone=False)\nmodel.load_state_dict(torch.load('../input/wheat-cyclic/model-cyclic-lr'))\nmodel = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:45:01.675706Z","iopub.execute_input":"2022-09-02T08:45:01.676440Z","iopub.status.idle":"2022-09-02T08:45:02.430259Z","shell.execute_reply.started":"2022-09-02T08:45:01.676405Z","shell.execute_reply":"2022-09-02T08:45:02.429270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def format_prediction_string(boxes, scores):\n    pred_strings = []\n    for j in zip(scores, boxes):\n        pred_strings.append(\"{0:.4f} {1} {2} {3} {4}\".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3]))\n    return \" \".join(pred_strings)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:45:03.654193Z","iopub.execute_input":"2022-09-02T08:45:03.655230Z","iopub.status.idle":"2022-09-02T08:45:03.661457Z","shell.execute_reply.started":"2022-09-02T08:45:03.655190Z","shell.execute_reply":"2022-09-02T08:45:03.660257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = []\nscore_threshold = 0.5\nmodel.eval()\nfor images,image_ids in tqdm(test_loader):\n    images = images.to(device).float()\n    with torch.no_grad():\n        output = model(images)\n        for i in range(images.shape[0]):\n            boxes = output[i].detach().cpu().numpy()[:,:4]\n            boxes = (boxes*2).astype(np.int32).clip(min=0, max=1023)\n            scores = output[i].detach().cpu().numpy()[:,4]\n            indexes = np.where(scores > score_threshold)[0]\n            boxes = boxes[indexes]\n            scores = scores[indexes]\n            boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n            boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n            image_id = image_ids[i]\n            result = {'image_id': image_id,'PredictionString': format_prediction_string(boxes, scores)}\n            results.append(result)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:45:04.616719Z","iopub.execute_input":"2022-09-02T08:45:04.617790Z","iopub.status.idle":"2022-09-02T08:45:05.758266Z","shell.execute_reply.started":"2022-09-02T08:45:04.617744Z","shell.execute_reply":"2022-09-02T08:45:05.756704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:45:06.847593Z","iopub.execute_input":"2022-09-02T08:45:06.848392Z","iopub.status.idle":"2022-09-02T08:45:06.856299Z","shell.execute_reply.started":"2022-09-02T08:45:06.848356Z","shell.execute_reply":"2022-09-02T08:45:06.854941Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:45:11.858897Z","iopub.execute_input":"2022-09-02T08:45:11.859484Z","iopub.status.idle":"2022-09-02T08:45:11.870500Z","shell.execute_reply.started":"2022-09-02T08:45:11.859451Z","shell.execute_reply":"2022-09-02T08:45:11.869112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score_threshold2 = 0.5\ni = 2\nsample = images[i].permute(1,2,0).cpu().numpy().astype(np.int32)\nboxes = output[i].detach().cpu().numpy()[:,:4].astype(np.int32)\nscores = output[i].detach().cpu().numpy()[:,4]\nindexes = np.where(scores > score_threshold2)[0]\nboxes = boxes[indexes]\nscores = scores[indexes]\nboxes[:, 2] = boxes[:, 2] - boxes[:, 0]\nboxes[:, 3] = boxes[:, 3] - boxes[:, 1]\nfig, ax = plt.subplots(1, 1, figsize=(16, 8))\nax.imshow(sample)\nfor box in boxes:\n    xmin,ymin,width,height = box\n    rect = patches.Rectangle((xmin,ymin),width,height, linewidth=1, edgecolor='r', facecolor='none')\n    ax.add_patch(rect)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:45:13.140955Z","iopub.execute_input":"2022-09-02T08:45:13.141576Z","iopub.status.idle":"2022-09-02T08:45:13.518464Z","shell.execute_reply.started":"2022-09-02T08:45:13.141541Z","shell.execute_reply":"2022-09-02T08:45:13.517656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}