{"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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        \n        os.path.join(dirname, filename)\n\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":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nimport cv2\nfrom torchvision import datasets,transforms\nfrom glob import glob\nimport os\nfrom PIL import Image\nfrom matplotlib import patches\nfrom torch.utils.data import Dataset\nimport torchvision\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nfrom torchvision.models.detection.rpn import AnchorGenerator\nfrom torch.utils.data import DataLoader\n#Albumentation\nimport albumentations as al\nfrom albumentations.pytorch.transforms import ToTensorV2\n\ntrain_dir ='/kaggle/input/global-wheat-detection/train/'\ntest_dir = '/kaggle/input/global-wheat-detection/test/'\ntrain = pd.read_csv('../input/global-wheat-detection/train.csv') \nweights = '../input/weights/fasterrcnn_resnet50_fpn (1).pth'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = pd.read_csv('../input/global-wheat-detection/sample_submission.csv')\nsample.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Wheatdatasets(Dataset):\n    \n    def __init__(self,dataframe,image_dir,transforms = None):\n        \n        super().__init__()\n    \n        self.image_id = dataframe['image_id'].unique()\n        self.df = dataframe\n        self.img_dir = image_dir\n        self.transforms = transforms\n        \n    def __getitem__(self,index:int):\n        \n        image_id = self.image_id[index]\n        record = self.df[self.df['image_id']==image_id]\n        \n        image = cv2.imread(self.img_dir+image_id+'.jpg',cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB).astype(np.float32)\n        image = image/255.0\n       \n        if self.transforms:\n            sample ={\n                'image':image\n            }\n            sample =self.transforms(**sample)\n            image = sample['image']\n            \n            return image,image_id\n        \n    def __len__(self) -> int:\n        return self.image_id.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_transform():\n    return al.Compose([\n        ToTensorV2(p=1.0)\n    ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create the Model\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained = True,pretrained_backbone=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else 'cpu'\nnum_class = 2 #wheats and background\n\nin_feature = model.roi_heads.box_predictor.cls_score.in_features\n\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_feature,num_class) #changin the pretrained head with a new one\n\nmodel.load_state_dict(torch.load(weights))\nmodel.eval()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = model.to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\n\ntest_dataset = Wheatdatasets(sample,test_dir,get_transform())\n\n\n\ntest_dataloader = DataLoader(\ntest_dataset,\nbatch_size=4,\nshuffle =False,\nnum_workers =4,drop_last = False,\ncollate_fn = collate_fn)\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def format_string(boxes,score):\n    pred_strings = []\n    for j in zip(score,boxes):\n        \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":"detection_threshold = 0.5\nresults = []\n\nfor images, image_ids in test_dataloader:\n\n    images = list(image.to(device) for image in images)\n    outputs = model(images)\n\n    for i, image in enumerate(images):\n\n        boxes = outputs[i]['boxes'].data.cpu().numpy()\n        scores = outputs[i]['scores'].data.cpu().numpy()\n        \n        boxes = boxes[scores >= detection_threshold].astype(np.int32)\n        scores = scores[scores >= detection_threshold]\n        image_id = image_ids[i]\n        \n        boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n        boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n        \n        result = {\n            'image_id': image_id,\n            'PredictionString': format_string(boxes, scores)\n        }\n\n        \n        results.append(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results[:2]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\ntest_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = images[0].permute(1,2,0).cpu().numpy()\nboxes = outputs[0]['boxes'].data.cpu().numpy()\nscore = outputs[0]['scores'].data.cpu().numpy()\n\nboxes = boxes[score >= detection_threshold].astype(np.int32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1, 1, figsize=(16, 8))\n\nfor box in boxes:\n    cv2.rectangle(sample,\n                  (box[0], box[1]),\n                  (box[2], box[3]),\n                  (220, 0, 0), 2)\n    \nax.set_axis_off()\nax.imshow(sample)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_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}