{"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":"The stats shows that:\n*     In train dataset there are 3147 patients.\n*     In test dataset there are 3 patients.\n*     Each patient has 1 or 2 scans. Average scan number shows that half of the patients have 2 scans.\n*     Each scan has minimum single image, maximum 1727 sequential images. The average is 318.","metadata":{}},{"cell_type":"code","source":"import os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom PIL import Image\nfrom IPython.display import HTML\n\ndef animate_dicom_files(dicom_directory):\n    dicom_files = [f for f in os.listdir(dicom_directory) if f.endswith('.dcm')]\n    dicom_files.sort()\n\n    fig, ax = plt.subplots()\n    ims = []\n\n    for dicom_file in dicom_files:\n        ds = pydicom.dcmread(os.path.join(dicom_directory, dicom_file))\n        pixel_data = ds.pixel_array\n        normalized_data = ((pixel_data - pixel_data.min()) / (pixel_data.max() - pixel_data.min()) * 255.0).astype('uint8')\n        img = Image.fromarray(normalized_data)\n        im = plt.imshow(img, cmap='gray', animated=True)\n        ims.append([im])\n\n    ani = animation.ArtistAnimation(fig, ims, interval=100, blit=True)\n\n    plt.close()\n\n    return HTML(ani.to_jshtml())\n\n# Replace with your actual directory containing DICOM files\ndicom_directory = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/'\n\nanimate_dicom_files(dicom_directory)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:37:07.869234Z","iopub.execute_input":"2023-08-13T07:37:07.870408Z","iopub.status.idle":"2023-08-13T07:39:03.518503Z","shell.execute_reply.started":"2023-08-13T07:37:07.870338Z","shell.execute_reply":"2023-08-13T07:39:03.516381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dicom_directory2 = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/51033/'","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:39:56.852616Z","iopub.execute_input":"2023-08-13T07:39:56.853063Z","iopub.status.idle":"2023-08-13T07:39:56.858994Z","shell.execute_reply.started":"2023-08-13T07:39:56.853025Z","shell.execute_reply":"2023-08-13T07:39:56.85771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate_dicom_files(dicom_directory2)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:40:09.977522Z","iopub.execute_input":"2023-08-13T07:40:09.978015Z","iopub.status.idle":"2023-08-13T07:42:07.124526Z","shell.execute_reply.started":"2023-08-13T07:40:09.977976Z","shell.execute_reply":"2023-08-13T07:42:07.122543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f1 = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10026/29700/1.dcm'\nf2 = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10026/42932/1.dcm'","metadata":{"execution":{"iopub.status.busy":"2023-08-13T11:58:33.511586Z","iopub.execute_input":"2023-08-13T11:58:33.5121Z","iopub.status.idle":"2023-08-13T11:58:33.518103Z","shell.execute_reply.started":"2023-08-13T11:58:33.51206Z","shell.execute_reply":"2023-08-13T11:58:33.516942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10026/","metadata":{"execution":{"iopub.status.busy":"2023-08-13T11:58:08.321987Z","iopub.execute_input":"2023-08-13T11:58:08.322526Z","iopub.status.idle":"2023-08-13T11:58:09.422549Z","shell.execute_reply.started":"2023-08-13T11:58:08.322485Z","shell.execute_reply":"2023-08-13T11:58:09.420678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta(f1)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T11:59:28.069777Z","iopub.execute_input":"2023-08-13T11:59:28.070227Z","iopub.status.idle":"2023-08-13T11:59:28.079717Z","shell.execute_reply.started":"2023-08-13T11:59:28.070195Z","shell.execute_reply":"2023-08-13T11:59:28.07884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta(f2)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T11:59:34.017627Z","iopub.execute_input":"2023-08-13T11:59:34.018397Z","iopub.status.idle":"2023-08-13T11:59:34.058718Z","shell.execute_reply.started":"2023-08-13T11:59:34.018349Z","shell.execute_reply":"2023-08-13T11:59:34.057602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dicom_to_png(dicom_file):\n    # Read DICOM file\n    ds = pydicom.dcmread(dicom_file)\n\n    # Convert pixel data to a NumPy array\n    pixel_data = ds.pixel_array\n\n    # Normalize pixel values to 0-255\n    pixel_data = ((pixel_data - pixel_data.min()) / (pixel_data.max() - pixel_data.min()) * 255.0).astype('uint8')\n\n    # Create an image from the pixel data\n    image = Image.fromarray(pixel_data)\n        \n    return image","metadata":{"execution":{"iopub.status.busy":"2023-08-09T09:09:12.382883Z","iopub.execute_input":"2023-08-09T09:09:12.383377Z","iopub.status.idle":"2023-08-09T09:09:12.391523Z","shell.execute_reply.started":"2023-08-09T09:09:12.383341Z","shell.execute_reply":"2023-08-09T09:09:12.389956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"singlesequence = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057'","metadata":{"execution":{"iopub.status.busy":"2023-08-09T09:08:29.826253Z","iopub.execute_input":"2023-08-09T09:08:29.827102Z","iopub.status.idle":"2023-08-09T09:08:29.832918Z","shell.execute_reply.started":"2023-08-09T09:08:29.827051Z","shell.execute_reply":"2023-08-09T09:08:29.831502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dcm1 = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/171.dcm'\ndcm2 = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/1000.dcm'\ndcm3 = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/1192.dcm'","metadata":{"execution":{"iopub.status.busy":"2023-08-11T08:55:56.27233Z","iopub.execute_input":"2023-08-11T08:55:56.272759Z","iopub.status.idle":"2023-08-11T08:55:56.278781Z","shell.execute_reply.started":"2023-08-11T08:55:56.272723Z","shell.execute_reply":"2023-08-11T08:55:56.277507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pydicom\ndef meta(file_path):\n    # Load the DICOM file\n    ds = pydicom.dcmread(file_path)\n    \n    # Print some common metadata attributes\n    print(\"Patient ID:\", ds.PatientID)\n    # Add more attributes as needed\n    print(ds)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T11:59:07.146397Z","iopub.execute_input":"2023-08-13T11:59:07.146867Z","iopub.status.idle":"2023-08-13T11:59:07.290387Z","shell.execute_reply.started":"2023-08-13T11:59:07.146834Z","shell.execute_reply":"2023-08-13T11:59:07.289258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta(dcm3)","metadata":{"execution":{"iopub.status.busy":"2023-08-11T09:02:29.697349Z","iopub.execute_input":"2023-08-11T09:02:29.697774Z","iopub.status.idle":"2023-08-11T09:02:29.715447Z","shell.execute_reply.started":"2023-08-11T09:02:29.697743Z","shell.execute_reply":"2023-08-11T09:02:29.714504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\nfrom skimage import transform\n\n# Step 1: Data Loading\n\ndef load_dicom_series(series_dir):\n    series = []\n    for filename in sorted(os.listdir(series_dir)):\n        if filename.endswith('.dcm'):\n            ds = pydicom.dcmread(os.path.join(series_dir, filename))\n            image = ds.pixel_array.astype(np.float32)\n            series.append(image)\n    return series\n\n# Example usage:\npatient_dir = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/'\nimage_series = load_dicom_series(patient_dir)\n\n\n# Step 2: Image Preprocessing\n\ndef preprocess_image(image, target_size=(512, 512), normalize=True):\n    # Resize image\n    image = transform.resize(image, target_size, mode='reflect', anti_aliasing=True)\n    \n    if normalize:\n        # Normalize pixel values to [0, 1]\n        image = (image - np.min(image)) / (np.max(image) - np.min(image))\n    \n    return image\n\n# Example usage:\npreprocessed_images = [preprocess_image(image) for image in image_series]\n","metadata":{"execution":{"iopub.status.busy":"2023-08-12T07:50:12.177577Z","iopub.execute_input":"2023-08-12T07:50:12.178488Z","iopub.status.idle":"2023-08-12T07:50:38.651726Z","shell.execute_reply.started":"2023-08-12T07:50:12.178452Z","shell.execute_reply":"2023-08-12T07:50:38.650709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2023-08-12T07:51:34.512014Z","iopub.execute_input":"2023-08-12T07:51:34.512453Z","iopub.status.idle":"2023-08-12T07:51:34.519714Z","shell.execute_reply.started":"2023-08-12T07:51:34.512415Z","shell.execute_reply":"2023-08-12T07:51:34.518613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\nimport tensorflow as tf\nfrom skimage import transform\n\n# Step 1: Data Loading\n\ndef load_dicom_series(series_dir):\n    series = []\n    for filename in sorted(os.listdir(series_dir)):\n        if filename.endswith('.dcm'):\n            ds = pydicom.dcmread(os.path.join(series_dir, filename))\n            image = ds.pixel_array.astype(np.float32)\n            series.append(image)\n    return series\n\n# Step 2: Image Preprocessing\n\ndef preprocess_image(image, target_size=(512, 512), normalize=True, windowing=True):\n    # Resize image\n    image = transform.resize(image, target_size, mode='reflect', anti_aliasing=True)\n    \n    if normalize:\n        # Normalize pixel values to [0, 1]\n        image = (image - np.min(image)) / (np.max(image) - np.min(image))\n    \n    return image\n\n# Dataset Creation\n\ndef create_dataset(root_dir, batch_size=32, target_size=(512, 512)):\n    patient_dirs = [os.path.join(root_dir, patient_id) for patient_id in os.listdir(root_dir)]\n    image_paths = []\n    labels = []  # Replace with your actual labels\n\n    for patient_dir in patient_dirs:\n        image_series = load_dicom_series(patient_dir)\n        preprocessed_images = [preprocess_image(image, target_size=target_size) for image in image_series]\n\n        image_paths.extend(preprocessed_images)\n        # Add corresponding labels for each patient here\n        labels.extend([1]*len(image_series))\n\n    image_paths = np.array(image_paths)\n    labels = np.array(labels)\n\n    dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))\n\n    def preprocess_path(image, label):\n        image = tf.image.decode_png(image, channels=1)  # Adjust channels as needed\n        image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n        return image, label\n\n    dataset = dataset.map(preprocess_path)\n    dataset = dataset.batch(batch_size)\n    dataset = dataset.prefetch(buffer_size=tf.data.AUTOTUNE)\n\n    return dataset\n\n# Example usage:\nroot_directory = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004'\nbatch_size = 16\ntarget_image_size = (512, 512)\ndisease_labels = [0, 1, 0, 1, 0]  # Replace with actual labels for each disease\n\ntrain_dataset = create_dataset(root_directory, batch_size=batch_size, target_size=target_image_size)\n","metadata":{"execution":{"iopub.status.busy":"2023-08-12T13:58:20.072426Z","iopub.execute_input":"2023-08-12T13:58:20.072779Z","iopub.status.idle":"2023-08-12T13:59:19.954512Z","shell.execute_reply.started":"2023-08-12T13:58:20.072749Z","shell.execute_reply":"2023-08-12T13:59:19.952274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preprocess_path","metadata":{"execution":{"iopub.status.busy":"2023-08-12T13:59:33.847996Z","iopub.execute_input":"2023-08-12T13:59:33.848331Z","iopub.status.idle":"2023-08-12T13:59:33.886166Z","shell.execute_reply.started":"2023-08-12T13:59:33.848304Z","shell.execute_reply":"2023-08-12T13:59:33.88445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_series","metadata":{"execution":{"iopub.status.busy":"2023-08-12T08:04:49.594504Z","iopub.execute_input":"2023-08-12T08:04:49.594961Z","iopub.status.idle":"2023-08-12T08:04:49.60211Z","shell.execute_reply.started":"2023-08-12T08:04:49.594926Z","shell.execute_reply":"2023-08-12T08:04:49.601028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"[4,5]*5","metadata":{"execution":{"iopub.status.busy":"2023-08-12T08:12:10.55175Z","iopub.execute_input":"2023-08-12T08:12:10.552199Z","iopub.status.idle":"2023-08-12T08:12:10.560674Z","shell.execute_reply.started":"2023-08-12T08:12:10.552168Z","shell.execute_reply":"2023-08-12T08:12:10.559364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import TimeDistributed, Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\n# Define the parameters\nnum_classes = 10\ninput_shape = (64, 64, 3)  # Adjust this according to your image dimensions\nsequence_length = 10      # Number of frames in each sequence\n\n# Create a simple CNN model\nmodel = Sequential([\n    TimeDistributed(Conv2D(32, (3, 3), activation='relu'), input_shape=(sequence_length, *input_shape)),\n    TimeDistributed(MaxPooling2D((2, 2))),\n    TimeDistributed(Conv2D(64, (3, 3), activation='relu')),\n    TimeDistributed(MaxPooling2D((2, 2))),\n    TimeDistributed(Conv2D(128, (3, 3), activation='relu')),\n    TimeDistributed(MaxPooling2D((2, 2))),\n    TimeDistributed(Flatten()),\n    TimeDistributed(Dense(128, activation='relu')),\n    TimeDistributed(Dropout(0.5)),\n    TimeDistributed(Dense(num_classes, activation='softmax'))\n])\n\n# Compile the model\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Generate synthetic data for demonstration purposes\nimport numpy as np\n\n# Create synthetic image sequence data\nnum_samples = 1000\nsequences = np.random.random((num_samples, sequence_length, *input_shape))\nlabels = np.random.randint(num_classes, size=num_samples)\nlabels = tf.keras.utils.to_categorical(labels, num_classes)\n\n# Train the model\nmodel.fit(sequences, labels, epochs=10, batch_size=32)\n\n# Save the model for future use\nmodel.save('image_sequence_classifier.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-08-13T12:26:34.600735Z","iopub.execute_input":"2023-08-13T12:26:34.601194Z","iopub.status.idle":"2023-08-13T12:26:37.08375Z","shell.execute_reply.started":"2023-08-13T12:26:34.60116Z","shell.execute_reply":"2023-08-13T12:26:37.082159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\n\nclass ImageClassificationRNN(nn.Module):\n    def __init__(self, num_classes, hidden_size, num_layers):\n        super(ImageClassificationRNN, self).__init__()\n        self.num_classes = num_classes\n        self.hidden_size = hidden_size\n        self.num_layers = num_layers\n        \n        self.lstm = nn.LSTM(input_size=4096, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)\n        self.fc = nn.Linear(hidden_size, num_classes)\n    \n    def forward(self, x):\n        # x: (batch_size, sequence_length, image_height, image_width)\n        batch_size, _, sequence_length, image_height, image_width = x.size()\n        \n        # Reshape to (batch_size * sequence_length, image_height, image_width)\n        x = x.view(-1, 1, image_height, image_width)\n        \n        # Apply transforms to normalize and resize images\n        transforms_list = [\n            transforms.Resize((image_height, image_width)),\n            transforms.Normalize((0.5,), (0.5,))\n        ]\n        transform = transforms.Compose(transforms_list)\n        x = torch.stack([transform(image) for image in x])\n        \n        # Reshape back to (batch_size, sequence_length, image_height, image_width)\n        x = x.view(batch_size, sequence_length, image_height, image_width)\n        \n        # Pass through LSTM\n        lstm_out, _ = self.lstm(x.view(batch_size, sequence_length, -1))\n        \n        # Get the output from the last time step\n        lstm_out = lstm_out[:, -1, :]\n        \n        # Pass through fully connected layer\n        output = self.fc(lstm_out)\n        \n        return output\n\n# Example usage\nnum_classes = 10\nhidden_size = 128\nnum_layers = 2\n\nmodel = ImageClassificationRNN(num_classes, hidden_size, num_layers)\n\n# Create a sample input tensor (batch_size, sequence_length, image_height, image_width)\nbatch_size = 2\nsequence_length = 3\nimage_height = 64\nimage_width = 64\nnum_channels = 1  # Change to 1 for grayscale\nsample_input = torch.randn(batch_size, 1, sequence_length, image_height, image_width)\n\n# Create an instance of the model\nnum_classes = 10\nhidden_size = 128\nnum_layers = 2\nmodel = ImageClassificationRNN(num_classes, hidden_size, num_layers)\n\n# Perform a forward pass\noutputs = model(sample_input)\n\n# Print the outputs for each sample in the batch\nfor i in range(batch_size):\n    print(f\"Sample {i+1} outputs: {outputs[i]}\")\n","metadata":{"execution":{"iopub.status.busy":"2023-08-13T13:05:38.365665Z","iopub.execute_input":"2023-08-13T13:05:38.366198Z","iopub.status.idle":"2023-08-13T13:05:38.408306Z","shell.execute_reply.started":"2023-08-13T13:05:38.366161Z","shell.execute_reply":"2023-08-13T13:05:38.407274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n\n# Create a sample input tensor (batch_size, sequence_length, image_height, image_width)\nbatch_size = 2\nsequence_length = 3\nimage_height = 64\nimage_width = 64\nnum_channels = 1  # Change to 1 for grayscale\nsample_input = torch.randn(batch_size, 1, sequence_length, image_height, image_width)\n\n# Create an instance of the model\nnum_classes = 10\nhidden_size = 128\nnum_layers = 2\nmodel = ImageClassificationRNN(num_classes, hidden_size, num_layers)\n\n# Perform a forward pass\noutputs = model(sample_input)\n\n# Print the outputs for each sample in the batch\nfor i in range(batch_size):\n    print(f\"Sample {i+1} outputs: {outputs[i]}\")\n","metadata":{"execution":{"iopub.status.busy":"2023-08-13T13:05:42.628482Z","iopub.execute_input":"2023-08-13T13:05:42.629817Z","iopub.status.idle":"2023-08-13T13:05:42.809715Z","shell.execute_reply.started":"2023-08-13T13:05:42.629767Z","shell.execute_reply":"2023-08-13T13:05:42.808277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2 \nimg = cv2.imread('picture.jpg')\t\t# assuming color image\t \nprint(img.shape) \t","metadata":{},"execution_count":null,"outputs":[]}]}