{"cells":[{"metadata":{},"cell_type":"markdown","source":"I just wrote a side note on what is happening in every line, this is not definitly my original work","execution_count":null},{"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 #for file reading\nimport subprocess","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#my pip was not updated\n!pip install --upgrade pip","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":false,"_kg_hide-output":false},"cell_type":"code","source":"!pip install -U /kaggle/input/tasnim/orkatzfdata/torch-1.5.0+cu101-cp37-cp37m-linux_x86_64.whl /kaggle/input/tasnim/orkatzfdata/torchvision-0.6.0+cu101-cp37-cp37m-linux_x86_64.whl","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":false,"_kg_hide-output":false},"cell_type":"code","source":"!pip install /kaggle/input/pycocotoolso/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl\n!pip install /kaggle/input/tasnim/orkatzfdata/yacs-0.1.7-py3-none-any.whl \nif not os.path.exists('fvcore'):\n    os.makedirs('fvcore') \n!cp -R '/kaggle/input/tasnim/orkatzfdata/fvcore-0.1.dev200407/fvcore-0.1.dev200407/' ./fvcore \n!pip install fvcore/fvcore-0.1.dev200407/.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp -R /kaggle/input/tasnim/orkatzfdata/detectron2-ResNeSt/* ./detectron2-ResNeSt/\n!pip install detectron2-ResNeSt/.\n\nif not os.path.exists('detectron2-ResNeSt'):\n    os.makedirs('detectron2-ResNeSt ') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import detectron2 \nfrom detectron2.utils.logger import setup_logger #function to setup logging for libgs\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 #don't know\nfrom detectron2.engine import DefaultPredictor #prediction\nfrom detectron2.config import get_cfg #don't know\nfrom detectron2.utils.visualizer import Visualizer #visualizing the results\nfrom detectron2.data import MetadataCatalog #don't know","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"CFG is a configuration file format used for storing settings. CFG files are created by many programs to store information and settings that differ from the factory defaults. CFG files usually appear as text documents, and can be opened by word processors though it is not recommended.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from detectron2.config import get_cfg #reading cfg file\ncfg = get_cfg() #get_cfg changed it's name\n\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_cascade_rcnn_ResNeSt_101_FPN_syncbn_range-scale_1x.yaml\")) #coco-detection\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 1  #only wheat detection, so class number is 1\n\n\ncfg.MODEL.WEIGHTS = os.path.join('/kaggle/input/tasnim/best-inrae-1/', \"model_final.pth\") #get the model weights \ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4  # set the testing threshold for this model\ncfg.DATASETS.TEST = (\"m5_val\", ) #datasets test don't know\npredictor1 = DefaultPredictor(cfg) #predicting with predictor","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') #reading my submission file as dataframe","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): #format_prediction_string (csv file col 2)\n    pred_strings = [] #empty set taken\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])) #scores, bbox index\n\n    return \" \".join(pred_strings)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2 #image processing\nimport glob \ndef norm(s):\n    return s/s.max()-0.01 #normalization\nresults = []\nfor image_id in df_sub['image_id']:\n    im = cv2.imread('/kaggle/input/global-wheat-detection/test/{}.jpg'.format(image_id)) #reading image with image id\n    boxes = [] #bbox\n    scores = [] #score\n    labels = [] #label\n    outputs = predictor1(im) #default_predictor\n    out = outputs[\"instances\"].to(\"cpu\") #this detection is done in cpu\n    scores = out.get_fields()['scores'].numpy() #from output, they are fetching the scores field, converting to np array\n    boxes = out.get_fields()['pred_boxes'].tensor.numpy().astype(int) #prediction box as int type\n    labels= out.get_fields()['scores'].numpy() #labling the scores\n    boxes = boxes.astype(int) #boxes: did not understand the boxes thingi\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)} #fusion the result\n    results.append(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import pyplot as plt #for plotting data\nimage = im.copy() #copying the image\nsize = 300 #size of the image shown\nfont = cv2.FONT_HERSHEY_SIMPLEX  #the text_font\n  \n# org \norg = (50, 50) #why you exist bro\n  \n# fontScale \nfontScale = 1\n   \n# Blue color in BGR \ncolor = (255, 0, 0) #Blue color my boxes\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) #image shown in rectangle\n    image = cv2.putText(image, '{:.2}'.format(s), (b[0],b[1]), font,  \n                   fontScale, color, thickness, cv2.LINE_AA) #label the boxes\nplt.figure(figsize=[20,20]) #plot my figure\nplt.imshow(image[:,:,::-1]) #don't know\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":{"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}