{"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 pandas as pd\nimport numpy as np\nimport seaborn as sb\nimport matplotlib.pyplot as plt\nimport nibabel as nib\n\nimport os\nimport pydicom\nfrom glob import glob\nfrom tqdm import tqdm, trange\n\nPATH = '/kaggle/input/rsna-2023-abdominal-trauma-detection'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-08-18T17:11:14.16258Z","iopub.execute_input":"2023-08-18T17:11:14.163132Z","iopub.status.idle":"2023-08-18T17:11:14.170686Z","shell.execute_reply.started":"2023-08-18T17:11:14.163085Z","shell.execute_reply":"2023-08-18T17:11:14.169448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Checking whether the series_id has segmentation image","metadata":{}},{"cell_type":"code","source":"id = 21057 #input series_id\n\na = glob(f'{PATH}/segmentations/*.nii')\nfor i in range(len(a)):\n    if (f'{PATH}/segmentations/{id}.nii' == a[i]):\n        print('ok')\n        break\nif i == len(a)-1:\n    print('The id does`t extist')","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:17:51.672513Z","iopub.execute_input":"2023-08-18T17:17:51.673536Z","iopub.status.idle":"2023-08-18T17:17:51.68571Z","shell.execute_reply.started":"2023-08-18T17:17:51.673495Z","shell.execute_reply":"2023-08-18T17:17:51.684642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(f'{PATH}/train.csv')\n\ntrain_series_meta = pd.read_csv(f'{PATH}/train_series_meta.csv')\ndf = pd.merge(train_series_meta, train, how='inner', on='patient_id')\n\nseg_filepath = f'{PATH}/segmentations/{id}.nii'\n\npatient_id = df[df['series_id'] == id]['patient_id'].iloc[0]\nfilepath = f'{PATH}/train_images/{patient_id}/{id}'","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:20:45.608986Z","iopub.execute_input":"2023-08-18T17:20:45.60945Z","iopub.status.idle":"2023-08-18T17:20:45.638919Z","shell.execute_reply.started":"2023-08-18T17:20:45.609415Z","shell.execute_reply":"2023-08-18T17:20:45.637715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#https://www.kaggle.com/code/parhammostame/construct-3d-arrays-from-dcm-nii-3-view-angles\ndef create_3D_scans(folder, downsample_rate=1): \n    filenames = os.listdir(folder)\n    filenames = [int(filename.split('.')[0]) for filename in filenames]\n    filenames = sorted(filenames)\n    filenames = [str(filename) + '.dcm' for filename in filenames]\n        \n    volume = []\n    for filename in tqdm(filenames[::downsample_rate]):\n        filepath = os.path.join(folder, filename)\n        ds = pydicom.dcmread(filepath)\n        image = ds.pixel_array\n        \n        # find rescale params\n        if (\"RescaleIntercept\" in ds) and (\"RescaleSlope\" in ds):\n            intercept = float(ds.RescaleIntercept)\n            slope = float(ds.RescaleSlope)\n    \n        # find clipping params\n        center = int(ds.WindowCenter)\n        width = int(ds.WindowWidth)\n        low = center - width / 2\n        high = center + width / 2    \n        image = (image * slope) + intercept\n        image = np.clip(image, low, high)\n\n        image = (image / np.max(image) * 255).astype(np.int16)\n        image = image[::downsample_rate, ::downsample_rate]\n        volume.append( image )\n    \n    volume = np.stack(volume, axis=0)\n    return volume\n\ndef create_3D_segmentations(filepath, downsample_rate=1):\n    img = nib.load(filepath).get_fdata()\n    img = np.transpose(img, [2, 1, 0])\n    img = np.rot90(img, -1, (1,2))\n    img = img[::-1,:,:]\n    img = np.transpose(img, [2, 1, 0])\n    img = img[::downsample_rate, ::downsample_rate, ::downsample_rate]\n    return img","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:20:48.276573Z","iopub.execute_input":"2023-08-18T17:20:48.277018Z","iopub.status.idle":"2023-08-18T17:20:48.292528Z","shell.execute_reply.started":"2023-08-18T17:20:48.276985Z","shell.execute_reply":"2023-08-18T17:20:48.29112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"volume = create_3D_scans(filepath)\nvolume = volume.transpose(1, 2, 0)\nvolume_seg = create_3D_segmentations(seg_filepath)\nvolume.shape","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:20:48.51253Z","iopub.execute_input":"2023-08-18T17:20:48.512966Z","iopub.status.idle":"2023-08-18T17:21:12.835609Z","shell.execute_reply.started":"2023-08-18T17:20:48.512934Z","shell.execute_reply":"2023-08-18T17:21:12.834373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Showing each organ mask images","metadata":{}},{"cell_type":"code","source":"z =500 #slice number\nfig = plt.figure(figsize=(16,16))\nax1 = fig.add_subplot(151)\nax1.imshow(np.where(volume_seg[:,:,z]==1,1,0), cmap = 'gray') #liver\nax2 = fig.add_subplot(152)\nax2.imshow(np.where(volume_seg[:,:,z]==2,1,0), cmap = 'gray') #spleen\nax3 = fig.add_subplot(153)\nax3.imshow(np.where(volume_seg[:,:,z]==3,1,0), cmap = 'gray') #right kidney\nax4 = fig.add_subplot(154)\nax4.imshow(np.where(volume_seg[:,:,z]==4,1,0), cmap = 'gray') #left kidney\nax5 = fig.add_subplot(155)\nax5.imshow(np.where(volume_seg[:,:,z]==5,1,0), cmap = 'gray') #bowel\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:21:12.839356Z","iopub.execute_input":"2023-08-18T17:21:12.839784Z","iopub.status.idle":"2023-08-18T17:21:13.746531Z","shell.execute_reply.started":"2023-08-18T17:21:12.839747Z","shell.execute_reply":"2023-08-18T17:21:13.745372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Masked images","metadata":{}},{"cell_type":"code","source":"fig = plt.figure(figsize=(16,16))\nax1 = fig.add_subplot(131)\nax1.imshow(volume[:,:,z], cmap = 'gray')\nax2 = fig.add_subplot(132)\nax2.imshow(volume_seg[:,:,z], cmap = 'gray')\nax3 = fig.add_subplot(133)\nax3.imshow(volume[:,:,z]*np.where(volume_seg[:,:,z]>0,1,0), cmap = 'gray')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:21:15.07211Z","iopub.execute_input":"2023-08-18T17:21:15.072549Z","iopub.status.idle":"2023-08-18T17:21:15.787231Z","shell.execute_reply.started":"2023-08-18T17:21:15.072516Z","shell.execute_reply":"2023-08-18T17:21:15.785897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Making each organ masked images","metadata":{}},{"cell_type":"code","source":"liver_ct = volume*np.where(volume_seg==1,1,0)\nspleen_ct = volume*np.where(volume_seg==2,1,0)\nr_kidney_ct = volume*np.where(volume_seg==3,1,0)\nl_kidney_ct = volume*np.where(volume_seg==4,1,0)\nbowel_ct = volume*np.where(volume_seg==5,1,0)","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:21:17.467686Z","iopub.execute_input":"2023-08-18T17:21:17.468995Z","iopub.status.idle":"2023-08-18T17:21:29.505097Z","shell.execute_reply.started":"2023-08-18T17:21:17.46895Z","shell.execute_reply":"2023-08-18T17:21:29.503615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"z =500 #slice number\nfig = plt.figure(figsize=(16,16))\nax1 = fig.add_subplot(151)\nax1.imshow(liver_ct[:,:,z], cmap = 'gray') #liver\nax2 = fig.add_subplot(152)\nax2.imshow(spleen_ct[:,:,380], cmap = 'gray') #spleen\nax3 = fig.add_subplot(153)\nax3.imshow(r_kidney_ct[:,:,z], cmap = 'gray') #right kidney\nax4 = fig.add_subplot(154)\nax4.imshow(l_kidney_ct[:,:,z], cmap = 'gray') #left kidney\nax5 = fig.add_subplot(155)\nax5.imshow(bowel_ct[:,:,z], cmap = 'gray') #bowel\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-18T17:21:29.507605Z","iopub.execute_input":"2023-08-18T17:21:29.508024Z","iopub.status.idle":"2023-08-18T17:21:30.402736Z","shell.execute_reply.started":"2023-08-18T17:21:29.507987Z","shell.execute_reply":"2023-08-18T17:21:30.401856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}