{"cells":[{"metadata":{"id":"TzcdlxjiBJJw","trusted":true},"cell_type":"code","source":"!pip install pyyaml>5.1 pycocotools>=2.0.1 --upgrade","execution_count":null,"outputs":[]},{"metadata":{"id":"RVzSgG7FyB_C","outputId":"b8096a5f-4075-4097-b087-c7da56b56e78","trusted":true},"cell_type":"code","source":"# install dependencies: \nimport torch, torchvision\nprint(torch.__version__, torch.cuda.is_available())\n!gcc --version\n# opencv is pre-installed on colab","execution_count":null,"outputs":[]},{"metadata":{"id":"zx81FmGkyRH2","outputId":"fda56447-4104-4f5c-b8ca-e8824b19ea37","trusted":true},"cell_type":"code","source":"# install detectron2: (colab has CUDA 10.1 + torch 1.5)\n# See https://detectron2.readthedocs.io/tutorials/install.html for instructions\nassert torch.__version__.startswith(\"1.5\")\n!pip install detectron2==0.2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.5/index.html --no-cache-dir --upgrade","execution_count":null,"outputs":[]},{"metadata":{"id":"ZZzXkHtUxP6L","trusted":true},"cell_type":"code","source":"# Some basic setup:\n# Setup detectron2 logger\nimport detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\n\n# import some common libraries\nimport numpy as np\nimport os, json, cv2, random\nimport pandas as pd\n# from google.colab.patches import cv2_imshow\n\n# import some common detectron2 utilities\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import MetadataCatalog, DatasetCatalog\n\nIMG_HEIGHT = 1024\nIMG_WIDTH = 1024","execution_count":null,"outputs":[]},{"metadata":{"id":"GSB1lSCyusxn","outputId":"8baa22e8-c68e-4df6-8adf-67878575f560","trusted":true},"cell_type":"code","source":"path = '/kaggle/input/global-wheat-detection/'","execution_count":null,"outputs":[]},{"metadata":{"id":"b8rUpp75IObs","outputId":"36d1f124-5d10-4d6e-ee42-11b12ac51854","trusted":true},"cell_type":"code","source":"from detectron2.engine import DefaultTrainer\nfrom detectron2.data import build_detection_train_loader\nimport detectron2.data.transforms as T\nfrom detectron2.data import DatasetMapper   # the default mapper\n\ncfg = get_cfg()\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_R_50_DC5_1x.yaml\"))\n# cfg.DATASETS.TRAIN = (\"wheat\",)\ncfg.DATASETS.TEST = ()\ncfg.DATALOADER.NUM_WORKERS = 2\ncfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Detection/faster_rcnn_R_50_DC5_1x.yaml\")  # Let training initialize from model zoo\ncfg.SOLVER.IMS_PER_BATCH = 2\n# cfg.SOLVER.BASE_LR = 0.00025  # pick a good LR\n# cfg.SOLVER.MAX_ITER = 750  # 300 iterations seems good enough for this toy dataset; you may need to train longer for a practical dataset\ncfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128   # faster, and good enough for this toy dataset (default: 512)\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 1  # only has one class (wheat)\ncfg.OUTPUT_DIR = '/kaggle/input/faster-rcnn-750-epoch'\n","execution_count":null,"outputs":[]},{"metadata":{"id":"8-H2YRz8Kq8u","outputId":"e264e6a6-ce47-46d3-bfd1-5b4e6da61364","trusted":true},"cell_type":"code","source":"cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, \"model_final.pth\")\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.55   # set a custom testing threshold for this model\ncfg.DATASETS.TEST = (\"wheat_val\",)\npredictor = DefaultPredictor(cfg)","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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from detectron2.utils.visualizer import ColorMode\n\ndf = pd.DataFrame(columns=['image_id', 'PredictionString'])\n\nfor img in os.listdir(f'{path}/test'):\n    im = cv2.imread(f'{path}/test/{img}', cv2.IMREAD_COLOR)\n    im = cv2.resize(im, (1024, 1024))\n    outputs = predictor(im)\n    outputs = outputs[\"instances\"].to(\"cpu\")\n    dict_ = outputs.get_fields()\n    str_ = ''\n    \n    if len(dict_['pred_boxes']):\n        for boxes, score in zip(dict_['pred_boxes'], dict_['scores']):\n            score_ = score.numpy().item()\n            x1, y1, x2, y2 = boxes.numpy().astype(np.int32).tolist()\n            xywh = [x1, x2, x2-x1, y2-y1]\n            str_ += ''.join([str(round(score_, 4))+' '] + [str(coor) + ' ' for coor in xywh])\n        \n    temp_df = pd.DataFrame([[img.split('.')[0], str_.strip()]], columns=['image_id', 'PredictionString'])\n    df = df.append(temp_df)\n","execution_count":null,"outputs":[]},{"metadata":{"id":"eLRyVB1mhNc2","trusted":true},"cell_type":"code","source":"df.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# blank_image = np.zeros((1024,1024,3), np.uint8)\n# preds = predictor(blank_image)\n# preds = preds[\"instances\"].to(\"cpu\")\n# dict_ = preds.get_fields()\n# len(dict_['pred_boxes'])","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}