{"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"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":24800,"databundleVersionId":1831594,"sourceType":"competition"}],"dockerImageVersionId":30042,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-07T14:06:53.667541Z","iopub.execute_input":"2023-11-07T14:06:53.668225Z","iopub.status.idle":"2023-11-07T14:06:53.676483Z","shell.execute_reply.started":"2023-11-07T14:06:53.668179Z","shell.execute_reply":"2023-11-07T14:06:53.675346Z"},"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_images(path, voi_lut=True, fix_monochrome=True):\n    \"\"\"\n    Read and process a DICOM image.\n\n    Parameters:\n    path (str): Path to the DICOM file.\n    voi_lut (bool): Whether to apply VOI LUT.\n    fix_monochrome (bool): Whether to fix monochrome images if PhotometricInterpretation is \"MONOCHROME1\".\n\n    Returns:\n    numpy.ndarray: Processed image as a NumPy array.\n    \"\"\"\n\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT is used to transform raw DICOM data to \"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","metadata":{"execution":{"iopub.status.busy":"2023-11-07T14:06:53.678557Z","iopub.execute_input":"2023-11-07T14:06:53.679278Z","iopub.status.idle":"2023-11-07T14:06:53.993279Z","shell.execute_reply.started":"2023-11-07T14:06:53.679227Z","shell.execute_reply":"2023-11-07T14:06:53.992242Z"},"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":"2023-11-07T14:06:53.99451Z","iopub.execute_input":"2023-11-07T14:06:53.994798Z","iopub.status.idle":"2023-11-07T14:06:54.001492Z","shell.execute_reply.started":"2023-11-07T14:06:53.994769Z","shell.execute_reply":"2023-11-07T14:06:53.999931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_id_train = []\ndim0train = []\ndim1train = []\nimage_id_test = []\ndim0test = []\ndim1test = []\n\nfor split in ['train', 'test']:\n    load_dir = f'../input/vinbigdata-chest-xray-abnormalities-detection/{split}/'\n    save_dir = f'/kaggle/working/{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_images(load_dir + file)\n        im = resize(xray, size=1024)  \n        im.save(save_dir + file.replace('dicom', 'png'))\n        \n        if split == 'train':\n            image_id_train.append(file.replace('.dicom', ''))\n            dim0train.append(xray.shape[0])\n            dim1train.append(xray.shape[1])\n            \n        if split == 'test':\n            image_id_test.append(file.replace('.dicom', ''))\n            dim0test.append(xray.shape[0])\n            dim1test.append(xray.shape[1])","metadata":{"execution":{"iopub.status.busy":"2023-11-07T14:06:54.003532Z","iopub.execute_input":"2023-11-07T14:06:54.004006Z","iopub.status.idle":"2023-11-07T14:07:19.703614Z","shell.execute_reply.started":"2023-11-07T14:06:54.003967Z","shell.execute_reply":"2023-11-07T14:07:19.701904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_meta = pd.DataFrame.from_dict({'image_id': image_id_train, 'dim0': dim0train, 'dim1': dim1train})\ndf_train_meta.to_csv('train_meta.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-07T14:07:19.704543Z","iopub.status.idle":"2023-11-07T14:07:19.704983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = pd.DataFrame.from_dict({'image_id': image_id_test, 'dim0': dim0test, 'dim1': dim1test})\ndf_test.to_csv('test.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"original_df = pd.read_csv('../input/vinbigdata-chest-xray-abnormalities-detection/train.csv')\noriginal_df.to_csv('train.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 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":{}}]}