{"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":"markdown","source":"# One Patient Images Slide Show \npatient_id 10494","metadata":{"papermill":{"duration":0.006229,"end_time":"2022-12-19T12:04:21.972985","exception":false,"start_time":"2022-12-19T12:04:21.966756","status":"completed"},"tags":[]}},{"cell_type":"code","source":"#https://www.kaggle.com/competitions/rsna-breast-cancer-detection/discussion/370045\n#!pip install -U pylibjpeg pylibjpeg-openjpeg pylibjpeg-libjpeg pydicom python-gdcm","metadata":{"_kg_hide-output":true,"papermill":{"duration":21.850887,"end_time":"2022-12-19T12:04:43.837453","exception":false,"start_time":"2022-12-19T12:04:21.986566","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-06T05:37:42.425277Z","iopub.execute_input":"2023-08-06T05:37:42.426098Z","iopub.status.idle":"2023-08-06T05:37:42.465531Z","shell.execute_reply.started":"2023-08-06T05:37:42.426053Z","shell.execute_reply":"2023-08-06T05:37:42.464332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install pylibjpeg --no-index --find-links=file:///kaggle/input/read-dicom-set\n!pip install pylibjpeg-openjpeg --no-index --find-links=file:///kaggle/input/read-dicom-set\n!pip install pylibjpeg-libjpeg --no-index --find-links=file:///kaggle/input/read-dicom-set\n!pip install pydicom --no-index --find-links=file:///kaggle/input/read-dicom-set\n!pip install python-gdcm --no-index --find-links=file:///kaggle/input/read-dicom-set\n!pip install dicomsdl --no-index --find-links=file:///kaggle/input/read-dicom-set","metadata":{"execution":{"iopub.status.busy":"2023-08-06T05:37:42.467445Z","iopub.execute_input":"2023-08-06T05:37:42.468038Z","iopub.status.idle":"2023-08-06T05:39:13.370541Z","shell.execute_reply.started":"2023-08-06T05:37:42.468003Z","shell.execute_reply":"2023-08-06T05:39:13.369002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport cv2\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport pylibjpeg\nfrom libjpeg import decode\nimport pydicom as dicom\nfrom pydicom import dcmread\nfrom pydicom.data import get_testdata_file\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-output":true,"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":8.231928,"end_time":"2022-12-19T12:04:52.078417","exception":false,"start_time":"2022-12-19T12:04:43.846489","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-06T07:46:54.541777Z","iopub.status.idle":"2023-08-06T07:46:54.542383Z","shell.execute_reply.started":"2023-08-06T07:46:54.542179Z","shell.execute_reply":"2023-08-06T07:46:54.542201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths=[]\nfiles=[]\nids=[]\ntraintest=[]\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        if filename[-4:]!='.csv':\n            paths+=[(os.path.join(dirname, filename))]\n            files+=[filename[:-4]]\n            ids+=[dirname.split('/')[-1]]\n            traintest+=[dirname.split('/')[-2]]","metadata":{"_kg_hide-output":true,"papermill":{"duration":73.173455,"end_time":"2022-12-19T12:06:05.261398","exception":false,"start_time":"2022-12-19T12:04:52.087943","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2023-08-06T05:39:25.672688Z","iopub.execute_input":"2023-08-06T05:39:25.67359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Images of patient_id 10494","metadata":{}},{"cell_type":"code","source":"paths=[]\nfiles=[]\nids1=[]\nids2=[]\ntraintest=[]\nfor dirname, _, filenames in os.walk('/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10494/65369'):\n    for filename in filenames:\n        if filename[-4:]!='.csv' and filename[-4:]!='quet':\n            paths+=[(os.path.join(dirname, filename))]\n            files+=[filename[:-4]]\n            ids1+=[dirname.split('/')[-1]]\n            ids2+=[dirname.split('/')[-2]]#patient_id\n            traintest+=[dirname.split('/')[-3]]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data0=pd.DataFrame(columns=['path','file','id1','id2','train/test'])\ndata0['path']=paths\ndata0['file']=files\ndata0['id1']=ids1#sequence_id\ndata0['id2']=ids2#patient_id\ndata0['train/test']=traintest\ndisplay(data0)\ndata0['newfile']=data0['id2']+'_'+data0['id1']+'_'+data0['file'].astype(str).str.zfill(4)+'.png'\ndisplay(data0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Labels of patient_id 10494","metadata":{}},{"cell_type":"code","source":"train=pd.read_csv('/kaggle/input/rsna-2023-abdominal-trauma-detection/train.csv')\ntrain2=train[train['patient_id']==10494]\ndisplay(train2.T)\n#extravasation_injury","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Read DICOM and transferred to PNG","metadata":{"papermill":{"duration":0.007921,"end_time":"2022-12-19T12:06:08.008874","exception":false,"start_time":"2022-12-19T12:06:08.000953","status":"completed"},"tags":[]}},{"cell_type":"code","source":"print(len(paths))\npaths=sorted(paths)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#images=[]\n#newfiles=[]\nerrors=[]\ndataset=[]\n\nfor i,path in enumerate(paths):#[0:30000]\n    img=dicom.dcmread(path,force=True)\n    pip=img.PhotometricInterpretation\n    if i%5000==0:\n        print(len(paths),i)\n\n    try:\n        data=img.pixel_array\n        data=data-np.min(data)\n        if np.max(data) != 0:\n            data=data/np.max(data)\n        data=(data*255).astype(np.uint8)  \n        data=cv2.cvtColor(data,cv2.COLOR_GRAY2RGB)\n        data=cv2.cvtColor(data,cv2.COLOR_BGR2GRAY)\n        data=cv2.resize(data,dsize=(224,224))\n        if pip=='MONOCHROME2':\n            data=255-data\n        ps=path.split('/')[-4:]\n        newfile=ps[-3]+'_'+ps[-2]+'_'+ps[-1][0:-4].zfill(4)+'.png'\n        cv2.imwrite(newfile,data)\n        #images+=[data]\n        #newfiles+=[newfile]\n        if data.max()>0:\n            dataset+=[(newfile,data)]\n        \n    except:\n        errors+=[i]\n        #newfiles+=['N']\n\nprint(len(dataset),len(errors))","metadata":{"papermill":{"duration":28474.854895,"end_time":"2022-12-19T20:00:42.873706","exception":false,"start_time":"2022-12-19T12:06:08.018811","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset=sorted(dataset)\n\nimages=[]\nfor i in range(len(dataset)):\n    if i%4==0:\n        images+=[dataset[i][1]]\nprint(len(images))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Slide Show","metadata":{"papermill":{"duration":0.010102,"end_time":"2022-12-19T20:00:42.894991","exception":false,"start_time":"2022-12-19T20:00:42.884889","status":"completed"},"tags":[]}},{"cell_type":"code","source":"from matplotlib import animation, rc\nrc('animation', html='jshtml')","metadata":{"papermill":{"duration":0.064293,"end_time":"2022-12-19T20:00:42.971953","exception":false,"start_time":"2022-12-19T20:00:42.90766","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_animation(ims):    \n    fig=plt.figure(figsize=(4,4))\n    #im=ims[0]\n    im=plt.imshow(cv2.cvtColor(ims[0],cv2.COLOR_BGR2RGB))\n    text = plt.text(0.05, 0.05, f'Slide {0}', transform=fig.transFigure, fontsize=14, color='blue')\n    def animate_func(i):\n        im.set_array(cv2.cvtColor(ims[i],cv2.COLOR_BGR2RGB))\n        text.set_text(f'Slide {i}')        \n        return [im] \n    plt.axis('off')\n    plt.gray()\n    plt.close()    \n\n    return animation.FuncAnimation(fig, animate_func, frames=len(ims), interval=1000//10)","metadata":{"papermill":{"duration":0.02353,"end_time":"2022-12-19T20:00:43.004966","exception":false,"start_time":"2022-12-19T20:00:42.981436","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_animation(images)","metadata":{"papermill":{"duration":709.991665,"end_time":"2022-12-19T20:12:33.038611","exception":false,"start_time":"2022-12-19T20:00:43.046946","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Which image shows extravasation_injury of patient_id 10494 ?\n* There is too many slices with no lesions even in patients with some abnormality.\n* I need to collect images with lesions, but I can't even identify the organ, let alone identify the abnormal area.\n* First I should understand the organ positions in series of images.","metadata":{}},{"cell_type":"markdown","source":"## To understand the organ positions, please confir the segmentation image of patient_id 10494","metadata":{}},{"cell_type":"markdown","source":"https://www.kaggle.com/stpeteishii/segmentation-image-of-the-matched-id","metadata":{}},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.693514,"end_time":"2022-12-19T20:12:35.819034","exception":false,"start_time":"2022-12-19T20:12:35.12552","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]}]}