{"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":"# Differenciating between Active Extravasation and Bowel injuries.","metadata":{}},{"cell_type":"markdown","source":"### Importing the necessary modules","metadata":{}},{"cell_type":"code","source":"import pydicom as dicom\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport pandas as pd\nfrom skimage import img_as_float\nfrom skimage.transform import resize \nfrom IPython.display import display\nimport tensorflow as tf\nimport random\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T04:42:33.700162Z","iopub.execute_input":"2023-08-15T04:42:33.700442Z","iopub.status.idle":"2023-08-15T04:42:44.562959Z","shell.execute_reply.started":"2023-08-15T04:42:33.700416Z","shell.execute_reply":"2023-08-15T04:42:44.561924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# Setting paths are variables","metadata":{"execution":{"iopub.status.busy":"2023-08-15T04:42:44.564693Z","iopub.execute_input":"2023-08-15T04:42:44.565413Z","iopub.status.idle":"2023-08-15T04:42:44.571908Z","shell.execute_reply.started":"2023-08-15T04:42:44.565379Z","shell.execute_reply":"2023-08-15T04:42:44.570707Z"}}},{"cell_type":"code","source":"# Using the data set\npath=\"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/\"\ntestpath=\"/kaggle/input/rsna-2023-abdominal-trauma-detection/test_images\"","metadata":{"execution":{"iopub.status.busy":"2023-08-15T04:42:44.574414Z","iopub.execute_input":"2023-08-15T04:42:44.575355Z","iopub.status.idle":"2023-08-15T04:42:44.582611Z","shell.execute_reply.started":"2023-08-15T04:42:44.575321Z","shell.execute_reply":"2023-08-15T04:42:44.581591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# A function that converts the .dicom image to a .png.","metadata":{}},{"cell_type":"code","source":"def convert_to_png(path, flag):\n    try:\n        os.makedirs('/kaggle/working/images/Active_Extravasation')\n        os.makedirs('/kaggle/working/images/Bowel')\n    except:\n        pass\n    try:\n         os.makedirs('/kaggle/working/test')\n    except:\n        pass\n    for root, _, files in os.walk(path):\n        try:\n            patient_id = int(root.split(\"/\")[-2])\n        except:\n            continue\n        for file in files:\n            filepath = os.path.join(root, file)\n            filename = os.path.basename(filepath)\n            try:\n                label_data = pd.read_csv(\"/kaggle/input/rsna-2023-abdominal-trauma-detection/image_level_labels.csv\")\n                label_data = label_data[label_data[\"patient_id\"] == patient_id]\n                if label_data.empty: \n                    continue\n                scan_image = dicom.dcmread(filepath).pixel_array.astype(float)\n                img = (np.maximum(scan_image, 0) / scan_image.max()) * 255.0\n                img = np.uint8(img)\n                if flag == 1:\n                    if label_data.iloc[0][\"injury_name\"] == \"Active_Extravasation\":\n                        Image.fromarray(img).save('/kaggle/working/images/Active_Extravasation/{}.png'.format(filename[:-4]))\n                    if label_data.iloc[0][\"injury_name\"] == \"Bowel\":\n                        Image.fromarray(img).save('/kaggle/working/images/Bowel/{}.png'.format(filename[:-4]))\n                if flag == 0:\n                    Image.fromarray(img).save('/kaggle/working/test/{}.png'.format(filename[:-4]+str(random.randrange(20, 50))))\n            except:\n                pass","metadata":{"execution":{"iopub.status.busy":"2023-08-15T04:42:44.585917Z","iopub.execute_input":"2023-08-15T04:42:44.586295Z","iopub.status.idle":"2023-08-15T04:42:44.600199Z","shell.execute_reply.started":"2023-08-15T04:42:44.586268Z","shell.execute_reply":"2023-08-15T04:42:44.599005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Running the converion function","metadata":{}},{"cell_type":"code","source":"convert_to_png(path,1)\nconvert_to_png(testpath, 0)\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T04:42:44.60199Z","iopub.execute_input":"2023-08-15T04:42:44.602421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Using keras to store our processed files in a dataset.","metadata":{}},{"cell_type":"code","source":"# Setting the dataset\ndata = tf.keras.utils.image_dataset_from_directory(\"/kaggle/working/images\")\ndata_iterator = data.as_numpy_iterator()\nbatch = data_iterator.next()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Showing images to find out which classes they belong","metadata":{}},{"cell_type":"code","source":"# Showing images\n# class 1 = Bowel\n# Class 0 = Active Extravasation\nfig, ax = plt.subplots(ncols=4, figsize=(20,20))\nfor index, img in enumerate(batch[0][:4]):\n    ax[index].imshow(img.astype(int))\n    ax[index].title.set_text(batch[1][index])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Scaling the images","metadata":{}},{"cell_type":"code","source":"# Scaling\ndata = data.map(lambda x,y: (x/255, y))\ndata_iterator = data.as_numpy_iterator()\nbatch = data_iterator.next()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(ncols=4, figsize=(20,20))\nfor index, img in enumerate(batch[0][:4]):\n    ax[index].imshow(img.astype(float))\n    ax[index].title.set_text(batch[1][index])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Splitting the data","metadata":{}},{"cell_type":"code","source":"# Splitting the data\ntraining_size = int(len(data)*.7)\nval_size = int(len(data)*.2)+1\ntest_size = int(len(data)*.1)+1","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = data.take(training_size)\nval = data.skip(training_size).take(val_size)\ntest = data.skip(training_size+val_size).take(test_size)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Deep learning model","metadata":{}},{"cell_type":"code","source":"# Importing neccessary modules\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D,Dense, Flatten, Dropout","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.add(Conv2D(16,(3,3),1,activation=\"relu\", input_shape=(256,256,3)))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(32,(3,3),1,activation=\"relu\"))\nmodel.add(MaxPooling2D())\n \nmodel.add(Conv2D(16,(3,3),1,activation=\"relu\"))\nmodel.add(MaxPooling2D())\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dense(1,activation=\"sigmoid\"))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\"adam\", loss=tf.losses.BinaryCrossentropy(), metrics=[\"accuracy\"])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating Logs\ntry:\n    os.makedirs('/kaggle/working/logs')\nexcept:\n    pass\nlogdir = '/kaggle/working/logs'\ntensor_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Fitting the model","metadata":{}},{"cell_type":"code","source":"hist = model.fit(train, epochs=20, validation_data=val, callbacks=[tensor_callback])","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}