{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip install -U /kaggle/input/orkatzfdata/torch-1.5.0+cu101-cp37-cp37m-linux_x86_64.whl /kaggle/input/orkatzfdata/torchvision-0.6.0+cu101-cp37-cp37m-linux_x86_64.whl","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"!pip install '/kaggle/input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl'\n!pip install /kaggle/input/orkatzfdata/yacs-0.1.7-py3-none-any.whl\n!mkdir fvcore\n!cp -R '/kaggle/input/orkatzfdata/fvcore-0.1.dev200407/fvcore-0.1.dev200407/' ./fvcore\n!pip install fvcore/fvcore-0.1.dev200407/.\n!mkdir detectron2-ResNeSt\n!cp -R /kaggle/input/orkatzfdata/detectron2-ResNeSt/* ./detectron2-ResNeSt/\n!pip install detectron2-ResNeSt/.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\n\n# import some common libraries\nimport numpy as np\nimport cv2\nimport random\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from detectron2.config import get_cfg\ncfg = get_cfg()\n\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_cascade_rcnn_ResNeSt_101_FPN_syncbn_range-scale_1x.yaml\"))\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 1  # \n\n\ncfg.MODEL.WEIGHTS = os.path.join('/kaggle/input/model-pth2/', \"model_fold2.pth\")\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4  # set the testing threshold for this model\ncfg.DATASETS.TEST = (\"m5_val\", )\npredictor1 = DefaultPredictor(cfg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\ndf_sub = pd.read_csv('/kaggle/input/global-wheat-detection/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":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":"import cv2\nimport glob\nresults = []\nfor image_id in df_sub['image_id']:\n    im = cv2.imread('/kaggle/input/global-wheat-detection/test/{}.jpg'.format(image_id))\n    boxes = []\n    scores = []\n    labels = []\n    outputs = predictor1(im)\n    out = outputs[\"instances\"].to(\"cpu\")\n    scores = out.get_fields()['scores'].numpy()\n    boxes = out.get_fields()['pred_boxes'].tensor.numpy().astype(int)\n    labels= out.get_fields()['scores'].numpy()\n    boxes = boxes.astype(int)\n    boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n    boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n    result = {'image_id': image_id,'PredictionString': format_prediction_string(boxes, scores)}\n    results.append(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import pyplot as plt\nimage = im.copy()\nsize = 300\nfont = cv2.FONT_HERSHEY_SIMPLEX \n    \n# fontScale \nfontScale = 1\n   \n# Blue color in BGR \ncolor = (255, 0, 0) \n  \n# Line thickness of 2 px \nthickness = 2\nfor b,s in zip(boxes,scores):\n    image = cv2.rectangle(image, (b[0],b[1]), (b[0]+b[2],b[1]+b[3]), (255,0,0), 1) \n    image = cv2.putText(image, '{:.2}'.format(s), (b[0],b[1]), font,  \n                   fontScale, color, thickness, cv2.LINE_AA)\nplt.figure(figsize=[20,20])\nplt.imshow(image[:,:,::-1])\nplt.show()","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)","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}