{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Pytorch starter - FasterRCNN Inference\n\n- You can find the [train notebook here](https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-train)\n- The weights are [available here](https://www.kaggle.com/dataset/7d5f1ed9454c848ecb909c109c6fa8e573ea4de299e249c79edc6f47660bf4c5)","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport os\nimport re\n\nfrom PIL import Image\n\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensorV2\n\nimport torch\nimport torchvision\n\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nfrom torchvision.models.detection.rpn import AnchorGenerator\n\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data.sampler import SequentialSampler\n\nfrom matplotlib import pyplot as plt\n\nDIR_INPUT = '/kaggle/input/global-wheat-detection'\nDIR_TRAIN = f'{DIR_INPUT}/train'\nDIR_TEST = f'{DIR_INPUT}/test'\n\nDIR_WEIGHTS = '/kaggle/input/global-wheat-detection-public'\n\nWEIGHTS_FILE = f'{DIR_WEIGHTS}/fasterrcnn_resnet50_fpn_best.pth'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-05T11:04:11.294701Z","iopub.execute_input":"2023-11-05T11:04:11.295170Z","iopub.status.idle":"2023-11-05T11:04:14.016875Z","shell.execute_reply.started":"2023-11-05T11:04:11.295105Z","shell.execute_reply":"2023-11-05T11:04:14.015998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv(f'{DIR_INPUT}/sample_submission.csv')\ntest_df.shape","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2023-11-05T11:04:14.018949Z","iopub.execute_input":"2023-11-05T11:04:14.019264Z","iopub.status.idle":"2023-11-05T11:04:14.038312Z","shell.execute_reply.started":"2023-11-05T11:04:14.019208Z","shell.execute_reply":"2023-11-05T11:04:14.037592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class WheatTestDataset(Dataset):\n\n    def __init__(self, dataframe, image_dir, transforms=None):\n        super().__init__()\n\n        self.image_ids = dataframe['image_id'].unique()\n        self.df = dataframe\n        self.image_dir = image_dir\n        self.transforms = transforms\n\n    def __getitem__(self, index: int):\n\n        image_id = self.image_ids[index]\n        records = self.df[self.df['image_id'] == image_id]\n\n        image = cv2.imread(f'{self.image_dir}/{image_id}.jpg', cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        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_ids.shape[0]","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:14.039436Z","iopub.execute_input":"2023-11-05T11:04:14.039695Z","iopub.status.idle":"2023-11-05T11:04:14.050812Z","shell.execute_reply.started":"2023-11-05T11:04:14.039658Z","shell.execute_reply":"2023-11-05T11:04:14.050046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Albumentations\ndef get_test_transform():\n    return A.Compose([\n        # A.Resize(512, 512),\n        ToTensorV2(p=1.0)\n    ])\n","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:14.052043Z","iopub.execute_input":"2023-11-05T11:04:14.052341Z","iopub.status.idle":"2023-11-05T11:04:14.067066Z","shell.execute_reply.started":"2023-11-05T11:04:14.052292Z","shell.execute_reply":"2023-11-05T11:04:14.066170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:14.070366Z","iopub.execute_input":"2023-11-05T11:04:14.070709Z","iopub.status.idle":"2023-11-05T11:04:14.612488Z","shell.execute_reply.started":"2023-11-05T11:04:14.070666Z","shell.execute_reply":"2023-11-05T11:04:14.611570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\nnum_classes = 2  # 1 class (wheat) + background\n\n# get number of input features for the classifier\nin_features = model.roi_heads.box_predictor.cls_score.in_features\n\n# replace the pre-trained head with a new one\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n\n# Load the trained weights\nmodel.load_state_dict(torch.load(WEIGHTS_FILE))\nmodel.eval()\n\nx = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:14.614289Z","iopub.execute_input":"2023-11-05T11:04:14.614693Z","iopub.status.idle":"2023-11-05T11:04:19.695113Z","shell.execute_reply.started":"2023-11-05T11:04:14.614630Z","shell.execute_reply":"2023-11-05T11:04:19.694255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\ntest_dataset = WheatTestDataset(test_df, DIR_TEST, get_test_transform())\n\ntest_data_loader = DataLoader(\n    test_dataset,\n    batch_size=4,\n    shuffle=False,\n    num_workers=4,\n    drop_last=False,\n    collate_fn=collate_fn\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:19.696354Z","iopub.execute_input":"2023-11-05T11:04:19.696621Z","iopub.status.idle":"2023-11-05T11:04:19.705722Z","shell.execute_reply.started":"2023-11-05T11:04:19.696583Z","shell.execute_reply":"2023-11-05T11:04:19.704641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:19.707007Z","iopub.execute_input":"2023-11-05T11:04:19.707310Z","iopub.status.idle":"2023-11-05T11:04:19.731427Z","shell.execute_reply.started":"2023-11-05T11:04:19.707268Z","shell.execute_reply":"2023-11-05T11:04:19.730669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"detection_threshold = 0.5\nresults = []\n\nfor images, image_ids in test_data_loader:\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_prediction_string(boxes, scores)\n        }\n\n        \n        results.append(result)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:19.732810Z","iopub.execute_input":"2023-11-05T11:04:19.733185Z","iopub.status.idle":"2023-11-05T11:04:21.535212Z","shell.execute_reply.started":"2023-11-05T11:04:19.733130Z","shell.execute_reply":"2023-11-05T11:04:21.533973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[0:2]","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:21.537635Z","iopub.execute_input":"2023-11-05T11:04:21.538012Z","iopub.status.idle":"2023-11-05T11:04:21.543830Z","shell.execute_reply.started":"2023-11-05T11:04:21.537952Z","shell.execute_reply":"2023-11-05T11:04:21.543039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:21.545142Z","iopub.execute_input":"2023-11-05T11:04:21.545448Z","iopub.status.idle":"2023-11-05T11:04:21.566536Z","shell.execute_reply.started":"2023-11-05T11:04:21.545404Z","shell.execute_reply":"2023-11-05T11:04:21.565734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = images[1].permute(1,2,0).cpu().numpy()\nboxes = outputs[1]['boxes'].data.cpu().numpy()\nscores = outputs[1]['scores'].data.cpu().numpy()\n\nboxes = boxes[scores >= detection_threshold].astype(np.int32)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:21.567668Z","iopub.execute_input":"2023-11-05T11:04:21.568020Z","iopub.status.idle":"2023-11-05T11:04:21.577712Z","shell.execute_reply.started":"2023-11-05T11:04:21.567974Z","shell.execute_reply":"2023-11-05T11:04:21.577086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:21.578981Z","iopub.execute_input":"2023-11-05T11:04:21.579247Z","iopub.status.idle":"2023-11-05T11:04:21.929533Z","shell.execute_reply.started":"2023-11-05T11:04:21.579204Z","shell.execute_reply":"2023-11-05T11:04:21.928463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-05T11:04:21.930886Z","iopub.execute_input":"2023-11-05T11:04:21.931245Z","iopub.status.idle":"2023-11-05T11:04:22.285736Z","shell.execute_reply.started":"2023-11-05T11:04:21.931191Z","shell.execute_reply":"2023-11-05T11:04:22.284112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}