{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":24800,"datasetId":1042002,"databundleVersionId":1831594}],"dockerImageVersionId":30664,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport os","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-13T09:28:02.796322Z","iopub.execute_input":"2024-03-13T09:28:02.796745Z","iopub.status.idle":"2024-03-13T09:28:04.018635Z","shell.execute_reply.started":"2024-03-13T09:28:02.796713Z","shell.execute_reply":"2024-03-13T09:28:04.017394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the root data directory\nDATA_DIR = \"/kaggle/input/vinbigdata-chest-xray-abnormalities-detection\"\n\n# Define the paths to the training and testing dicom folders respectively\nTRAIN_DIR = os.path.join(DATA_DIR, \"train\")\nTEST_DIR = os.path.join(DATA_DIR, \"test\")\n\n# Capture all the relevant full train/test paths\nTRAIN_DICOM_PATHS = [os.path.join(TRAIN_DIR, f_name) for f_name in os.listdir(TRAIN_DIR)]\nTEST_DICOM_PATHS = [os.path.join(TEST_DIR, f_name) for f_name in os.listdir(TEST_DIR)]\nprint(f\"\\n... The number of training files is {len(TRAIN_DICOM_PATHS)} ...\")\nprint(f\"... The number of testing files is {len(TEST_DICOM_PATHS)} ...\")\n\n# Define paths to the relevant csv files\nTRAIN_CSV = os.path.join(DATA_DIR, \"train.csv\")\nSS_CSV = os.path.join(DATA_DIR, \"sample_submission.csv\")\n\n# Create the relevant dataframe objects\ntrain_df = pd.read_csv(TRAIN_CSV)\nss_df = pd.read_csv(SS_CSV)\n\nprint(\"\\n\\nTRAIN DATAFRAME\\n\\n\")\ndisplay(train_df.head(3))\n\nprint(\"\\n\\nSAMPLE SUBMISSION DATAFRAME\\n\\n\")\ndisplay(ss_df.head(3))","metadata":{"execution":{"iopub.status.busy":"2024-03-13T09:28:04.020722Z","iopub.execute_input":"2024-03-13T09:28:04.021361Z","iopub.status.idle":"2024-03-13T09:28:05.819821Z","shell.execute_reply.started":"2024-03-13T09:28:04.021325Z","shell.execute_reply":"2024-03-13T09:28:05.818516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nfrom PIL import Image\nfrom PIL import ImageOps","metadata":{"execution":{"iopub.status.busy":"2024-03-13T09:28:05.825299Z","iopub.execute_input":"2024-03-13T09:28:05.826267Z","iopub.status.idle":"2024-03-13T09:28:06.09535Z","shell.execute_reply.started":"2024-03-13T09:28:05.826233Z","shell.execute_reply":"2024-03-13T09:28:06.094031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# IMG CONVERSION CLASSES\n\ndef resize_and_pad_image(img, desired_size=(640, 640), fill_color=(0, 0, 0)):\n    # Calculate the ratio to resize the image to fit the desired size while keeping the aspect ratio\n    ratio = min(desired_size[0] / img.size[0], desired_size[1] / img.size[1])\n    new_size = (int(img.size[0] * ratio), int(img.size[1] * ratio))\n    \n    # Resize the image\n    img = img.resize(new_size, Image.ANTIALIAS)\n    \n    # Create a new image with desired size and black background\n    padded_img = Image.new(\"RGB\", desired_size, fill_color)\n    \n    # Calculate positioning for the image\n    x = (desired_size[0] - new_size[0]) // 2\n    y = (desired_size[1] - new_size[1]) // 2\n    \n    # Paste the resized image onto the center of the new image\n    padded_img.paste(img, (x, y))\n    \n    return padded_img\n\ndef read_and_save_xray(path, output_path, voi_lut=True, fix_monochrome=True):\n    dicom = pydicom.read_file(path)\n    \n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \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    img = Image.fromarray(data)\n    \n    # Resize and pad the image\n    img = resize_and_pad_image(img)\n    \n    img.save(output_path)\n\ndef convert_directory(dicom_dir, output_dir, file_extension='.jpg'): # or '.png'\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    \n    for filename in os.listdir(dicom_dir):\n        if filename.endswith('.dicom'):\n            try:\n                path_to_dicom = os.path.join(dicom_dir, filename)\n                output_path = os.path.join(output_dir, filename.replace('.dicom', file_extension))\n                read_and_save_xray(path_to_dicom, output_path)\n                print(f\"Converted and saved: {filename} as {file_extension}\")\n            except Exception as e:\n                print(f\"Error converting file {filename}: {e}\")","metadata":{"execution":{"iopub.status.busy":"2024-03-13T09:28:06.097217Z","iopub.execute_input":"2024-03-13T09:28:06.098042Z","iopub.status.idle":"2024-03-13T09:28:06.119579Z","shell.execute_reply.started":"2024-03-13T09:28:06.097996Z","shell.execute_reply":"2024-03-13T09:28:06.118148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dicom_directory = TRAIN_DIR\noutput_directory = '/kaggle/working/TRAIN_DIR_JPG_640x640'\nconvert_directory(dicom_directory, output_directory)","metadata":{"execution":{"iopub.status.busy":"2024-03-13T09:28:06.121568Z","iopub.execute_input":"2024-03-13T09:28:06.122152Z","iopub.status.idle":"2024-03-13T09:37:37.305903Z","shell.execute_reply.started":"2024-03-13T09:28:06.122099Z","shell.execute_reply":"2024-03-13T09:37:37.304162Z"},"trusted":true},"execution_count":null,"outputs":[]}]}