{"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":"**环境配置**","metadata":{}},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\nimport torch, torchvision\nimport pandas as pd \n\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nfrom pathlib import Path\nimport numpy as np \nimport cv2\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:36:49.458195Z","iopub.execute_input":"2023-06-24T19:36:49.459230Z","iopub.status.idle":"2023-06-24T19:36:51.649781Z","shell.execute_reply.started":"2023-06-24T19:36:49.459119Z","shell.execute_reply":"2023-06-24T19:36:51.648538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = Path('/kaggle/input/global-wheat-detection')\ntest_df = pd.read_csv('/kaggle/input/global-wheat-detection/sample_submission.csv')\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:36:51.656506Z","iopub.execute_input":"2023-06-24T19:36:51.659582Z","iopub.status.idle":"2023-06-24T19:36:51.697104Z","shell.execute_reply.started":"2023-06-24T19:36:51.659534Z","shell.execute_reply":"2023-06-24T19:36:51.696074Z"},"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-06-24T19:36:51.702086Z","iopub.execute_input":"2023-06-24T19:36:51.704686Z","iopub.status.idle":"2023-06-24T19:36:51.719104Z","shell.execute_reply.started":"2023-06-24T19:36:51.704646Z","shell.execute_reply":"2023-06-24T19:36:51.717934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Transform**","metadata":{}},{"cell_type":"code","source":"# Albumentations\nimport albumentations as A\nimport cv2\nfrom albumentations.pytorch.transforms import ToTensorV2\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-06-24T19:36:51.727177Z","iopub.execute_input":"2023-06-24T19:36:51.729880Z","iopub.status.idle":"2023-06-24T19:36:54.243068Z","shell.execute_reply.started":"2023-06-24T19:36:51.729822Z","shell.execute_reply":"2023-06-24T19:36:54.241802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:36:54.244730Z","iopub.execute_input":"2023-06-24T19:36:54.245164Z","iopub.status.idle":"2023-06-24T19:36:54.330174Z","shell.execute_reply.started":"2023-06-24T19:36:54.245119Z","shell.execute_reply":"2023-06-24T19:36:54.328602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Loading Model**","metadata":{}},{"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-06-24T19:36:54.331810Z","iopub.execute_input":"2023-06-24T19:36:54.333140Z","iopub.status.idle":"2023-06-24T19:36:55.366605Z","shell.execute_reply.started":"2023-06-24T19:36:54.333095Z","shell.execute_reply":"2023-06-24T19:36:55.365540Z"},"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(\"/kaggle/input/global-wheat-detection-pytorch/model.pth\"))\nmodel.eval()\n\nx = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:36:55.369611Z","iopub.execute_input":"2023-06-24T19:36:55.371050Z","iopub.status.idle":"2023-06-24T19:37:00.085787Z","shell.execute_reply.started":"2023-06-24T19:36:55.371009Z","shell.execute_reply":"2023-06-24T19:37:00.084750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Utilities Functions**","metadata":{}},{"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\ntest_dataset = WheatTestDataset(test_df, path/'test', get_test_transform())\n\ntest_data_loader = DataLoader(\n    test_dataset,\n    batch_size=4,\n    shuffle=False,\n    num_workers=2,\n    drop_last=False,\n    collate_fn=collate_fn\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:37:00.087343Z","iopub.execute_input":"2023-06-24T19:37:00.088412Z","iopub.status.idle":"2023-06-24T19:37:00.100418Z","shell.execute_reply.started":"2023-06-24T19:37:00.088378Z","shell.execute_reply":"2023-06-24T19:37:00.098377Z"},"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-06-24T19:37:00.102079Z","iopub.execute_input":"2023-06-24T19:37:00.102751Z","iopub.status.idle":"2023-06-24T19:37:00.111041Z","shell.execute_reply.started":"2023-06-24T19:37:00.102712Z","shell.execute_reply":"2023-06-24T19:37:00.109847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Prediction On Test DataLoader**","metadata":{}},{"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)","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:37:00.112847Z","iopub.execute_input":"2023-06-24T19:37:00.113250Z","iopub.status.idle":"2023-06-24T19:37:07.091791Z","shell.execute_reply.started":"2023-06-24T19:37:00.113210Z","shell.execute_reply":"2023-06-24T19:37:07.090400Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[0:2]","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:37:07.096449Z","iopub.execute_input":"2023-06-24T19:37:07.096812Z","iopub.status.idle":"2023-06-24T19:37:07.104188Z","shell.execute_reply.started":"2023-06-24T19:37:07.096777Z","shell.execute_reply":"2023-06-24T19:37:07.103221Z"},"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-06-24T19:37:07.105666Z","iopub.execute_input":"2023-06-24T19:37:07.106348Z","iopub.status.idle":"2023-06-24T19:37:07.123936Z","shell.execute_reply.started":"2023-06-24T19:37:07.106310Z","shell.execute_reply":"2023-06-24T19:37:07.122817Z"},"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-06-24T19:37:07.125786Z","iopub.execute_input":"2023-06-24T19:37:07.126146Z","iopub.status.idle":"2023-06-24T19:37:07.144814Z","shell.execute_reply.started":"2023-06-24T19:37:07.126107Z","shell.execute_reply":"2023-06-24T19:37:07.143901Z"},"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-06-24T19:37:07.146227Z","iopub.execute_input":"2023-06-24T19:37:07.146664Z","iopub.status.idle":"2023-06-24T19:37:07.732784Z","shell.execute_reply.started":"2023-06-24T19:37:07.146625Z","shell.execute_reply":"2023-06-24T19:37:07.731801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-06-24T19:37:07.733762Z","iopub.execute_input":"2023-06-24T19:37:07.734077Z","iopub.status.idle":"2023-06-24T19:37:07.743371Z","shell.execute_reply.started":"2023-06-24T19:37:07.734046Z","shell.execute_reply":"2023-06-24T19:37:07.742448Z"},"trusted":true},"execution_count":null,"outputs":[]}]}