{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":10338,"databundleVersionId":862042,"sourceType":"competition"},{"sourceId":1403676,"sourceType":"datasetVersion","datasetId":789895},{"sourceId":7213657,"sourceType":"datasetVersion","datasetId":4174243},{"sourceId":40875834,"sourceType":"kernelVersion"}],"dockerImageVersionId":29981,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"%%writefile test.py\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport os\nimport re\nimport albumentations as A\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\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data.sampler import SequentialSampler\nfrom PIL import Image\nfrom albumentations.pytorch.transforms import ToTensorV2\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\nDIR_INPUT = '../input/rsna-pneumonia-detection-2018/input'\nDIR_TEST = f\"{DIR_INPUT}/samples\"\ntest_images = os.listdir(DIR_TEST)\nprint(f\"Validation instances: {len(test_images)}\")\n\n# load a model; pre-trained on COCO\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True, min_size=1024)\nnum_classes = 2  # 1 class (pnueomonia) + background\n# get the number of input features for the classifier\nin_features = model.roi_heads.box_predictor.cls_score.in_features\n# replace the pre-trained head with a new one\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n\nos.makedirs('../validation_predictions', exist_ok=True)\nmodel.load_state_dict(torch.load('../input/rsna-pytorch-hackathon-fasterrcnn-resnet-training/fasterrcnn_resnet50_fpn.pth'))\nmodel.to(device)\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], \n                                                             int(j[1][0]), int(j[1][1]), \n                                                             int(j[1][2]), int(j[1][3])))\n\n    return \" \".join(pred_strings)\n\ndetection_threshold = 0.9\nimg_num = 0\nresults = []\nmodel.eval()\nwith torch.no_grad():\n    for i, image in tqdm(enumerate(test_images), total=len(test_images)):\n\n        orig_image = cv2.imread(f\"{DIR_TEST}/{test_images[i]}\", cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        image = np.transpose(image, (2, 0, 1)).astype(np.float32)\n        image = torch.tensor(image, dtype=torch.float).cuda()\n        image = torch.unsqueeze(image, 0)\n\n        model.eval()\n        cpu_device = torch.device(\"cpu\")\n\n        outputs = model(image)\n        \n        outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs]\n        if len(outputs[0]['boxes']) != 0:\n            for counter in range(len(outputs[0]['boxes'])):\n                boxes = outputs[0]['boxes'].data.cpu().numpy()\n                scores = outputs[0]['scores'].data.cpu().numpy()\n                boxes = boxes[scores >= detection_threshold].astype(np.int32)\n                draw_boxes = boxes.copy()\n                boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n                boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n                \n            for box in draw_boxes:\n                cv2.rectangle(orig_image,\n                            (int(box[0]), int(box[1])),\n                            (int(box[2]), int(box[3])),\n                            (0, 0, 255), 3)\n        \n            plt.imshow(cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB))\n            plt.axis('off')\n            plt.close()\n                \n            result = {\n                'patientId': test_images[i].split('.')[0],\n                'PredictionString': format_prediction_string(boxes, scores)\n            }\n            results.append(result)\n        else:\n            result = {\n                'patientId': test_images[i].split('.')[0],\n                'PredictionString': None\n            }\n            results.append(result)\n\nsub_df = pd.DataFrame(results, columns=['patientId', 'PredictionString'])\nprint(sub_df.head())\nsub_df.to_csv('submission.csv', index=False)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-16T07:36:16.853961Z","iopub.execute_input":"2023-12-16T07:36:16.854747Z","iopub.status.idle":"2023-12-16T07:36:16.863199Z","shell.execute_reply.started":"2023-12-16T07:36:16.854713Z","shell.execute_reply":"2023-12-16T07:36:16.862320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python test.py","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2023-12-16T07:36:16.864972Z","iopub.execute_input":"2023-12-16T07:36:16.865400Z","iopub.status.idle":"2023-12-16T07:48:26.395193Z","shell.execute_reply.started":"2023-12-16T07:36:16.865367Z","shell.execute_reply":"2023-12-16T07:48:26.394021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}