{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":409982,"sourceType":"modelInstanceVersion","isSourceIdPinned":false,"modelInstanceId":334833,"modelId":355861},{"sourceId":411604,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":336063,"modelId":357072}],"dockerImageVersionId":31041,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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-faster-rcnn-v2/pytorch/default/1'\n\nWEIGHTS_FILE = f'{DIR_WEIGHTS}/fasterrcnn_resnet50_fpn.pth'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:21.893473Z","iopub.execute_input":"2025-05-24T09:48:21.894167Z","iopub.status.idle":"2025-05-24T09:48:31.015464Z","shell.execute_reply.started":"2025-05-24T09:48:21.894144Z","shell.execute_reply":"2025-05-24T09:48:31.014743Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df = pd.read_csv(f\"{DIR_INPUT}/sample_submission.csv\")\ntest_df.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:31.016812Z","iopub.execute_input":"2025-05-24T09:48:31.017316Z","iopub.status.idle":"2025-05-24T09:48:31.037258Z","shell.execute_reply.started":"2025-05-24T09:48:31.017297Z","shell.execute_reply":"2025-05-24T09:48:31.036690Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:31.037915Z","iopub.execute_input":"2025-05-24T09:48:31.038112Z","iopub.status.idle":"2025-05-24T09:48:31.049524Z","shell.execute_reply.started":"2025-05-24T09:48:31.038096Z","shell.execute_reply":"2025-05-24T09:48:31.048780Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_test_transform():\n    return A.Compose([\n        # A.Resize(512, 512),\n        ToTensorV2(p=1.0)\n    ])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:31.051144Z","iopub.execute_input":"2025-05-24T09:48:31.051333Z","iopub.status.idle":"2025-05-24T09:48:31.061002Z","shell.execute_reply.started":"2025-05-24T09:48:31.051319Z","shell.execute_reply":"2025-05-24T09:48:31.060373Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:31.061567Z","iopub.execute_input":"2025-05-24T09:48:31.061882Z","iopub.status.idle":"2025-05-24T09:48:31.660936Z","shell.execute_reply.started":"2025-05-24T09:48:31.061862Z","shell.execute_reply":"2025-05-24T09:48:31.660359Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:31.661534Z","iopub.execute_input":"2025-05-24T09:48:31.661773Z","iopub.status.idle":"2025-05-24T09:48:34.445164Z","shell.execute_reply.started":"2025-05-24T09:48:31.661750Z","shell.execute_reply":"2025-05-24T09:48:34.444569Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:34.445873Z","iopub.execute_input":"2025-05-24T09:48:34.446134Z","iopub.status.idle":"2025-05-24T09:48:34.459383Z","shell.execute_reply.started":"2025-05-24T09:48:34.446103Z","shell.execute_reply":"2025-05-24T09:48:34.458779Z"}},"outputs":[],"execution_count":null},{"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:34.460157Z","iopub.execute_input":"2025-05-24T09:48:34.460754Z","iopub.status.idle":"2025-05-24T09:48:34.473934Z","shell.execute_reply.started":"2025-05-24T09:48:34.460715Z","shell.execute_reply":"2025-05-24T09:48:34.473298Z"}},"outputs":[],"execution_count":null},{"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        results.append(result)\n\nresults[:2]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:48:34.474551Z","iopub.execute_input":"2025-05-24T09:48:34.474762Z","iopub.status.idle":"2025-05-24T09:48:36.536186Z","shell.execute_reply.started":"2025-05-24T09:48:34.474720Z","shell.execute_reply":"2025-05-24T09:48:36.535318Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:49:03.042959Z","iopub.execute_input":"2025-05-24T09:49:03.043249Z","iopub.status.idle":"2025-05-24T09:49:03.063118Z","shell.execute_reply.started":"2025-05-24T09:49:03.043223Z","shell.execute_reply":"2025-05-24T09:49:03.062370Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:49:10.748698Z","iopub.execute_input":"2025-05-24T09:49:10.749006Z","iopub.status.idle":"2025-05-24T09:49:10.766040Z","shell.execute_reply.started":"2025-05-24T09:49:10.748986Z","shell.execute_reply":"2025-05-24T09:49:10.765177Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:49:15.662861Z","iopub.execute_input":"2025-05-24T09:49:15.663656Z","iopub.status.idle":"2025-05-24T09:49:16.297196Z","shell.execute_reply.started":"2025-05-24T09:49:15.663633Z","shell.execute_reply":"2025-05-24T09:49:16.296449Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-24T09:49:24.359910Z","iopub.execute_input":"2025-05-24T09:49:24.360199Z","iopub.status.idle":"2025-05-24T09:49:24.368864Z","shell.execute_reply.started":"2025-05-24T09:49:24.360176Z","shell.execute_reply":"2025-05-24T09:49:24.368289Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}