{"cells":[{"metadata":{},"cell_type":"markdown","source":"**By using the output of this notebook, you are accepting the [competition rules](https://www.kaggle.com/c/vinbigdata-chest-xray-abnormalities-detection/rules).**\n\n\n**This is originally from https://www.kaggle.com/xhlulu/vinbigdata-process-and-resize-to-png-256x256 by @xhlulu, I just modified a bit to save metadata for test images**\n\n## References\n\n- Monochrome fix and scaling: https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way\n- Resizing and saving image: https://www.kaggle.com/xhlulu/vinbigdata-process-and-resize-to-image"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_id = []\ndim0 = []\ndim1 = []\n\n#for split in ['train', 'test']:\nfor split in ['test']:\n    load_dir = f'../input/vinbigdata-chest-xray-abnormalities-detection/{split}/'\n    save_dir = f'/kaggle/tmp/{split}/'\n\n    os.makedirs(save_dir, exist_ok=True)\n\n    for file in tqdm(os.listdir(load_dir)):\n        # set keep_ratio=True to have original aspect ratio\n        xray = read_xray(load_dir + file)\n        #im = resize(xray, size=256)  \n        #im.save(save_dir + file.replace('dicom', 'png'))\n        \n        image_id.append(file.replace('.dicom', ''))\n        dim0.append(xray.shape[0])\n        dim1.append(xray.shape[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"file_list = os.listdir(load_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from joblib import Parallel, delayed\n\ndef load_meta(load_dir: str, file: str):\n    xray = read_xray(load_dir + file, False, False)\n    image_id = file.replace('.dicom', '')\n    height, width = xray.shape[:2]\n    return image_id, height, width\n\nprint(f\"total {len(file_list)}\")\nn_jobs = 16\nresults = Parallel(n_jobs, verbose=1)(\n    delayed(load_meta)(load_dir, filename) for filename in file_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_meta = pd.DataFrame(results, columns=[\"image_id\", \"dim0\", \"dim1\"])\ntest_meta.to_csv(\"test_meta.csv\", index=False)","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}