{"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":"import numpy as np\nimport pandas as pd\nimport torch\n\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport SimpleITK as sitk\nimport cv2\n\nimport os\nfrom os import listdir, mkdir\nimport glob\nfrom tqdm.auto import tqdm","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:45:36.498710Z","iopub.execute_input":"2021-08-16T15:45:36.499149Z","iopub.status.idle":"2021-08-16T15:45:36.505312Z","shell.execute_reply.started":"2021-08-16T15:45:36.499116Z","shell.execute_reply":"2021-08-16T15:45:36.503871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/siim-covid19-detection/sample_submission.csv')\ntest_path = '/kaggle/input/siim-covid19-detection/test/'\ndetection_model_path =  '/kaggle/input/image-detection-model-1/yolov5/kaggle-siim-covid/exp/weights/best.pt'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-08-16T15:21:38.871222Z","iopub.execute_input":"2021-08-16T15:21:38.871638Z","iopub.status.idle":"2021-08-16T15:21:38.889382Z","shell.execute_reply.started":"2021-08-16T15:21:38.871595Z","shell.execute_reply":"2021-08-16T15:21:38.888404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['file_level'] = df['id'].apply(lambda x : str(x).split('_')[1])\ndf_study = df[df['file_level']=='study']\ndf_image = df[df['file_level']=='image']\ndf_study['study'] =  df_study['id'].apply(lambda x : str(x).split('_')[0])\ndf_image['image'] =  df_image['id'].apply(lambda x : str(x).split('_')[0])","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:38.891475Z","iopub.execute_input":"2021-08-16T15:21:38.891901Z","iopub.status.idle":"2021-08-16T15:21:38.919838Z","shell.execute_reply.started":"2021-08-16T15:21:38.891859Z","shell.execute_reply":"2021-08-16T15:21:38.918805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 判断提交或快存","metadata":{}},{"cell_type":"code","source":"if df.shape[0] == 2477:\n    quick_save = True\nelse: quick_save = False","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:38.921648Z","iopub.execute_input":"2021-08-16T15:21:38.922229Z","iopub.status.idle":"2021-08-16T15:21:38.927273Z","shell.execute_reply.started":"2021-08-16T15:21:38.922187Z","shell.execute_reply":"2021-08-16T15:21:38.926208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if quick_save:\n    df_study = df_study[35:40]\n    ","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:38.930129Z","iopub.execute_input":"2021-08-16T15:21:38.93046Z","iopub.status.idle":"2021-08-16T15:21:38.939628Z","shell.execute_reply.started":"2021-08-16T15:21:38.930432Z","shell.execute_reply":"2021-08-16T15:21:38.938584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_study_dict = {}\nfor i in df_study.index:\n    path_list = glob.glob(test_path + f'{df_study.loc[i,\"study\"]}/' + '*/*'+'.dcm')\n    for path in path_list:\n        image_code = path.split('/')[7].split('.')[0]\n        image_study_dict[image_code] = df_study.loc[i,'study']\n        ","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:38.941284Z","iopub.execute_input":"2021-08-16T15:21:38.941576Z","iopub.status.idle":"2021-08-16T15:21:38.996804Z","shell.execute_reply.started":"2021-08-16T15:21:38.941548Z","shell.execute_reply":"2021-08-16T15:21:38.995433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if quick_save:\n    df_image = df_image[df_image['image'].isin(image_study_dict.keys())]\n\ndf_image['study'] = ''\ndf_image['study'] = df_image['image'].apply(lambda x:image_study_dict[x])","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:39.002702Z","iopub.execute_input":"2021-08-16T15:21:39.003479Z","iopub.status.idle":"2021-08-16T15:21:39.019842Z","shell.execute_reply.started":"2021-08-16T15:21:39.003398Z","shell.execute_reply":"2021-08-16T15:21:39.018578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 存储测试集图片路径","metadata":{}},{"cell_type":"code","source":"df_image['image_path'] = ''\nfor i in tqdm(df_image.index):\n    path = glob.glob(test_path + df_image.loc[i,'study'] +'/*/' + df_image.loc[i,'image'] +'.dcm')[0]\n    df_image.loc[i,'image_path'] = path","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:39.02488Z","iopub.execute_input":"2021-08-16T15:21:39.025663Z","iopub.status.idle":"2021-08-16T15:21:39.119714Z","shell.execute_reply.started":"2021-08-16T15:21:39.025583Z","shell.execute_reply":"2021-08-16T15:21:39.118768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir /kaggle/test","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:39.121914Z","iopub.execute_input":"2021-08-16T15:21:39.122517Z","iopub.status.idle":"2021-08-16T15:21:39.848274Z","shell.execute_reply.started":"2021-08-16T15:21:39.122474Z","shell.execute_reply":"2021-08-16T15:21:39.847113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_xray(path, fix_monochrome = True):\n    \n    dicom = sitk.ReadImage(path)\n    \n    data = sitk.GetArrayFromImage(dicom)[0,:,:]\n               \n    if fix_monochrome and dicom.GetMetaData('0028|0004') == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data,data.shape[0],data.shape[1]\n\ndef resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    \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-08-16T15:21:39.852219Z","iopub.execute_input":"2021-08-16T15:21:39.852546Z","iopub.status.idle":"2021-08-16T15:21:39.863599Z","shell.execute_reply.started":"2021-08-16T15:21:39.852512Z","shell.execute_reply":"2021-08-16T15:21:39.862484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE = 640\n\ndf_image['dim_h'] = 0\ndf_image['dim_w'] = 0\ndf_image['path'] =  ''\n\n\nfor i in tqdm(df_image.index):\n    image,df_image.loc[i,'dim_h'],df_image.loc[i,'dim_w'] = read_xray(df_image.loc[i,'image_path'])\n    im = resize(image,size = IMG_SIZE)\n    png_path = '/kaggle/test/' + df_image.loc[i,'image'] +'.png'\n    df_image.loc[i,'path'] = png_path\n    im.save(png_path) ","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:39.865258Z","iopub.execute_input":"2021-08-16T15:21:39.865635Z","iopub.status.idle":"2021-08-16T15:21:44.867177Z","shell.execute_reply.started":"2021-08-16T15:21:39.865601Z","shell.execute_reply":"2021-08-16T15:21:44.86618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_image['dim_h'] = df_image['dim_h'].astype('int64')\ndf_image['dim_w'] = df_image['dim_w'].astype('int64')","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:44.868702Z","iopub.execute_input":"2021-08-16T15:21:44.86917Z","iopub.status.idle":"2021-08-16T15:21:44.875091Z","shell.execute_reply.started":"2021-08-16T15:21:44.869125Z","shell.execute_reply":"2021-08-16T15:21:44.87412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###  定义函数","metadata":{}},{"cell_type":"code","source":"!pip install /kaggle/input/kerasapplications/keras-applications-master -q\n!pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps\n\nimport efficientnet.tfkeras as efn\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","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:21:44.876701Z","iopub.execute_input":"2021-08-16T15:21:44.877348Z","iopub.status.idle":"2021-08-16T15:22:44.985774Z","shell.execute_reply.started":"2021-08-16T15:21:44.877303Z","shell.execute_reply":"2021-08-16T15:22:44.98475Z"},"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#GCS_DS_PATH = KaggleDatasets().get_gcs_path(COMPETITION_NAME)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:22:44.987342Z","iopub.execute_input":"2021-08-16T15:22:44.987765Z","iopub.status.idle":"2021-08-16T15:22:44.998982Z","shell.execute_reply.started":"2021-08-16T15:22:44.987704Z","shell.execute_reply":"2021-08-16T15:22:44.997635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### study predict","metadata":{}},{"cell_type":"code","source":"test_paths = df_image['path'].values","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:22:45.000999Z","iopub.execute_input":"2021-08-16T15:22:45.001461Z","iopub.status.idle":"2021-08-16T15:22:45.008899Z","shell.execute_reply.started":"2021-08-16T15:22:45.001414Z","shell.execute_reply":"2021-08-16T15:22:45.007672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_image['negative'] = 0\ndf_image['typical'] = 0\ndf_image['indeterminate'] = 0\ndf_image['atypical'] = 0\n\nlabel_cols = df_image.columns[9:]","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:22:45.010882Z","iopub.execute_input":"2021-08-16T15:22:45.011498Z","iopub.status.idle":"2021-08-16T15:22:45.022705Z","shell.execute_reply.started":"2021-08-16T15:22:45.01145Z","shell.execute_reply":"2021-08-16T15:22:45.02174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMSIZE = (224, 240, 260, 300, 380, 456, 512, 600, 640)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:22:45.026511Z","iopub.execute_input":"2021-08-16T15:22:45.026835Z","iopub.status.idle":"2021-08-16T15:22:45.033963Z","shell.execute_reply.started":"2021-08-16T15:22:45.026804Z","shell.execute_reply":"2021-08-16T15:22:45.032958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_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        '/kaggle/input/study-class-model-effnetb7/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '/kaggle/input/study-class-model-effnetb7/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '/kaggle/input/study-class-model-effnetb7/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '/kaggle/input/study-class-model-effnetb7/model3.h5'\n    )\n    models4 = tf.keras.models.load_model(\n        '/kaggle/input/study-class-model-effnetb7/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    \n    \n    \ndf_image[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) / len(models)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:22:45.035653Z","iopub.execute_input":"2021-08-16T15:22:45.036111Z","iopub.status.idle":"2021-08-16T15:25:27.015935Z","shell.execute_reply.started":"2021-08-16T15:22:45.036066Z","shell.execute_reply":"2021-08-16T15:25:27.014899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in df_image.index:\n    negative = df_image.loc[i,'negative']\n    typical = df_image.loc[i,'typical']\n    indeterminate = df_image.loc[i,'indeterminate']\n    atypical = df_image.loc[i,'atypical']\n    df_image.loc[i, 'study_pre'] = f'negative {negative} 0 0 1 1 typical {typical} 0 0 1 1 indeterminate {indeterminate} 0 0 1 1 atypical {atypical} 0 0 1 1'","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:25:27.017541Z","iopub.execute_input":"2021-08-16T15:25:27.017973Z","iopub.status.idle":"2021-08-16T15:25:27.029303Z","shell.execute_reply.started":"2021-08-16T15:25:27.017928Z","shell.execute_reply":"2021-08-16T15:25:27.028023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_study['PredictionString'] = ''\nfor i in df_study.index:\n    df_image_sub = df_image[df_image['study']==df_study.loc[i,'study']]\n    df_study.loc[i,'PredictionString'] = df_study.loc[i,'PredictionString'] + df_image_sub.iloc[0]['study_pre']","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:25:27.030942Z","iopub.execute_input":"2021-08-16T15:25:27.031387Z","iopub.status.idle":"2021-08-16T15:25:27.057209Z","shell.execute_reply.started":"2021-08-16T15:25:27.031341Z","shell.execute_reply":"2021-08-16T15:25:27.055684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_study = df_study[['id','PredictionString']]","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:25:27.059084Z","iopub.execute_input":"2021-08-16T15:25:27.05953Z","iopub.status.idle":"2021-08-16T15:25:27.070533Z","shell.execute_reply.started":"2021-08-16T15:25:27.059484Z","shell.execute_reply":"2021-08-16T15:25:27.069133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### opacity classes prediction","metadata":{}},{"cell_type":"code","source":"test_paths = df_image['path'].values\ndf_image['none'] = 0\nlabel_cols = 'none'\n\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512)\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        '/kaggle/input/2-class-models-efficientnetb7/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '/kaggle/input/2-class-models-efficientnetb7/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '/kaggle/input/2-class-models-efficientnetb7/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '/kaggle/input/2-class-models-efficientnetb7/model3.h5'\n    )\n    models4 = tf.keras.models.load_model(\n        '/kaggle/input/2-class-models-efficientnetb7/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    \n    \n    \ndf_image[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) / len(models)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:25:27.074036Z","iopub.execute_input":"2021-08-16T15:25:27.074437Z","iopub.status.idle":"2021-08-16T15:28:25.387126Z","shell.execute_reply.started":"2021-08-16T15:25:27.0744Z","shell.execute_reply":"2021-08-16T15:28:25.386087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del models\ndel models0, models1, models2, models3, models4","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:25.391691Z","iopub.execute_input":"2021-08-16T15:28:25.392032Z","iopub.status.idle":"2021-08-16T15:28:25.396943Z","shell.execute_reply.started":"2021-08-16T15:28:25.391998Z","shell.execute_reply":"2021-08-16T15:28:25.395722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from numba import cuda\nimport torch\ncuda.select_device(0)\ncuda.close()\ncuda.select_device(0)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:25.399541Z","iopub.execute_input":"2021-08-16T15:28:25.40003Z","iopub.status.idle":"2021-08-16T15:28:27.501641Z","shell.execute_reply.started":"2021-08-16T15:28:25.399966Z","shell.execute_reply":"2021-08-16T15:28:27.500546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### image predict","metadata":{}},{"cell_type":"code","source":"TEST_PATH = '/kaggle/test/'","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:27.503245Z","iopub.execute_input":"2021-08-16T15:28:27.503882Z","iopub.status.idle":"2021-08-16T15:28:27.507907Z","shell.execute_reply.started":"2021-08-16T15:28:27.503838Z","shell.execute_reply":"2021-08-16T15:28:27.506769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil, os","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:27.509358Z","iopub.execute_input":"2021-08-16T15:28:27.509991Z","iopub.status.idle":"2021-08-16T15:28:27.52388Z","shell.execute_reply.started":"2021-08-16T15:28:27.509923Z","shell.execute_reply":"2021-08-16T15:28:27.522467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.copytree('/kaggle/input/image-detection-model-1/yolov5', '/kaggle/working/yolov5')\nos.chdir('/kaggle/working/yolov5') ","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:27.525931Z","iopub.execute_input":"2021-08-16T15:28:27.526477Z","iopub.status.idle":"2021-08-16T15:28:34.403881Z","shell.execute_reply.started":"2021-08-16T15:28:27.526424Z","shell.execute_reply":"2021-08-16T15:28:34.402831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python detect.py --weights $detection_model_path\\\n                  --source $TEST_PATH\\\n                  --img {IMG_SIZE} \\\n                  --conf 0.10 \\\n                  --iou-thres 0.5 \\\n                  --max-det 3 \\\n                  --save-txt --save-conf --exist-ok","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:34.405376Z","iopub.execute_input":"2021-08-16T15:28:34.405789Z","iopub.status.idle":"2021-08-16T15:28:43.781471Z","shell.execute_reply.started":"2021-08-16T15:28:34.405723Z","shell.execute_reply":"2021-08-16T15:28:43.780299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"PRED_PATH = '/kaggle/working/yolov5/runs/detect/exp/labels'","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.78335Z","iopub.execute_input":"2021-08-16T15:28:43.7838Z","iopub.status.idle":"2021-08-16T15:28:43.791793Z","shell.execute_reply.started":"2021-08-16T15:28:43.783737Z","shell.execute_reply":"2021-08-16T15:28:43.790783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prediction_files = os.listdir(PRED_PATH)\nprint('Number of test images predicted as opacity: ', len(prediction_files))","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.794143Z","iopub.execute_input":"2021-08-16T15:28:43.794553Z","iopub.status.idle":"2021-08-16T15:28:43.802036Z","shell.execute_reply.started":"2021-08-16T15:28:43.79451Z","shell.execute_reply":"2021-08-16T15:28:43.800813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The submisison requires xmin, ymin, xmax, ymax format. \n# YOLOv5 returns x_center, y_center, width, height\ndef correct_bbox_format(bboxes,img_w,img_h):\n    correct_bboxes = []\n    for b in bboxes:\n        xc, yc = b[0]*img_w, b[1]*img_h\n        w, h = b[2]*img_w, b[3]*img_h\n\n        xmin = xc - w/2\n        xmax = xc + w/2\n        ymin = yc - h/2\n        ymax = yc + h/2\n        \n        correct_bboxes.append([xmin, ymin, xmax, ymax])\n        \n    return correct_bboxes\n\n# Read the txt file generated by YOLOv5 during inference and extract \n# confidence and bounding box coordinates.\ndef get_conf_bboxes(file_path):\n    class_id = []\n    confidence = []\n    bboxes = []\n    with open(file_path, 'r') as file:\n        for line in file:\n            preds = line.strip('\\n').split(' ')\n            preds = list(map(float, preds))\n            class_id.append(preds[0])\n            confidence.append(preds[-1])\n            bboxes.append(preds[1:-1])\n    return class_id,confidence, bboxes","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.804186Z","iopub.execute_input":"2021-08-16T15:28:43.804608Z","iopub.status.idle":"2021-08-16T15:28:43.817605Z","shell.execute_reply.started":"2021-08-16T15:28:43.804564Z","shell.execute_reply":"2021-08-16T15:28:43.816625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prediction loop for submission\npredictions = []\n\nfor i in tqdm(df_image.index):\n    row = df_image.loc[i]\n    id_name = row.image\n    img_h = row.dim_h\n    img_w = row.dim_w\n    \n    if f'{id_name}.txt' in prediction_files:\n        class_id, confidence, bboxes = get_conf_bboxes(f'{PRED_PATH}/{id_name}.txt')\n        bboxes = correct_bbox_format(bboxes,img_w,img_h)\n        pred_string = ''\n        for j, conf in enumerate(confidence):\n            pred_string += 'opacity {:.6f} '.format(conf) + ' '.join(map(str, bboxes[j])) + ' '    \n        predictions.append(pred_string[:-1]) \n    else:\n        predictions.append(\"none 1.0 0 0 1 1\")\n    \ndf_image['PredictionString'] = predictions","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.819378Z","iopub.execute_input":"2021-08-16T15:28:43.82008Z","iopub.status.idle":"2021-08-16T15:28:43.878335Z","shell.execute_reply.started":"2021-08-16T15:28:43.820035Z","shell.execute_reply":"2021-08-16T15:28:43.877316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in df_image.index: \n    pro = 1 - df_image.loc[i,'none']\n    if df_image.loc[i,'PredictionString']!='none 1.0 0 0 1 1':\n        df_image.loc[i,'PredictionString'] = df_image.loc[i,'PredictionString']  \\\n                                                            +' none {:.6f} 0 0 1 1'.format(pro)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.879949Z","iopub.execute_input":"2021-08-16T15:28:43.880602Z","iopub.status.idle":"2021-08-16T15:28:43.891982Z","shell.execute_reply.started":"2021-08-16T15:28:43.880558Z","shell.execute_reply":"2021-08-16T15:28:43.890604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_image = df_image[['id','PredictionString']]","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.894182Z","iopub.execute_input":"2021-08-16T15:28:43.894985Z","iopub.status.idle":"2021-08-16T15:28:43.908943Z","shell.execute_reply.started":"2021-08-16T15:28:43.894941Z","shell.execute_reply":"2021-08-16T15:28:43.90778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submission = pd.concat([df_study,df_image])","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.910672Z","iopub.execute_input":"2021-08-16T15:28:43.911366Z","iopub.status.idle":"2021-08-16T15:28:43.92061Z","shell.execute_reply.started":"2021-08-16T15:28:43.911319Z","shell.execute_reply":"2021-08-16T15:28:43.919467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submission.to_csv('/kaggle/working/submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2021-08-16T15:28:43.923858Z","iopub.execute_input":"2021-08-16T15:28:43.924229Z","iopub.status.idle":"2021-08-16T15:28:43.935307Z","shell.execute_reply.started":"2021-08-16T15:28:43.924175Z","shell.execute_reply":"2021-08-16T15:28:43.934302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}