{"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-08-01T05:10:44.590605Z","iopub.execute_input":"2022-08-01T05:10:44.591166Z","iopub.status.idle":"2022-08-01T05:10:44.625382Z","shell.execute_reply.started":"2022-08-01T05:10:44.591046Z","shell.execute_reply":"2022-08-01T05:10:44.624410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Global Wheat Detection Inference\n### Training Notebook: https://www.kaggle.com/code/wasdac/global-wheat-train\n### Inference Notebook: https://www.kaggle.com/code/wasdac/global-wheat-inference","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport cv2\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom tqdm.auto import tqdm","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:10:44.627022Z","iopub.execute_input":"2022-08-01T05:10:44.627688Z","iopub.status.idle":"2022-08-01T05:10:44.953156Z","shell.execute_reply.started":"2022-08-01T05:10:44.627655Z","shell.execute_reply":"2022-08-01T05:10:44.952248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision import datasets\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:10:44.954957Z","iopub.execute_input":"2022-08-01T05:10:44.955335Z","iopub.status.idle":"2022-08-01T05:10:48.477628Z","shell.execute_reply.started":"2022-08-01T05:10:44.955304Z","shell.execute_reply":"2022-08-01T05:10:48.476540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CFG:\n    learning_rate = 3e-3\n    num_epochs = 1\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:10:48.480639Z","iopub.execute_input":"2022-08-01T05:10:48.481755Z","iopub.status.idle":"2022-08-01T05:10:48.487894Z","shell.execute_reply.started":"2022-08-01T05:10:48.481705Z","shell.execute_reply":"2022-08-01T05:10:48.486427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)\nnum_classes = 2  \nin_features = model.roi_heads.box_predictor.cls_score.in_features\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\nmodel.eval()\nmodel = model.to(CFG.device)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:10:48.489143Z","iopub.execute_input":"2022-08-01T05:10:48.489608Z","iopub.status.idle":"2022-08-01T05:10:49.162909Z","shell.execute_reply.started":"2022-08-01T05:10:48.489578Z","shell.execute_reply":"2022-08-01T05:10:49.161799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LOAD_PATH = \"../input/resnet50wheatdetection2/resnet50_faster_rcnn_2.pth\"\nmodel.load_state_dict(torch.load(LOAD_PATH, map_location=torch.device(CFG.device)))","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:10:49.164223Z","iopub.execute_input":"2022-08-01T05:10:49.164512Z","iopub.status.idle":"2022-08-01T05:10:50.964141Z","shell.execute_reply.started":"2022-08-01T05:10:49.164485Z","shell.execute_reply":"2022-08-01T05:10:50.962808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_imgs_root = \"../input/global-wheat-detection/test\"\ntest_img_lst = os.listdir(test_imgs_root)\ntest_img_lst","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:10:50.966011Z","iopub.execute_input":"2022-08-01T05:10:50.967136Z","iopub.status.idle":"2022-08-01T05:10:50.980960Z","shell.execute_reply.started":"2022-08-01T05:10:50.967089Z","shell.execute_reply":"2022-08-01T05:10:50.979658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"threshold = 0.7\nsubmission_dict = {}\nfor img in test_img_lst:\n    img_name = img.split(\".\")[0]\n    #print(img_name)\n    test_img_path = os.path.join(test_imgs_root, img)\n    test_img = cv2.imread(test_img_path)\n    test_img_rgb = cv2.cvtColor(test_img, cv2.COLOR_BGR2RGB)\n    test_img_tensor = transforms.ToTensor()(test_img_rgb)\n    test_img_unsqueezed = test_img_tensor.unsqueeze(0)\n    with torch.no_grad():\n        loss = model(test_img_unsqueezed.to(CFG.device))\n        loss_0 = loss[0]\n        #print(loss_0[\"boxes\"][:5])\n        #print(loss_0[\"scores\"][:5])\n        #break\n        pred_string = \"\"\n        for enum, test_bbox in enumerate(loss_0[\"boxes\"]):\n            score = loss_0[\"scores\"][enum]\n            if score > threshold:\n                x1, y1 = int(test_bbox[0]), int(test_bbox[1])\n                x2, y2 = int(test_bbox[2]), int(test_bbox[3])\n                w = x2-x1\n                h = y2-y1\n                cv2.rectangle(test_img, (x1,y1), (x2,y2), color=(255,0,0), thickness=3)\n                pred_string += f\"{score:.3f} {x1} {y1} {w} {h} \"\n        #print(pred_string)\n    submission_dict[img_name] = pred_string\n    #print(pred_string)\n    plt.figure(figsize=(10,10))\n    plt.imshow(test_img)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:11:40.113212Z","iopub.execute_input":"2022-08-01T05:11:40.113962Z","iopub.status.idle":"2022-08-01T05:12:17.843739Z","shell.execute_reply.started":"2022-08-01T05:11:40.113914Z","shell.execute_reply":"2022-08-01T05:12:17.842346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print(submission_dict.items())","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:11:13.171040Z","iopub.status.idle":"2022-08-01T05:11:13.172001Z","shell.execute_reply.started":"2022-08-01T05:11:13.171657Z","shell.execute_reply":"2022-08-01T05:11:13.171690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df_path = \"../input/global-wheat-detection/sample_submission.csv\"\nsubmission_df = pd.read_csv(submission_df_path)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:12:35.720975Z","iopub.execute_input":"2022-08-01T05:12:35.721797Z","iopub.status.idle":"2022-08-01T05:12:35.741211Z","shell.execute_reply.started":"2022-08-01T05:12:35.721755Z","shell.execute_reply":"2022-08-01T05:12:35.740339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for en, (k,v) in enumerate(submission_dict.items()):\n    #print(k,v)\n    submission_df[\"image_id\"][en] = k\n    submission_df[\"PredictionString\"][en] = v\n    \n\nsubmission_df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:12:36.022173Z","iopub.execute_input":"2022-08-01T05:12:36.022900Z","iopub.status.idle":"2022-08-01T05:12:36.042161Z","shell.execute_reply.started":"2022-08-01T05:12:36.022862Z","shell.execute_reply":"2022-08-01T05:12:36.040948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df","metadata":{"execution":{"iopub.status.busy":"2022-08-01T05:12:36.269802Z","iopub.execute_input":"2022-08-01T05:12:36.270877Z","iopub.status.idle":"2022-08-01T05:12:36.284497Z","shell.execute_reply.started":"2022-08-01T05:12:36.270838Z","shell.execute_reply":"2022-08-01T05:12:36.283724Z"},"trusted":true},"execution_count":null,"outputs":[]}]}