{"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":"# Segmentation Image of the matched patient_id 10494","metadata":{}},{"cell_type":"markdown","source":"https://www.kaggle.com/code/stpeteishii/one-patient-images-slide-show","metadata":{}},{"cell_type":"markdown","source":"segmentations/ Model generated pixel-level annotations of the relevant organs and some major bones for a subset of the scans in the training set. This data is provided in the nifti file format. The filenames are series IDs. You can find a description of the source model (total segmentator) here and the data used to train that model here.\n\nNote that the NIFTI files and DICOM files are not in the same orientation. Use the NIFTI header information along with DICOM metadata to determine the appropriate orientation.","metadata":{}},{"cell_type":"markdown","source":"    !rm *\n    !rm -rf 0\n    !rm -rf 1\n    !rm -rf 2\n    !rm -rf 3\n    !rm -rf 4\n","metadata":{}},{"cell_type":"code","source":"!pip install nibabel","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:20.193729Z","iopub.execute_input":"2023-08-06T12:57:20.194179Z","iopub.status.idle":"2023-08-06T12:57:29.155217Z","shell.execute_reply.started":"2023-08-06T12:57:20.194129Z","shell.execute_reply":"2023-08-06T12:57:29.153629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport nibabel as nib\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation, rc\nrc('animation', html='jshtml')","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:29.157376Z","iopub.execute_input":"2023-08-06T12:57:29.15782Z","iopub.status.idle":"2023-08-06T12:57:29.164272Z","shell.execute_reply.started":"2023-08-06T12:57:29.15778Z","shell.execute_reply":"2023-08-06T12:57:29.163093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths=[]\nids=[]\nfor dirname, _, filenames in os.walk('/kaggle/input/rsna-2023-abdominal-trauma-detection/segmentations'):\n    for filename in filenames:\n        ids+=[filename[0:-4]]\n        paths+=[(os.path.join(dirname, filename))]","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:29.166101Z","iopub.execute_input":"2023-08-06T12:57:29.166424Z","iopub.status.idle":"2023-08-06T12:57:29.183255Z","shell.execute_reply.started":"2023-08-06T12:57:29.166398Z","shell.execute_reply":"2023-08-06T12:57:29.182474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ids= os.listdir('/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images')\nprint(list(set(ids) & set(train_ids)))\n# segmentation data of patinent_id used in train data","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:29.185813Z","iopub.execute_input":"2023-08-06T12:57:29.186131Z","iopub.status.idle":"2023-08-06T12:57:29.202211Z","shell.execute_reply.started":"2023-08-06T12:57:29.186106Z","shell.execute_reply":"2023-08-06T12:57:29.200678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tpaths=[]\nfor dirname, _, filenames in os.walk('/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10494'):\n    for filename in filenames:\n        tpaths+=[(os.path.join(dirname, filename))]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# id=10494 (214 slices)","metadata":{}},{"cell_type":"code","source":"images=[]\nfor path in paths:\n    if path.split('/')[-1]=='10494.nii':\n        nii_img = nib.load(path)\n        data = nii_img.get_fdata()\n        print(data.shape)\n        imagesi=[]\n        for i in range(data.shape[2]):\n            img=data[:,:,i]*51\n            if img.max()>0:\n                #print(img.max())\n                img=np.rot90(img)\n                plt.figure(figsize=(4,4))\n                plt.imshow(img)\n                plt.axis('off')\n                plt.show()\n                newfile='10494_seg_'+str(i).zfill(4)+'.png'\n                print(newfile)\n                cv2.imwrite(newfile,img)\n                imagesi+=[img]\n        print(len(imagesi))\n        images+=[imagesi]","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:29.203367Z","iopub.execute_input":"2023-08-06T12:57:29.203724Z","iopub.status.idle":"2023-08-06T12:57:30.954462Z","shell.execute_reply.started":"2023-08-06T12:57:29.203694Z","shell.execute_reply":"2023-08-06T12:57:30.953751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_animation(ims):\n    fig=plt.figure(figsize=(4,4))\n    im=plt.imshow(ims[0])#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    plt.axis('off')\n    plt.close()\n    def animate_func(i):\n        im.set_array(ims[i])#cv2.cvtColor(ims[i],cv2.COLOR_BGR2RGB)\n        text.set_text(f'Slide {i}')        \n        return [im]       \n    return animation.FuncAnimation(fig, animate_func, frames=len(ims), interval=1000//10)","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:30.95564Z","iopub.execute_input":"2023-08-06T12:57:30.956117Z","iopub.status.idle":"2023-08-06T12:57:30.961893Z","shell.execute_reply.started":"2023-08-06T12:57:30.956088Z","shell.execute_reply":"2023-08-06T12:57:30.961213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_animation(images[0])","metadata":{"execution":{"iopub.status.busy":"2023-08-06T12:57:30.962986Z","iopub.execute_input":"2023-08-06T12:57:30.963442Z","iopub.status.idle":"2023-08-06T12:57:31.935027Z","shell.execute_reply.started":"2023-08-06T12:57:30.963418Z","shell.execute_reply":"2023-08-06T12:57:31.933516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# split image by organ","metadata":{}},{"cell_type":"code","source":"path0='10494_seg_0175.png'\n\nplt.figure(figsize=(4,4))\nimage3 = cv2.imread(path0)\nplt.imshow(image3)\nplt.axis('off')\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image = cv2.imread(path0, cv2.IMREAD_COLOR)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nhsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\npixels = np.argwhere(hsv>0)\nall_colors = {tuple(image[pixel[0], pixel[1]]) for pixel in pixels}\nprint(\"All colors:\", all_colors)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"colors=[(51, 51, 51), (255, 255, 255), (102, 102, 102), (204, 204, 204), (153, 153, 153)]\norgans=['bowel','liver','spleen','right kidney','left kidney']\n\nfor i,color in enumerate(colors):\n    lower_color = color\n    upper_color = color\n    mask = cv2.inRange(image, lower_color, upper_color)\n    focus = cv2.bitwise_and(image, image, mask=mask)\n    print(organs[i])\n    plt.figure(figsize=(3,3))\n    plt.imshow(focus)\n    plt.axis('off')\n    plt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# create segmentation images by organ","metadata":{}},{"cell_type":"code","source":"for i in list('01234'):\n    !mkdir {i}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths3=[]\nfor dirname, _, filenames in os.walk('./'):\n    for filename in filenames:\n        if filename[-4:]=='.png':\n            paths3+=[(os.path.join(dirname, filename))]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for path in paths3:\n    image = cv2.imread(path, cv2.IMREAD_COLOR)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    for i,color in enumerate(colors):\n        lower_color = color\n        upper_color = color\n        mask = cv2.inRange(image, lower_color, upper_color)\n        focus = cv2.bitwise_and(image, image, mask=mask)\n        file=path.split('/')[-1]\n        if focus.sum()>0:\n            print(organs[i],file)\n            cv2.imwrite(os.path.join(str(i),file),focus)\n            plt.figure(figsize=(3,3))\n            plt.imshow(focus)\n            plt.axis('off')\n            plt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}