{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm_notebook","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/global-wheat-detection/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_data = []\nfor g in tqdm_notebook(train_df.groupby('image_id')):\n    data = {}\n    data['filename'] = g[0]\n    data['bbox'] = g[1]['bbox'].values\n    total_data.append(data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install '../input/detectron2-wheat/pycocotools-2.0.0-cp37-cp37m-linux_x86_64.whl'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install '../input/detectron2-wheat/yacs-0.1.7-py3-none-any.whl'\n!pip install '../input/detectron2-wheat/fvcore-0.1.1.post200513-py3-none-any.whl'\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install '../input/detectron2-wheat/detectron2-0.1.2cu101-cp37-cp37m-linux_x86_64.whl'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport numpy as np\nimport json\nfrom detectron2.structures import BoxMode\n\ndef get_wheat_dicts(total_data):\n    \n    dataset_dicts = []\n    for idx, v in enumerate(total_data):\n        record = {}\n        \n        filename = os.path.join('../input/global-wheat-detection/train/', v[\"filename\"]+'.jpg')\n        height, width = 1024,1024\n        \n        record[\"file_name\"] = filename\n        record[\"image_id\"] = idx\n        record[\"height\"] = height\n        record[\"width\"] = width\n      \n        \n        objs = []\n        for b in v['bbox']:\n            b = json.loads(b)\n            obj = {\n                'bbox': list(b),\n                'bbox_mode': BoxMode.XYWH_ABS,\n                'category_id':0,\n            }\n            objs.append(obj)\n            \n        record[\"annotations\"] = objs\n        dataset_dicts.append(record)\n    return dataset_dicts\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\nimport numpy as np\nimport cv2\nimport random\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import MetadataCatalog","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"wheat_metadata = MetadataCatalog.get(\"wheat_train\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from detectron2.engine import DefaultTrainer\nfrom detectron2.config import get_cfg\n\ncfg = get_cfg()\ncfg.merge_from_file('../input/detectron2-wheat/configs/COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml')   \ncfg.DATASETS.TRAIN = (\"wheat_train\",)\ncfg.DATASETS.TEST = ()\ncfg.DATALOADER.NUM_WORKERS = 2\ncfg.SOLVER.IMS_PER_BATCH = 8\ncfg.SOLVER.BASE_LR = 0.00025  \ncfg.SOLVER.MAX_ITER = 1500   \ncfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128 \ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 1  \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cfg.MODEL.WEIGHTS = '../input/simple-detectron2-training/output/model_final.pth'\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7\ncfg.DATASETS.TEST = (\"wheat_val\", )\npredictor = DefaultPredictor(cfg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob \nimport cv2\n\nimage_id = []\nPredictionString = []\n\nfor f in tqdm_notebook(glob.glob('../input/global-wheat-detection/test/*.jpg')):\n    img = cv2.imread(f)\n    outputs = predictor(img)\n    res = outputs['instances'].to('cpu')\n    \n    s_pred = ''\n\n    for i, s in enumerate(res.scores.tolist()):\n        s_pred += '{:.4f} {} {} {} {} '.format(s,int(res.pred_boxes.tensor.tolist()[i][0]),int(res.pred_boxes.tensor.tolist()[i][1]),\n                                                               int(res.pred_boxes.tensor.tolist()[i][2] - res.pred_boxes.tensor.tolist()[i][0]),int(res.pred_boxes.tensor.tolist()[i][3] - res.pred_boxes.tensor.tolist()[i][1]))\n    \n    \n    image_id.append(f.split('/')[-1].split('.')[0])\n    PredictionString.append(s_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res_df = pd.DataFrame({'image_id':image_id,'PredictionString':PredictionString})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res_df.to_csv('submission.csv',index=False)","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}