{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:01.048288Z","iopub.execute_input":"2024-10-22T11:04:01.048703Z","iopub.status.idle":"2024-10-22T11:04:02.434149Z","shell.execute_reply.started":"2024-10-22T11:04:01.048662Z","shell.execute_reply":"2024-10-22T11:04:02.432742Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pydicom\nimport matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:02.439339Z","iopub.execute_input":"2024-10-22T11:04:02.439831Z","iopub.status.idle":"2024-10-22T11:04:02.772718Z","shell.execute_reply.started":"2024-10-22T11:04:02.439794Z","shell.execute_reply":"2024-10-22T11:04:02.771504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dicom_images(directory):\n    dicom_images = []\n    \n    # Iterate over files in the directory\n    for filename in os.listdir(directory):\n        if filename.endswith(\".dcm\"):\n            filepath = os.path.join(directory, filename)\n            dicom_image = pydicom.dcmread(filepath)\n            dicom_images.append(dicom_image)\n    \n    # Sort images by InstanceNumber\n    dicom_images.sort(key=lambda x: x.InstanceNumber)\n    \n    return dicom_images\n\ndef display_image(dicom_image):\n    # Get the pixel array from the DICOM image\n    image_data = dicom_image.pixel_array\n    \n    # Plot the image\n    plt.imshow(image_data, cmap='gray')\n    plt.title(f\"Instance Number: {dicom_image.InstanceNumber}\")\n    plt.axis('off')  # Remove axes for a clean look\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:02.774553Z","iopub.execute_input":"2024-10-22T11:04:02.774997Z","iopub.status.idle":"2024-10-22T11:04:02.785570Z","shell.execute_reply.started":"2024-10-22T11:04:02.774948Z","shell.execute_reply":"2024-10-22T11:04:02.783606Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# def reconstruct_3d_volume(dicom_images):\n#     # Extract pixel arrays from sorted DICOM images and stack them into a 3D array\n#     slices = [dicom_image.pixel_array for dicom_image in dicom_images]\n#     volume_3d = np.stack(slices, axis=-1)  # Stack along the third dimension\n#     return volume_3d\n\n# def visualize_slice(volume_3d, slice_idx):\n#     plt.imshow(volume_3d[:, :, slice_idx], cmap='gray')\n#     plt.title(f\"Slice {slice_idx}\")\n#     plt.axis('off')\n#     plt.show()\n\n# def visualize_3d(volume_3d):\n#     fig = plt.figure(figsize=(10, 10))\n#     ax = fig.add_subplot(111, projection='3d')\n\n#     # Define the grid for the volume data\n#     ax.voxels(volume_3d, edgecolor='k')\n\n#     plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:02.788649Z","iopub.execute_input":"2024-10-22T11:04:02.789413Z","iopub.status.idle":"2024-10-22T11:04:02.807186Z","shell.execute_reply.started":"2024-10-22T11:04:02.789360Z","shell.execute_reply":"2024-10-22T11:04:02.805684Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"directory = \"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/100206310/1792451510/\"  # Replace with the actual directory path\ndicom_images = load_dicom_images(directory)\n\n# Visualize the first DICOM image\nfor dicom_image in dicom_images:\n    display_image(dicom_image)\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:02.808802Z","iopub.execute_input":"2024-10-22T11:04:02.809276Z","iopub.status.idle":"2024-10-22T11:04:03.389716Z","shell.execute_reply.started":"2024-10-22T11:04:02.809224Z","shell.execute_reply":"2024-10-22T11:04:03.388261Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_label_coordinates.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:03.391410Z","iopub.execute_input":"2024-10-22T11:04:03.391900Z","iopub.status.idle":"2024-10-22T11:04:03.507556Z","shell.execute_reply.started":"2024-10-22T11:04:03.391851Z","shell.execute_reply":"2024-10-22T11:04:03.506481Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label.head(1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:03.509184Z","iopub.execute_input":"2024-10-22T11:04:03.509611Z","iopub.status.idle":"2024-10-22T11:04:03.531837Z","shell.execute_reply.started":"2024-10-22T11:04:03.509565Z","shell.execute_reply":"2024-10-22T11:04:03.530589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"grouped_df = label.groupby(['study_id', 'series_id']).size().reset_index(name='count')\n\n# Filter where count is greater than 1\nfiltered_df = grouped_df[grouped_df['count'] > 1]\nfiltered_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:03.533292Z","iopub.execute_input":"2024-10-22T11:04:03.534019Z","iopub.status.idle":"2024-10-22T11:04:03.564743Z","shell.execute_reply.started":"2024-10-22T11:04:03.533968Z","shell.execute_reply":"2024-10-22T11:04:03.563526Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_des = pd.read_csv('/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_series_descriptions.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:04:03.566260Z","iopub.execute_input":"2024-10-22T11:04:03.566705Z","iopub.status.idle":"2024-10-22T11:04:03.588908Z","shell.execute_reply.started":"2024-10-22T11:04:03.566656Z","shell.execute_reply":"2024-10-22T11:04:03.586745Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# def load_dicom_images_with_labels(directory, df, study_id, series_id):\n#     dicom_images = []\n    \n#     # Iterate over files in the directory\n#     for filename in os.listdir(directory):\n#         if filename.endswith(\".dcm\"):\n#             filepath = os.path.join(directory, filename)\n#             dicom_image = pydicom.dcmread(filepath)\n            \n#             # Get the InstanceNumber from the DICOM file\n#             instance_number = dicom_image.InstanceNumber\n            \n#             # Find matching rows in DataFrame\n#             matching_rows = df[(df['study_id'] == int(study_id)) & \n#                                (df['series_id'] == int(series_id)) &\n#                                (df['instance_number'] == int(instance_number))]\n            \n#             # If there are matching rows, overlay the conditions\n#             if not matching_rows.empty:\n#                 for _, row in matching_rows.iterrows():\n#                     dicom_images.append((dicom_image, row))  # Append image and corresponding data\n    \n#     return dicom_images\n\n# def display_image_with_labels(dicom_image, label_data, study_id, series_id):\n#     # Get the pixel array from the DICOM image\n#     image_data = dicom_image.pixel_array\n    \n#     # Plot the image\n#     plt.imshow(image_data, cmap='gray')\n    \n#     # Extract the label and coordinates from the DataFrame\n#     condition = label_data['condition']\n#     level = label_data['level']\n#     x, y = label_data['x'], label_data['y']\n    \n#     # Plot a small circle around the (x, y) coordinates\n#     circle = plt.Circle((x, y), radius=15, color='red', fill=False, lw=2)\n#     plt.gca().add_patch(circle)\n    \n#     # Add a label on top of the image for reference\n#     #plt.text(x + 12, y, condition, color='red', fontsize=12, backgroundcolor='white')\n    \n#     # Set the title with StudyID, SeriesID, InstanceNumber, Condition, and Level\n#     plt.title(f\"StudyID: {study_id}, SeriesID: {series_id}, InstanceNumber: {dicom_image.InstanceNumber}\\n\"\n#               f\"Condition: {condition}, Level: {level}\")\n    \n#     # Show the image\n#     plt.axis('off')  # Remove axes for a clean look\n#     plt.show()\n\n# # Example usage\n# # Extract study_id and series_id from directory manually\n# def load_mri(study_id,series_id):\n#     directory = f\"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/{study_id}/{series_id}/\"  # Replace with actual DICOM directory\n#     dicom_images_with_labels = load_dicom_images_with_labels(directory, label, study_id, series_id)\n\n# # Visualize the DICOM images with condition labels and circles\n#     for dicom_image, label_data in dicom_images_with_labels:\n#         display_image_with_labels(dicom_image, label_data, study_id, series_id)\n# study_id = 1117361192  # Replace with actual study ID from the folder name\n# series_id = 1222187318  # Replace with actual series ID from the folder name\n# load_mri(1117361192,1222187318)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:08:23.349625Z","iopub.execute_input":"2024-10-22T11:08:23.350077Z","iopub.status.idle":"2024-10-22T11:08:25.316348Z","shell.execute_reply.started":"2024-10-22T11:08:23.350037Z","shell.execute_reply":"2024-10-22T11:08:25.315248Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label[(label.study_id == 100206310)&(label.series_id ==1792451510)]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:12:53.603569Z","iopub.execute_input":"2024-10-22T11:12:53.603977Z","iopub.status.idle":"2024-10-22T11:12:53.620820Z","shell.execute_reply.started":"2024-10-22T11:12:53.603939Z","shell.execute_reply":"2024-10-22T11:12:53.619518Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"study_id = 100206310  # Replace with actual study ID from the folder name\nseries_id = 1792451510  # Replace with actual series ID from the folder name","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:36:41.020387Z","iopub.execute_input":"2024-10-22T11:36:41.020784Z","iopub.status.idle":"2024-10-22T11:36:41.026026Z","shell.execute_reply.started":"2024-10-22T11:36:41.020749Z","shell.execute_reply":"2024-10-22T11:36:41.024866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dicom_images_with_labels(directory, df, study_id, series_id):\n    dicom_images = {}\n    \n    # Iterate over files in the directory\n    for filename in os.listdir(directory):\n        if filename.endswith(\".dcm\"):\n            filepath = os.path.join(directory, filename)\n            dicom_image = pydicom.dcmread(filepath)\n            \n            # Get the InstanceNumber from the DICOM file\n            instance_number = dicom_image.InstanceNumber\n            \n            # Find matching rows in DataFrame\n            matching_rows = df[(df['study_id'] == int(study_id)) & \n                               (df['series_id'] == int(series_id)) &\n                               (df['instance_number'] == int(instance_number))]\n            \n            # If there are matching rows, store the image and all its corresponding label data\n            if not matching_rows.empty:\n                # Store the image and its associated label rows in a dictionary by instance_number\n                dicom_images[instance_number] = (dicom_image, matching_rows)\n    \n    return dicom_images\n\n# Function to display the image with all labels on it\nimport matplotlib.patches as patches\n\ndef display_image_with_labels(dicom_image, label_data, study_id, series_id):\n    # Get the pixel array from the DICOM image\n    image_data = dicom_image.pixel_array\n    \n    # Plot the image\n    plt.imshow(image_data, cmap='gray')\n    \n    # Define rectangle dimensions (for example, 30x30 pixels)\n    rect_width = 100\n    rect_height = 50\n    \n    # Check if label_data is a Series (single row) or DataFrame (multiple rows)\n    if isinstance(label_data, pd.Series):\n        # If it's a Series, we handle it as a single row\n        condition = label_data['condition']\n        level = label_data['level']\n        x, y = label_data['x'], label_data['y']\n        \n        # Plot a rectangle around the (x, y) coordinates\n        rectangle = patches.Rectangle((x - rect_width / 2, y - rect_height / 2), \n                                      rect_width, rect_height, linewidth=1, \n                                      edgecolor='red', facecolor='none')\n        plt.gca().add_patch(rectangle)\n        \n        # Add the condition text near the rectangle\n        plt.text(x + rect_width / 2 + 5, y, f\"{level}\", color='red', fontsize=10)\n    \n    else:\n        # If it's a DataFrame, iterate through all rows and plot them\n        for _, row in label_data.iterrows():\n            # Extract the label and coordinates from the DataFrame\n            condition = row['condition']\n            level = row['level']\n            x, y = row['x'], row['y']\n            \n            # Plot a rectangle around the (x, y) coordinates\n            rectangle = patches.Rectangle((x - rect_width / 2, y - rect_height / 2), \n                                          rect_width, rect_height, linewidth=1, \n                                          edgecolor='red', facecolor='none')\n            plt.gca().add_patch(rectangle)\n            \n            # Add the condition text near the rectangle\n            plt.text(x + rect_width / 2 + 5, y, f\"{level}\", color='red', fontsize=10)\n    \n    # Set the title with StudyID, SeriesID, and InstanceNumber\n    plt.title(f\"StudyID: {study_id}, SeriesID: {series_id}, InstanceNumber: {dicom_image.InstanceNumber}, Condition: {condition}\")\n    \n    # Show the image\n    plt.axis('off')  # Remove axes for a clean look\n    plt.show()\n\n\ndef load_mri(study_id,series_id):\n    directory = f\"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/{study_id}/{series_id}/\"  # Replace with actual DICOM directory\n    \n    # Load DICOM images and corresponding labels for the given study and series\n    dicom_images_with_labels = load_dicom_images_with_labels(directory, label, study_id, series_id)\n\n    for instance_number, (dicom_image, label_data) in dicom_images_with_labels.items():\n        display_image_with_labels(dicom_image, label_data, study_id, series_id)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:50:23.599260Z","iopub.execute_input":"2024-10-22T11:50:23.599651Z","iopub.status.idle":"2024-10-22T11:50:23.617216Z","shell.execute_reply.started":"2024-10-22T11:50:23.599615Z","shell.execute_reply":"2024-10-22T11:50:23.615636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"load_mri(1117361192,1222187318)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-22T11:50:23.984101Z","iopub.execute_input":"2024-10-22T11:50:23.984957Z","iopub.status.idle":"2024-10-22T11:50:24.912172Z","shell.execute_reply.started":"2024-10-22T11:50:23.984912Z","shell.execute_reply":"2024-10-22T11:50:24.910972Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}