{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Prepare DICOM Images for ML"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport pydicom\nimport glob\nimport datetime\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"## First, read all of my DICOM files into a list\nmydicoms = glob.glob(\"/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/*.dicom\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Let's look at the contents of the first DICOM:"},{"metadata":{"trusted":true},"cell_type":"code","source":"dcm1 = pydicom.dcmread(mydicoms[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dcm1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Looking at the attributes listed above, I can see that I'm looking to extract the following attributes: \n* Patient's Sex\n* Patient's Age\n* Patient's Weight\n* Patient's Size"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Patient's Sex\ndcm1[(0x0010, 0x0040)].value","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Patient's Age\ndcm1[(0x0010, 0x1010)].value","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Rows\ndcm1[(0x0028, 0x0010)].value","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Cols\ndcm1.get((0x0028, 0x0011)).value","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sex_key = (0x0010, 0x0040)\ndef get_patients_sex(dcm):\n    if sex_key in dcm:\n        return dcm[sex_key].value\n    else:\n        return None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"age_key = (0x0010, 0x1010)\ndef get_patients_age(dcm):\n    if age_key in dcm:\n        return dcm[age_key].value\n    else:\n        return None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weight_key = (0x0010, 0x1030)\ndef get_patients_weight(dcm):\n    if weight_key in dcm:\n        return dcm[weight_key].value\n    else:\n        return None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"size_key = (0x0010, 0x1020)\ndef get_patients_size(dcm):\n    if size_key in dcm:\n        return dcm[size_key].value\n    else:\n        return None","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Now, let's create the dataframe that we want, and populate it in a loop with all of our DICOMS:"},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data = pd.read_csv('../input/vinbigdata-chest-xray-abnormalities-detection/train.csv')\nsampled_data = all_data # .sample(frac=0.25)\nn = len(sampled_data.index)\nprint('n:', n)\ntrain_dir = '../input/vinbigdata-chest-xray-abnormalities-detection/train'\nsexes = []\nages = []\nweights = []\nsizes = []\ni = 0\nstart_time = datetime.datetime.now()\nfor index, row in sampled_data.iterrows():\n    image_id = row['image_id']\n    file_path = train_dir + \"/\" + image_id + '.dicom'\n    dcm = pydicom.dcmread(file_path, stop_before_pixels=True)\n    sex = get_patients_sex(dcm)\n    sexes.append(sex)\n    age = get_patients_age(dcm)\n    ages.append(age)\n    weight = get_patients_weight(dcm)\n    weights.append(weight)\n    size = get_patients_size(dcm)\n    sizes.append(size)\n    i += 1\n    if i % 100 == 0:\n        print()\n        fraction_done = i / n\n        print('fraction_done:', fraction_done)\n        current_time = datetime.datetime.now()\n        elapsed_minutes = int((current_time - start_time).total_seconds()) // 60\n        print('elapsed_minutes:', elapsed_minutes)\n        if elapsed_minutes > 0:\n            records_per_minute = i / elapsed_minutes\n            remaining_minutes = (n - i) // records_per_minute\n            print('remaining_minutes:', remaining_minutes)\nsampled_data['sex'] = sexes\nsampled_data['age'] = ages\nsampled_data['weight'] = weights\nsampled_data['size'] = sizes\n\nsampled_data.to_csv(\"all_data.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sampled_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}