{"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":"code","source":"!conda install '/kaggle/input/pydicom-conda-helper/libjpeg-turbo-2.1.0-h7f98852_0.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/libgcc-ng-9.3.0-h2828fa1_19.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/gdcm-2.8.9-py37h500ead1_1.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/conda-4.10.1-py37h89c1867_0.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/certifi-2020.12.5-py37h89c1867_1.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/openssl-1.1.1k-h7f98852_0.tar.bz2' -c conda-forge -y","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:01:47.890855Z","iopub.execute_input":"2021-07-07T09:01:47.891229Z","iopub.status.idle":"2021-07-07T09:02:58.045499Z","shell.execute_reply.started":"2021-07-07T09:01:47.891147Z","shell.execute_reply":"2021-07-07T09:02:58.044566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:02:58.04722Z","iopub.execute_input":"2021-07-07T09:02:58.047555Z","iopub.status.idle":"2021-07-07T09:02:58.061342Z","shell.execute_reply.started":"2021-07-07T09:02:58.047517Z","shell.execute_reply":"2021-07-07T09:02:58.060514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nif df.shape[0] == 2477:\n    fast_sub = True\n    fast_df = pd.DataFrame(([['00086460a852_study', 'negative 1 0 0 1 1'], \n                         ['000c9c05fd14_study', 'negative 1 0 0 1 1'], \n                         ['65761e66de9f_image', 'none 1 0 0 1 1'], \n                         ['51759b5579bc_image', 'none 1 0 0 1 1']]), \n                       columns=['id', 'PredictionString'])\nelse:\n    fast_sub = False","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:02:58.063324Z","iopub.execute_input":"2021-07-07T09:02:58.063663Z","iopub.status.idle":"2021-07-07T09:02:58.090464Z","shell.execute_reply.started":"2021-07-07T09:02:58.063627Z","shell.execute_reply":"2021-07-07T09:02:58.089675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    # Original from: https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n    \n    # 近似3个标准差内数据\n    q1,q2,q3 = np.quantile(data, [.15865,.5,.84135]) \n    iqr = q3 - q1\n    multiplier = 1.5\n\n    mask = ((q2 - multiplier * iqr) < data) & (data < (q2 + multiplier * iqr))\n    \n    if data[mask].size != 0:\n        p = .001\n        data = data.astype(np.float32) - np.quantile(data[mask], p)\n        data = data / np.quantile(data[mask], 1-p)\n    else:\n        data = data - np.min(data)\n        data = data / np.max(data)\n\n    data = np.clip(data, 0, 1)\n    data = (data * 255).astype(np.uint8)\n        \n    return data","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:02:58.091982Z","iopub.execute_input":"2021-07-07T09:02:58.092301Z","iopub.status.idle":"2021-07-07T09:02:58.380314Z","shell.execute_reply.started":"2021-07-07T09:02:58.092269Z","shell.execute_reply":"2021-07-07T09:02:58.379488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    # Original from: https://www.kaggle.com/xhlulu/vinbigdata-process-and-resize-to-image\n    im = Image.fromarray(array)\n    \n    if keep_ratio:\n        im.thumbnail((size, size), resample)\n    else:\n        im = im.resize((size, size), resample)\n    \n    return im","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:02:58.38327Z","iopub.execute_input":"2021-07-07T09:02:58.383528Z","iopub.status.idle":"2021-07-07T09:02:58.390011Z","shell.execute_reply.started":"2021-07-07T09:02:58.3835Z","shell.execute_reply":"2021-07-07T09:02:58.389162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"split = 'test'\nsave_dir = f'/kaggle/tmp/{split}/'\n\nos.makedirs(save_dir, exist_ok=True)\n\nsave_dir = f'/kaggle/tmp/{split}/study/'\nos.makedirs(save_dir, exist_ok=True)\nif fast_sub:\n    xray = read_xray('../input/siim-covid19-detection/train/00086460a852/9e8302230c91/65761e66de9f.dcm')\n    im = resize(xray, size=600)  \n    study = '00086460a852' + '_study.png'\n    im.save(os.path.join(save_dir, study))\n    xray = read_xray('../input/siim-covid19-detection/train/000c9c05fd14/e555410bd2cd/51759b5579bc.dcm')\n    im = resize(xray, size=600)  \n    study = '000c9c05fd14' + '_study.png'\n    im.save(os.path.join(save_dir, study))\nelse:   \n    for dirname, _, filenames in tqdm(os.walk(f'../input/siim-covid19-detection/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=600)  \n            study = dirname.split('/')[-2] + '_study.png'\n            im.save(os.path.join(save_dir, study))","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:02:58.393217Z","iopub.execute_input":"2021-07-07T09:02:58.393479Z","iopub.status.idle":"2021-07-07T09:03:00.298309Z","shell.execute_reply.started":"2021-07-07T09:02:58.393451Z","shell.execute_reply":"2021-07-07T09:03:00.29726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_id = []\ndim0 = []\ndim1 = []\nsplits = []\nsave_dir = f'/kaggle/tmp/{split}/image/'\nos.makedirs(save_dir, exist_ok=True)\nif fast_sub:\n    xray = read_xray('../input/siim-covid19-detection/train/00086460a852/9e8302230c91/65761e66de9f.dcm')\n    im = resize(xray, size=640)  \n    im.save(os.path.join(save_dir,'65761e66de9f_image.png'))\n    image_id.append('65761e66de9f.dcm'.replace('.dcm', ''))\n    dim0.append(xray.shape[0])\n    dim1.append(xray.shape[1])\n    splits.append(split)\n    xray = read_xray('../input/siim-covid19-detection/train/000c9c05fd14/e555410bd2cd/51759b5579bc.dcm')\n    im = resize(xray, size=640)  \n    im.save(os.path.join(save_dir, '51759b5579bc_image.png'))\n    image_id.append('51759b5579bc.dcm'.replace('.dcm', ''))\n    dim0.append(xray.shape[0])\n    dim1.append(xray.shape[1])\n    splits.append(split)\nelse:\n    for dirname, _, filenames in tqdm(os.walk(f'../input/siim-covid19-detection/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=640)  \n            im.save(os.path.join(save_dir, file.replace('.dcm', '_image.png')))\n            image_id.append(file.replace('.dcm', ''))\n            dim0.append(xray.shape[0])\n            dim1.append(xray.shape[1])\n            splits.append(split)\nmeta = pd.DataFrame.from_dict({'image_id': image_id, 'dim0': dim0, 'dim1': dim1, 'split': splits})","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:03:00.30259Z","iopub.execute_input":"2021-07-07T09:03:00.302964Z","iopub.status.idle":"2021-07-07T09:03:00.947084Z","shell.execute_reply.started":"2021-07-07T09:03:00.302927Z","shell.execute_reply":"2021-07-07T09:03:00.946201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nif fast_sub:\n    df = fast_df.copy()\nelse:\n    df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nid_laststr_list  = []\nfor i in range(df.shape[0]):\n    id_laststr_list.append(df.loc[i,'id'][-1])\ndf['id_last_str'] = id_laststr_list\n\nstudy_len = df[df['id_last_str'] == 'y'].shape[0]","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:03:00.948365Z","iopub.execute_input":"2021-07-07T09:03:00.948718Z","iopub.status.idle":"2021-07-07T09:03:00.962836Z","shell.execute_reply.started":"2021-07-07T09:03:00.948684Z","shell.execute_reply":"2021-07-07T09:03:00.961875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install /kaggle/input/kerasapplications -q\n!pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps\n\nimport os\n\nimport efficientnet.tfkeras as efn\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ndef auto_select_accelerator():\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n\n    return strategy\n\n\ndef build_decoder(with_labels=True, target_size=(300, 300), ext='jpg'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3)\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3)\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.cast(img, tf.float32) / 255.0\n        img = tf.image.resize(img, target_size)\n\n        return img\n\n    def decode_with_labels(path, label):\n        return decode(path), label\n\n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True):\n    def augment(img):\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_flip_up_down(img)\n        return img\n\n    def augment_with_labels(img, label):\n        return augment(img), label\n\n    return augment_with_labels if with_labels else augment\n\n\ndef build_dataset(paths, labels=None, bsize=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=1024, \n                  cache_dir=\"\"):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n\n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n\n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n\n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\n\n    dset = tf.data.Dataset.from_tensor_slices(slices)\n    dset = dset.map(decode_fn, num_parallel_calls=AUTO)\n    dset = dset.cache(cache_dir) if cache else dset\n    dset = dset.map(augment_fn, num_parallel_calls=AUTO) if augment else dset\n    dset = dset.repeat() if repeat else dset\n    dset = dset.shuffle(shuffle) if shuffle else dset\n    dset = dset.batch(bsize).prefetch(AUTO)\n\n    return dset\n","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:03:00.966143Z","iopub.execute_input":"2021-07-07T09:03:00.966505Z","iopub.status.idle":"2021-07-07T09:03:57.204718Z","shell.execute_reply.started":"2021-07-07T09:03:00.966474Z","shell.execute_reply":"2021-07-07T09:03:57.203691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#COMPETITION_NAME = \"siim-cov19-test-img512-study-600\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16\n\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512)\nif fast_sub:\n    sub_df = fast_df.copy()\nelse:\n    sub_df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nsub_df = sub_df[study_len:]\ntest_paths = f'/kaggle/tmp/{split}/image/' + sub_df['id'] +'.png'\nsub_df['none'] = 0\n\nlabel_cols = sub_df.columns[2]\n\ntest_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[8], IMSIZE[8]), ext='png')\ndtest = build_dataset(\n    test_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder\n)\n\nwith strategy.scope():\n    \n    models = []\n    \n    models0 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model3.h5'\n    )\n    models4 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model4.h5'\n    )\n    \n    models.append(models0)\n    models.append(models1)\n    models.append(models2)\n    models.append(models3)\n    models.append(models4)\n\n    \nsub_df[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) / len(models)\ndf_2class = sub_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:03:57.206493Z","iopub.execute_input":"2021-07-07T09:03:57.206815Z","iopub.status.idle":"2021-07-07T09:05:57.223487Z","shell.execute_reply.started":"2021-07-07T09:03:57.206776Z","shell.execute_reply":"2021-07-07T09:05:57.222664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del models\ndel models0, models1, models2, models3, models4","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:05:57.226298Z","iopub.execute_input":"2021-07-07T09:05:57.226551Z","iopub.status.idle":"2021-07-07T09:05:57.232671Z","shell.execute_reply.started":"2021-07-07T09:05:57.226525Z","shell.execute_reply":"2021-07-07T09:05:57.231799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 切换至GPU\nfrom numba import cuda\nimport torch\ncuda.select_device(0)\ncuda.close()\ncuda.select_device(0)","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:05:57.23617Z","iopub.execute_input":"2021-07-07T09:05:57.236464Z","iopub.status.idle":"2021-07-07T09:05:59.465623Z","shell.execute_reply.started":"2021-07-07T09:05:57.236439Z","shell.execute_reply":"2021-07-07T09:05:59.464731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install ../input/mmdetectionv2130/src/addict-2.4.0-py3-none-any.whl\n!pip install ../input/mmdetectionv2130/src/yapf-0.31.0-py2.py3-none-any.whl\n!pip install ../input/mmdetectionv2130/src/mmcv_full-1.3.7-cp37-cp37m-manylinux1_x86_64.whl\n!rsync -a ../input/mmdetectionv2130/mmdetection ../\n!pip install ../input/mmdetectionv2130/src/mmpycocotools-12.0.3\n!pip install ../input/pycocotools202/pycocotools-2.0.2-cp37-cp37m-linux_x86_64.whl\n!cd ../mmdetection && pip install -e .","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:05:59.467221Z","iopub.execute_input":"2021-07-07T09:05:59.46754Z","iopub.status.idle":"2021-07-07T09:08:56.379863Z","shell.execute_reply.started":"2021-07-07T09:05:59.467503Z","shell.execute_reply":"2021-07-07T09:08:56.378891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.insert(0, \"../mmdetection\")\nimport mmcv\nfrom mmdet.models import build_detector\nfrom mmcv.runner import load_checkpoint\nfrom mmcv.parallel import MMDataParallel\nfrom mmdet.datasets import build_dataloader, build_dataset\nfrom mmdet.apis import single_gpu_test\nfrom mmdet.apis import init_detector, inference_detector, show_result_pyplot","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:08:56.381561Z","iopub.execute_input":"2021-07-07T09:08:56.381969Z","iopub.status.idle":"2021-07-07T09:09:19.736624Z","shell.execute_reply.started":"2021-07-07T09:08:56.381928Z","shell.execute_reply":"2021-07-07T09:09:19.735716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta = meta[meta['split'] == 'test']\nif fast_sub:\n    test_df = fast_df.copy()\nelse:\n    test_df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\ntest_df = df[study_len:].reset_index(drop=True) \nmeta['image_id'] = meta['image_id'] + '_image'\nmeta.columns = ['id', 'dim0', 'dim1', 'split']\ntest_df = pd.merge(test_df, meta, on = 'id', how = 'left')","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:09:19.73811Z","iopub.execute_input":"2021-07-07T09:09:19.73844Z","iopub.status.idle":"2021-07-07T09:09:19.755396Z","shell.execute_reply.started":"2021-07-07T09:09:19.738403Z","shell.execute_reply":"2021-07-07T09:09:19.754273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from mmcv import Config\nfrom pathlib import Path\n\n# cfg = Config.fromfile('/kaggle/working/mmdetection/configs/vfnet/vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py')\n# cfg = Config.fromfile(\"/kaggle/working/mmdetection/configs/vfnet/vfnet_r50_fpn_mstrain_2x_coco.py\")\n# cfg = Config.fromfile(\"/kaggle/working/mmdetection/configs/gfl/gfl_r50_fpn_mstrain_2x_coco.py\")\nbaseline_cfg_path = \"../mmdetection/configs/retinanet/retinanet_r101_fpn_1x_coco.py\"\n#baseline_cfg_path = \"../mmdetection/configs/faster_rcnn/faster_rcnn_r101_fpn_1x_coco.py\"\n#baseline_cfg_path = \"../mmdetection/configs/cascade_rcnn/cascade_rcnn_r101_fpn_1x_coco.py\"\n#baseline_cfg_path = \"../input/mmdetectionv2130/mmdetection/configs/vfnet/vfnet_r101_fpn_1x_coco.py\"\ncfg = Config.fromfile(baseline_cfg_path)","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:09:19.756725Z","iopub.execute_input":"2021-07-07T09:09:19.75726Z","iopub.status.idle":"2021-07-07T09:09:19.782255Z","shell.execute_reply.started":"2021-07-07T09:09:19.757211Z","shell.execute_reply":"2021-07-07T09:09:19.781511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set the number of classes\ncfg.model.bbox_head.num_classes = 2 # retinanet vfnet\n#cfg.model.roi_head.bbox_head.num_classes = 2 # faster rcnn\n#cfg.model.roi_head.bbox_head[0].num_classes = 2 # cascade rcnn\n#cfg.model.roi_head.bbox_head[1].num_classes = 2\n#cfg.model.roi_head.bbox_head[2].num_classes = 2\ncfg.model.bbox_head.anchor_generator.ratios = [0.25, 0.5, 1.0, 2.0, 4.0] # retinanet\n#cfg.model.rpn_head.anchor_generator.ratios = [0.25, 0.5, 1.0, 2.0, 4.0] # rcnn\nbatch_size = 4\ncfg.data.samples_per_gpu = batch_size # Batch size of a single GPU used in testing\ncfg.data.workers_per_gpu = 2 # Worker to pre-fetch data for each single GPU\ncfg.test_pipeline = [\n    dict(type='LoadImageFromFile'),\n    dict(\n        type='MultiScaleFlipAug',\n        img_scale=(640, 640),\n        flip=False,\n        transforms=[\n            dict(type='Resize', keep_ratio=True),\n            dict(type='RandomFlip'),\n            dict(\n                type='Normalize',\n                mean=[123.675, 116.28, 103.53],\n                std=[58.395, 57.12, 57.375],\n                to_rgb=True),\n            dict(type='Pad', size_divisor=32),\n            dict(type='ImageToTensor', keys=['img']),\n            dict(type='Collect', keys=['img'])\n        ])\n]","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:09:19.783444Z","iopub.execute_input":"2021-07-07T09:09:19.783812Z","iopub.status.idle":"2021-07-07T09:09:19.791259Z","shell.execute_reply.started":"2021-07-07T09:09:19.783777Z","shell.execute_reply":"2021-07-07T09:09:19.790196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cfg_path = f'/kaggle/working/{Path(baseline_cfg_path).name}'\nprint(cfg_path)\n\n# Save config file for inference later\ncfg.dump(cfg_path)\n#print(f'Config:\\n{cfg.pretty_text}')","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:09:19.792563Z","iopub.execute_input":"2021-07-07T09:09:19.793109Z","iopub.status.idle":"2021-07-07T09:09:20.054436Z","shell.execute_reply.started":"2021-07-07T09:09:19.793075Z","shell.execute_reply":"2021-07-07T09:09:20.053639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint = f'/kaggle/input/mmdetmodel0707/retinanet_r101.pth'\n\nprint(\"Loading weights from:\", checkpoint)\ncfg = Config.fromfile(cfg_path)\nmodel = init_detector(cfg, checkpoint, device='cuda:0')","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:25:16.401516Z","iopub.execute_input":"2021-07-07T09:25:16.401902Z","iopub.status.idle":"2021-07-07T09:25:22.616315Z","shell.execute_reply.started":"2021-07-07T09:25:16.401866Z","shell.execute_reply":"2021-07-07T09:25:22.615415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def scale_coords(image_height, image_width, bboxes, raw_size):\n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n\n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]] / raw_size * image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]] / raw_size * image_height\n    #bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    #bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n\n    return bboxes","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:25:27.793068Z","iopub.execute_input":"2021-07-07T09:25:27.79345Z","iopub.status.idle":"2021-07-07T09:25:27.800546Z","shell.execute_reply.started":"2021-07-07T09:25:27.79342Z","shell.execute_reply":"2021-07-07T09:25:27.799806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nraw_size = 640\nimgs_path = f'/kaggle/tmp/{split}/image/'\n\nthreshold = 0.001\nimage_ids = []\nPredictionStrings = []\n#imagepaths = [item['file_name'] for item in test_df['id']]\ntest_paths = f'/kaggle/tmp/{split}/image/' + test_df['id'] +'.png'\ntest_imgs = test_paths.tolist()\n#for i in range(0, len(test_imgs), batch_size):\n#    bz = test_imgs[i : i + batch_size]\nfor i in range(len(test_imgs)):\n    imgs = cv2.imread(test_imgs[i])\n    #print(imgs.shape)\n    results = inference_detector(model, imgs)\n    #results = inference_detector(model, bz)\n    #for j in range(len(test_batch)):\n    result = results[1]\n    #print(results[0])\n    results_filtered = result[result[:, 4]>threshold]\n    bboxes = results_filtered[:, :4]\n    scores = results_filtered[:, 4] \n    pre_str = ''\n    img_id = test_imgs[i].split('/')[-1].split('.')[0]\n    if len(bboxes) > 0:\n        w, h = test_df.loc[test_df.id==img_id,['dim1', 'dim0']].values[0]\n        bboxes = scale_coords(h, w, bboxes, raw_size)\n        for i in range(len(bboxes)):\n            pre_str = pre_str + 'opacity %.3f %.0f %.0f %.0f %.0f ' %(scores[i], bboxes[i][0], bboxes[i][1], bboxes[i][2], bboxes[i][3])\n    image_ids.append(img_id)\n    PredictionStrings.append(pre_str.rstrip())\n\n\npred_df = pd.DataFrame({'id':image_ids,\n                        'PredictionString':PredictionStrings})\n#print(pred_df)","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:25:30.395714Z","iopub.execute_input":"2021-07-07T09:25:30.396066Z","iopub.status.idle":"2021-07-07T09:25:30.66382Z","shell.execute_reply.started":"2021-07-07T09:25:30.396037Z","shell.execute_reply":"2021-07-07T09:25:30.662045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = test_df.drop(['PredictionString'], axis=1)\nsub_df = pd.merge(test_df, pred_df, on = 'id', how = 'left').fillna(\"none 1 0 0 1 1\")\nsub_df = sub_df[['id', 'PredictionString']]\nsub_df['none'] = df_2class['none'] \nfor i in range(sub_df.shape[0]):\n    if sub_df.loc[i,'PredictionString'] != 'none 1 0 0 1 1':\n        sub_df.loc[i,'PredictionString'] = sub_df.loc[i,'PredictionString'] + ' none ' + str(sub_df.loc[i,'none']) + ' 0 0 1 1'\nsub_df = sub_df[['id', 'PredictionString']]   \ndf = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\ndf_study = df[:study_len]\ndf_study = df_study.append(sub_df).reset_index(drop=True)\ndf_study.to_csv('/kaggle/working/submission.csv',index = False)  \n#print(df_study)","metadata":{"execution":{"iopub.status.busy":"2021-07-07T09:25:37.894296Z","iopub.execute_input":"2021-07-07T09:25:37.894623Z","iopub.status.idle":"2021-07-07T09:25:37.963569Z","shell.execute_reply.started":"2021-07-07T09:25:37.894592Z","shell.execute_reply":"2021-07-07T09:25:37.961616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}