{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\nos.listdir('/kaggle/input/clone-mmdetection-feng/mmdetection_feng/wheat_detection')\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\nimport torch\nprint(torch.cuda.is_available())\n# You can write up to 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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":"!ls -l /kaggle/input/clone-mmdetection-feng/mmdetection_feng/mmdet/models/detectors","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cat /kaggle/input/clone-mmdetection-feng/mmdetection_feng/mmdet/models/detectors/base.py","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp -r /kaggle/input/clone-mmdetection-feng/mmdetection_feng/ /kaggle/working/mmdetection_feng","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('/kaggle/input/clone-mmdetection-feng/mmdetection_feng')\nos.listdir('.')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('/kaggle/input/clone-mmdetection-feng/mmdetection_feng/configs/wheat_detection/')\nos.listdir('/kaggle/input/clone-mmdetection-feng/mmdetection_feng/mmdet/datasets')","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 /kaggle/input/mmdetection20-5-13/cocoapi/cocoapi .","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd /kaggle/working/cocoapi/PythonAPI","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('/kaggle/working/')","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":"import pycocotools","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd /kaggle/working/mmdetection_feng","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -v -e.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cd /kaggle/working/mmdetection_feng","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# !cat ./mmdet/models/detectors/base.py","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import sys\nsys.path.append('/kaggle/working/mmdetection_feng') # To find local version","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# os.listdir()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# !ls -l /kaggle/working/mmdetection_feng/mmdet/models/detectors","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# !cat /kaggle/working/mmdetection_feng/mmdet/models/detectors/base.py","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import mmdet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import time\n\nfrom mmdet.apis import init_detector, inference_detector\nfrom tqdm import tqdm\nimport os\nimport cv2\n\nimport pandas as pd","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\n    return \" \".join(pred_strings)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def submission_test(config_file, checkpoint_file):\n\n#     model = init_detector(config_file, checkpoint_file, device='cuda:0')\n\n#     results = []\n#     test_path = '/kaggle/input/global-wheat-detection/test'\n#     bar = tqdm(os.listdir(test_path))\n#     for file in bar:\n#         img = f'{test_path}/{file}'\n#         result = inference_detector(model, img)\n#         result = [_ for _ in result if len(_) != 0]\n#         boxes = []\n#         scores = []\n\n#         image = cv2.imread(img)\n#         for class_result in result:\n#             for item in class_result:\n#                 box = item[:4]\n#                 x1, y1, x2, y2 = box\n#                 score = item[4]\n#                 boxes.append([x1, y1, x2 - x1, y2 - y1])\n#                 scores.append(float(score))\n\n#         cur_image_result = {\n#             'image_id': file[:-4],\n#             'PredictionString': format_prediction_string(boxes, scores)\n#         }\n#         results.append(cur_image_result)\n\n\n#     test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\n#     return test_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef submission_test(config_file, checkpoint_file):\n\n    model = init_detector(config_file, checkpoint_file, device='cuda:0')\n\n    results = []\n    test_path = '/kaggle/input/global-wheat-detection/test'\n    # test_path = '/home/fengyouliang/datasets/WHD/test'\n\n    bar = tqdm(os.listdir(test_path))\n    for file in bar:\n        img = f'{test_path}/{file}'\n        result = inference_detector(model, img)\n        if isinstance(result, tuple):\n            bbox_result, segm_result = result\n            if isinstance(segm_result, tuple):\n                segm_result = segm_result[0]  # ms rcnn\n        else:\n            bbox_result, segm_result = result, None\n        result = [_ for _ in bbox_result if len(_) != 0]\n        boxes = []\n        scores = []\n\n        for class_result in result:\n            for item in class_result:\n                box = item[:4]\n                x1, y1, x2, y2 = box\n                score = item[4]\n                boxes.append([x1, y1, x2 - x1, y2 - y1])\n                scores.append(float(score))\n\n        cur_image_result = {\n            'image_id': file[:-4],\n            'PredictionString': format_prediction_string(boxes, scores)\n        }\n        results.append(cur_image_result)\n\n    test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\n    return test_df\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Inference","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n\npath = '/kaggle/input/maskrcnn/'\nos.listdir(path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"root_path = path\n\nconfig_file = f'{root_path}/maskrcnn.py'\ncheckpoint_file = f'{root_path}/epoch_12.pth'\n\n# with open(config_file, 'r') as f:\n#     py = f.readlines()\n    \nimport os\nos.path.isfile(config_file), os.path.isfile(checkpoint_file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for _ in py:\n#     print(_[:-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = submission_test(config_file, checkpoint_file)\n\n# save_path = '/kaggle/working'\n#     if not os.path.exists(save_path):\n#         os.makedirs(save_path)\n#     test_df.to_csv(f'{save_path}/submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"! rm -rf /kaggle/working","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv('/kaggle/working/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}