{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Pytorch - FasterRCNN Inference\n* I used no internet in this notebook\n* You can find my train notebook [here](http://https://www.kaggle.com/godeep48/fasterrcnn-wheat-head-detection)."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#from tqdm import tqdm_notebook as tqdm\nfrom tqdm import tqdm \n\nimport cv2\nimport os\nimport re\n\nimport random\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"INPUT_DATA = \"../input/global-wheat-detection/\"\nTRAIN_DIR = os.path.join(INPUT_DATA, \"train\")\nTEST_DIR = os.path.join(INPUT_DATA, \"test\")\n\n#Path for the weight file.\nDIR_PATH = \"../input/fasterrcnn-wheat-head-detection\"\nWEIGHT_FILE = os.path.join(DIR_PATH, \"fasterrcnn_best_resnet50.pth\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.read_csv(os.path.join(INPUT_DATA, \"sample_submission.csv\"))\nprint(f\"Shape of test dataframe: {df_test.shape}\")\ndf_test.head(4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data Transform - Test Albumentation\ndef get_test_transform():\n    return A.Compose([\n        ToTensorV2(p=1.0)\n    ])\n\n\nclass WheatDatasetTest(Dataset):\n    def __init__(self, dataframe, image_dir, transform=None):\n        super().__init__()\n        self.dataframe = dataframe\n        self.image_dir = image_dir\n        self.transform = transform\n        self.image_ids = dataframe[\"image_id\"].unique()\n        \n    def __getitem__(self, idx):\n        image_id = self.image_ids[idx]\n        #details = self.dataframe[self.dataframe[\"image_id\"]==image_id]\n        img_path = os.path.join(TEST_DIR, image_id)+\".jpg\"\n        image = cv2.imread(img_path, cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        \n        if self.transform:\n            sample = {\n                'image': image,\n            }\n            \n            sample = self.transform(**sample)\n            image = sample['image']\n        \n        return image, image_id\n    \n    def __len__(self) -> int:\n        return len(self.image_ids)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load Test DataSet"},{"metadata":{"trusted":true},"cell_type":"code","source":"def collate_fn(batch):\n    return tuple(zip(*batch))\n\ntest_dataset = WheatDatasetTest(df_test, TEST_DIR, get_test_transform())\nprint(f\"Length of test dataset: {len(test_dataset)}\")\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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(WEIGHT_FILE, map_location=torch.device('cpu')))\nmodel.eval()\n\nx = model.to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"detection_threshold = 0.5\nresults = []\noutput_list = []\n\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        output_dict = {\n            'image_id': image_ids[i],\n            'boxes': outputs[i]['boxes'].data.cpu().numpy(),\n            'scores': outputs[i]['scores'].data.cpu().numpy()\n        }\n        output_list.append(output_dict)\n        \n        result = {\n            'image_id': image_id,\n            'PredictionString': format_prediction_string(boxes, scores)\n        }\n\n        \n        results.append(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ndf_test.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Predict Images"},{"metadata":{"trusted":true},"cell_type":"code","source":"## Plot image prediction\n\ndef predict_images(n_num, random_selection=True):\n    '''Plot N Number of Predicted Images'''\n    if random_selection:\n        index = random.sample(range(0, len(df_test[\"image_id\"].unique())), n_num)\n    else:\n        index = range(0, n_num)\n        \n    plt.figure(figsize=(15,15))\n    fig_no = 1\n    \n    for i in index:\n        images, image_id = test_dataset.__getitem__(i)\n        sample = images.permute(1,2,0).cpu().numpy()\n        boxes = output_list[i]['boxes']\n        scores = output_list[i]['scores']\n        boxes = boxes[scores >= detection_threshold].astype(np.int32)\n        #Plot figure/image\n        for box in boxes:\n            cv2.rectangle(sample,(box[0], box[1]),(box[2], box[3]),(255,223,0), 2)\n        plt.subplot(n_num/2, n_num/2, fig_no)\n        plt.imshow(sample)\n        fig_no+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict_images(4, True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Ref**: https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-inference/"}],"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}