{"cells":[{"metadata":{},"cell_type":"markdown","source":"# https://www.kaggle.com/superkevingit/faster-rcnn-with-mmdetection-without-internet","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install ../input/mmcvwhl/addict-2.2.1-py3-none-any.whl\n!pip install ../input/mmdetection20-5-13/mmcv-0.5.1-cp37-cp37m-linux_x86_64.whl\n!pip install ../input/mmdetection20-5-13/terminal-0.4.0-py3-none-any.whl\n!pip install ../input/mmdetection20-5-13/terminaltables-3.1.0-py3-none-any.whl","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Copy the MMDetection framework to the writeable directoy.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp -r ../input/mmdetection20-5-13/mmdetection/mmdetection .","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We should prepare the data and convert to COCO format.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir -p mmdetection/data/Wheatdetection/annotations\n!cp -r ../input/global-wheat-detection/test mmdetection/data/Wheatdetection/test\n!cp -r ../input/global-wheat-detection/sample_submission.csv mmdetection/data/Wheatdetection/\n!mkdir mmdetection/configs/wheatdetection","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Some config files for faster-rcnn implement and test data.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp ../input/mmdetfasterrcnn/config/config/faster_rcnn_r50_fpn_1x_coco_test.py mmdetection/configs/wheatdetection\n!cp ../input/mmdetfasterrcnn/config/config/wheat_detection_test.py mmdetection/configs/_base_/datasets\n!cp ../input/mmdetfasterrcnn/config/config/__init__.py mmdetection/mmdet/datasets\n!cp ../input/mmdetfasterrcnn/config/config/wheat.py mmdetection/mmdet/datasets","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd mmdetection","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"compile the coco toolbox","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp -r ../../input/mmdetection20-5-13/cocoapi/cocoapi .","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd cocoapi/PythonAPI","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!make","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!make install","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!python setup.py install","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pycocotools","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd ../..","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"compile the MMDetection Framework","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -v -e .","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd ../","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now, we can use MMDetection for the inference.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import sys\nsys.path.append('mmdetection') # To find local version","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from mmdet.apis import init_detector, inference_detector, show_result_pyplot\nimport mmcv\nfrom mmcv import Config\nfrom mmdet.models import build_detector\nfrom mmcv.runner import load_checkpoint\nfrom mmcv.parallel import MMDataParallel\nfrom mmdet.apis import single_gpu_test\nfrom mmdet.datasets import build_dataloader, build_dataset\n\nimport pandas as pd\nimport os\nimport json\n\nfrom PIL import Image\n\nimport torch","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from mmdet.apis import inference_detector, init_detector\nWEIGHTS_FILE = '../input/zlb0525/epoch_18.pth'# f'{DIR_WEIGHTS}/epoch_50.pth'\nconfig_file = '../input/zlb0525/cascade_rcnn_r50_fpn_1x_coco.py'\nmodel = init_detector(config_file, WEIGHTS_FILE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#################################### cascade rcnn ############################################\nDATA_ROOT_PATH = '../input/global-wheat-detection/test/'\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\nmodel.to(device)\nmodel.eval()\nfrom tqdm import tqdm\nresults = []\nwith torch.no_grad():\n    for img_name in tqdm(os.listdir(DATA_ROOT_PATH)):\n        img_pth = os.path.join(DATA_ROOT_PATH, img_name)\n        result = inference_detector(model, img_pth)\n        \n        boxes = result[0][:, :4]\n        scores = result[0][:, 4]\n        if len(boxes) > 0:\n            boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n            boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n        \n        result = {\n            'image_id': img_name[:-4],\n            'PredictionString': format_prediction_string(boxes, scores)\n        }\n\n        results.append(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.to_csv('submission.csv', index=False)\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -rf mmdetection/","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}