{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport sys\nsys.path.insert(0, \"../input/weightedboxesfusion\")\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"\nfrom ensemble_boxes import *\nimport cv2\nimport os\nfrom tqdm.notebook import tqdm\nfrom glob import glob\nfrom PIL import Image\nimport torch\nimport torchvision\nfrom torchvision.models.detection.faster_rcnn import FasterRCNN, FastRCNNPredictor\nfrom torchvision.models.detection.rpn import AnchorGenerator\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensorV2\nfrom torch.utils.data import DataLoader, Dataset\nimport re\nfrom matplotlib import pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Utils data function","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# def read_bbox_from_str(s):\n#     s = s.replace(\"[\", \"\").replace(\"]\", \"\")\n#     char_bbox = s.split(\",\")\n#     bbox = [float(c) for c in char_bbox]\n#     return bbox\n\n\ndef 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    return \" \".join(pred_strings)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class WheatTestDataset(Dataset):\n    def __init__(self, img_ids, img_dir, transforms):\n        self.img_ids = img_ids\n        self.img_dir = img_dir\n        self.transforms = transforms\n        \n    def __getitem__(self, idx):\n        img_id = self.img_ids[idx]\n        img_fn = f\"{self.img_dir}/{img_id}.jpg\"\n        img = cv2.imread(img_fn)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32)\n        img /= 255.0\n        if self.transforms:\n            sample = {\n                'image': img,\n            }\n            sample = self.transforms(**sample)\n            img = sample['image']\n        return img_id, img\n        \n    def __len__(self):\n        return len(self.img_ids)\n    \n    \ndef collate_fn(batch):\n    return tuple(zip(*batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntest_df = pd.read_csv(\"/kaggle/input/global-wheat-detection/sample_submission.csv\")\nimg_ids = test_df[\"image_id\"]\nprint(\"number of image:\",  len(img_ids))\nimg_dir = \"/kaggle/input/global-wheat-detection/test\"\n\ntest_transform = A.Compose([ToTensorV2(p=1.0)])\ntest_dataset = WheatTestDataset(img_ids, img_dir, test_transform)\ntest_dataloader = DataLoader(\n    test_dataset,\n    batch_size=8,\n    shuffle=False,\n    num_workers=2,\n    collate_fn=collate_fn\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_class = 2\n\nweight_file = \"/kaggle/input/modev5/model_800_0.82.pth\"\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False, pretrained_backbone=False)\nin_features = model.roi_heads.box_predictor.cls_score.in_features\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, nb_class)\n\nif os.path.isfile(weight_file):\n    print(\"loading ...\")\n    model.load_state_dict(torch.load(weight_file))\n    \nparams = [p for p in model.parameters() if p.requires_grad]\noptimizer = torch.optim.SGD(params, lr=0.005, momentum=0, weight_decay=0.0005)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\nmodel.to(device)\nmodel.eval()\nprint(\"\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def run_wbf(prediction, image_size=1024, iou_thr=0.44, skip_box_thr=0.43, weights=None):\n    boxes = [(prediction['boxes']/(image_size-1)).tolist()]\n    scores = [prediction['scores'].tolist()]\n    labels = [np.ones(prediction['scores'].shape[0]).tolist()]\n    boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr)\n    boxes = boxes*(image_size-1)\n    return boxes, scores, labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"thresh = 0.5\nresults = []\n\nfor image_ids, images in tqdm(test_dataloader):\n    images = list(image.to(device) for image in images)\n    predictions = model(images)\n\n    for i, image in enumerate(images):\n#         boxes, scores, _ = run_wbf(predictions[i], iou_thr=0.4)\n        boxes = predictions[i][\"boxes\"]\n        scores = predictions[i][\"scores\"]\n    \n#         indicies = torchvision.ops.nms(boxes, scores, iou_threshold=0.5)\n#         boxes = boxes[indicies].data.cpu().numpy().astype(np.int32).clip(min=0, max=1024)\n#         scores = scores[indicies].data.cpu().numpy()\n\n        boxes = boxes.data.cpu().numpy().astype(np.int32).clip(min=0, max=1024)\n        scores = scores.data.cpu().numpy()\n        boxes = boxes[scores >= thresh]\n        scores = scores[scores >= thresh]\n        \n        boxes[:, 2] = (boxes[:, 2] - boxes[:, 0])\n        boxes[:, 3] = (boxes[:, 3] - boxes[:, 1])\n\n#         boxes[:, 0] = boxes[:,0] - boxes[:,2]*0.1\n#         boxes[:, 1] = boxes[:,1] - boxes[:,3]*0.1\n        result = {\n            'image_id': image_ids[i],\n            'PredictionString': format_prediction_string(boxes, scores)\n        }\n        results.append(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.head()","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}