{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":99552,"databundleVersionId":13190393,"sourceType":"competition"}],"dockerImageVersionId":31089,"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\nimport pydicom\nimport nibabel as nib\nimport matplotlib.pyplot as plt\nimport glob\nimport random","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:45:15.851128Z","iopub.execute_input":"2025-07-29T19:45:15.85143Z","iopub.status.idle":"2025-07-29T19:45:15.85645Z","shell.execute_reply.started":"2025-07-29T19:45:15.851408Z","shell.execute_reply":"2025-07-29T19:45:15.855638Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"input_dir = \"/kaggle/input/rsna-intracranial-aneurysm-detection\"\nimage_dir = \"/kaggle/input/rsna-intracranial-aneurysm-detection/segmentations/\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:04.943178Z","iopub.execute_input":"2025-07-29T18:45:04.943498Z","iopub.status.idle":"2025-07-29T18:45:04.948639Z","shell.execute_reply.started":"2025-07-29T18:45:04.943476Z","shell.execute_reply":"2025-07-29T18:45:04.947568Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_files =os.listdir(image_dir)\nprint(len(image_files))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:05.522653Z","iopub.execute_input":"2025-07-29T18:45:05.522989Z","iopub.status.idle":"2025-07-29T18:45:05.546638Z","shell.execute_reply.started":"2025-07-29T18:45:05.522964Z","shell.execute_reply":"2025-07-29T18:45:05.545636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"files = os.listdir(input_dir)\n\nfor file in files:\n    print(file)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:06.110474Z","iopub.execute_input":"2025-07-29T18:45:06.11085Z","iopub.status.idle":"2025-07-29T18:45:06.116771Z","shell.execute_reply.started":"2025-07-29T18:45:06.110818Z","shell.execute_reply":"2025-07-29T18:45:06.115835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv(input_dir + \"/train.csv\")\nprint(train_df.shape)\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:06.711118Z","iopub.execute_input":"2025-07-29T18:45:06.711586Z","iopub.status.idle":"2025-07-29T18:45:06.793186Z","shell.execute_reply.started":"2025-07-29T18:45:06.711538Z","shell.execute_reply":"2025-07-29T18:45:06.792018Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:07.337269Z","iopub.execute_input":"2025-07-29T18:45:07.338029Z","iopub.status.idle":"2025-07-29T18:45:07.364507Z","shell.execute_reply.started":"2025-07-29T18:45:07.337998Z","shell.execute_reply":"2025-07-29T18:45:07.363433Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_df.describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:08.050753Z","iopub.execute_input":"2025-07-29T18:45:08.051171Z","iopub.status.idle":"2025-07-29T18:45:08.096453Z","shell.execute_reply.started":"2025-07-29T18:45:08.051141Z","shell.execute_reply":"2025-07-29T18:45:08.095353Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_loc_df = pd.read_csv(input_dir + \"/train_localizers.csv\")\nprint(train_loc_df.shape)\ntrain_loc_df.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:19.048323Z","iopub.execute_input":"2025-07-29T18:45:19.048678Z","iopub.status.idle":"2025-07-29T18:45:19.086929Z","shell.execute_reply.started":"2025-07-29T18:45:19.04865Z","shell.execute_reply":"2025-07-29T18:45:19.086032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_loc_df.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:19.714573Z","iopub.execute_input":"2025-07-29T18:45:19.7156Z","iopub.status.idle":"2025-07-29T18:45:19.727452Z","shell.execute_reply.started":"2025-07-29T18:45:19.715554Z","shell.execute_reply":"2025-07-29T18:45:19.726243Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_loc_df.describe())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:20.317068Z","iopub.execute_input":"2025-07-29T18:45:20.317415Z","iopub.status.idle":"2025-07-29T18:45:20.337736Z","shell.execute_reply.started":"2025-07-29T18:45:20.317391Z","shell.execute_reply":"2025-07-29T18:45:20.33664Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Select the last 14 columns (assuming they are the label/object columns)\nlabel_columns = train_df.columns[-14:]\n\n# Count how many times each label is present (i.e., sum the 1s per column)\nlabel_counts = train_df[label_columns].sum().sort_values(ascending=False)\n\n# Print the counts\nprint(\"Object presence counts:\")\nprint(label_counts)\n\n# Plot a bar chart\nplt.figure(figsize=(12, 6))\nlabel_counts.plot(kind='bar', color='skyblue', edgecolor='black')\nplt.title(\"Frequency of Each Object Label in Training Data\")\nplt.xlabel(\"Object Label\")\nplt.ylabel(\"Count (Presence = 1)\")\nplt.xticks(rotation=45)\nplt.tight_layout()\nplt.grid(axis='y', linestyle='--', alpha=0.7)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:20.892443Z","iopub.execute_input":"2025-07-29T18:45:20.892808Z","iopub.status.idle":"2025-07-29T18:45:21.377254Z","shell.execute_reply.started":"2025-07-29T18:45:20.892777Z","shell.execute_reply":"2025-07-29T18:45:21.376084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"object_counts = train_loc_df['location'].value_counts()\n\n# Print the frequency counts\nprint(\"Frequency of each unique object in 'location':\")\nprint(object_counts)\n\n# Plot a bar chart of the frequency counts\nplt.figure(figsize=(12, 6))\nobject_counts.plot(kind='bar', color='cornflowerblue', edgecolor='black')\nplt.title(\"Frequency of Unique Objects in location\")\nplt.xlabel(\"location\")\nplt.ylabel(\"Frequency\")\nplt.xticks(rotation=45, ha='right')  # Rotate x-axis labels for readability\nplt.tight_layout()  # Adjust layout to ensure everything fits without overlap\nplt.grid(axis='y', linestyle='--', alpha=0.7)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:45:28.578498Z","iopub.execute_input":"2025-07-29T18:45:28.578887Z","iopub.status.idle":"2025-07-29T18:45:28.929983Z","shell.execute_reply.started":"2025-07-29T18:45:28.57886Z","shell.execute_reply":"2025-07-29T18:45:28.928953Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dicom_series(series_path):\n    dicoms = []\n    for fname in sorted(os.listdir(series_path)):\n        if fname.endswith('.dcm'):\n            dcm = pydicom.dcmread(os.path.join(series_path, fname))\n            dicoms.append(dcm)\n    dicoms.sort(key=lambda x: float(x.ImagePositionPatient[2]))  # Sort by slice location\n    images = np.stack([d.pixel_array for d in dicoms])\n    sop_uids = [d.SOPInstanceUID for d in dicoms]\n    return images, sop_uids, dicoms\n\ndef load_nii_seg(seg_path):\n    nii = nib.load(seg_path)\n    data = nii.get_fdata()\n    return data.astype(np.uint8)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T18:46:15.49438Z","iopub.execute_input":"2025-07-29T18:46:15.494723Z","iopub.status.idle":"2025-07-29T18:46:15.502104Z","shell.execute_reply.started":"2025-07-29T18:46:15.494698Z","shell.execute_reply":"2025-07-29T18:46:15.500908Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def show_slice(dcm_slice, seg_slice, overlay=False):\n    plt.figure(figsize=(12, 4))\n    \n    # DICOM\n    plt.subplot(1, 3, 1)\n    plt.imshow(dcm_slice, cmap='gray')\n    plt.title(\"DICOM Slice\")\n    \n    # Segmentation\n    if seg_slice is not None:\n        plt.subplot(1, 3, 2)\n        plt.imshow(seg_slice, cmap='gray')\n        plt.title(\"Segmentation Slice\")\n        \n        # Overlay\n        if overlay:\n            plt.subplot(1, 3, 3)\n            plt.imshow(dcm_slice, cmap='gray')\n            plt.imshow(seg_slice, cmap='Reds', alpha=0.4)\n            plt.title(\"Overlay\")\n    \n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:38:14.718182Z","iopub.execute_input":"2025-07-29T19:38:14.719238Z","iopub.status.idle":"2025-07-29T19:38:14.725811Z","shell.execute_reply.started":"2025-07-29T19:38:14.719208Z","shell.execute_reply":"2025-07-29T19:38:14.724862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Example paths\nseries_id = train_loc_df.SeriesInstanceUID[0]\t\nsop_uid_target = train_loc_df.SOPInstanceUID[0]\nprint(series_id, sop_uid_target)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:38:15.588184Z","iopub.execute_input":"2025-07-29T19:38:15.588518Z","iopub.status.idle":"2025-07-29T19:38:15.594242Z","shell.execute_reply.started":"2025-07-29T19:38:15.588493Z","shell.execute_reply":"2025-07-29T19:38:15.59315Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"series_path = f'{input_dir}/series/{series_id}'\nseg_path = f'{input_dir}/segmentations/{sop_uid_target}/{sop_uid_target}.nii'  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:38:20.549539Z","iopub.execute_input":"2025-07-29T19:38:20.549916Z","iopub.status.idle":"2025-07-29T19:38:20.555166Z","shell.execute_reply.started":"2025-07-29T19:38:20.549884Z","shell.execute_reply":"2025-07-29T19:38:20.554131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load data\ndcm_images, sop_uids, dicoms = load_dicom_series(series_path)\nseg_volume = load_nii_seg(seg_nii_list[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:38:23.362795Z","iopub.execute_input":"2025-07-29T19:38:23.363103Z","iopub.status.idle":"2025-07-29T19:38:27.479831Z","shell.execute_reply.started":"2025-07-29T19:38:23.363083Z","shell.execute_reply":"2025-07-29T19:38:27.478874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Find the matching slice index\nslice_idx = sop_uids.index(sop_uid_target)\nprint(f\"Matching slice index: {slice_idx}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:38:30.493013Z","iopub.execute_input":"2025-07-29T19:38:30.493307Z","iopub.status.idle":"2025-07-29T19:38:30.499257Z","shell.execute_reply.started":"2025-07-29T19:38:30.493287Z","shell.execute_reply":"2025-07-29T19:38:30.498183Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Get slices\ndcm_slice = dcm_images[slice_idx]\nseg_slice = seg_volume[slice_idx]  # Assuming same depth alignment\nprint(dcm_slice.shape, seg_slice.shape)\n\n# Plot\nshow_slice(dcm_slice, seg_slice, overlay=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:38:33.420982Z","iopub.execute_input":"2025-07-29T19:38:33.4213Z","iopub.status.idle":"2025-07-29T19:38:33.93198Z","shell.execute_reply.started":"2025-07-29T19:38:33.42128Z","shell.execute_reply":"2025-07-29T19:38:33.931054Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"seg_nii_list = glob.glob(f'{input_dir}/segmentations/*/*.nii')\nprint(len(seg_nii_list))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:27:18.119888Z","iopub.execute_input":"2025-07-29T19:27:18.120179Z","iopub.status.idle":"2025-07-29T19:27:18.289371Z","shell.execute_reply.started":"2025-07-29T19:27:18.120158Z","shell.execute_reply":"2025-07-29T19:27:18.288328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"nii_seg = load_nii_seg(seg_nii_list[0])\nprint(nii_seg.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:29:56.984806Z","iopub.execute_input":"2025-07-29T19:29:56.985082Z","iopub.status.idle":"2025-07-29T19:29:57.015995Z","shell.execute_reply.started":"2025-07-29T19:29:56.985063Z","shell.execute_reply":"2025-07-29T19:29:57.015012Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_random_slices(nii_path, num_slices=25):\n    # Load the NIfTI image\n    nii_img = nib.load(nii_path)\n    data = nii_img.get_fdata()\n    \n    # Ensure it's a 3D volume\n    if data.ndim != 3:\n        raise ValueError(\"Input NIfTI image is not 3D.\")\n\n    # Get the number of slices along the z-axis\n    total_slices = data.shape[2]\n\n    # Choose random slice indices\n    random_indices = random.sample(range(total_slices), min(num_slices, total_slices))\n    random_indices.sort()  # Optional: sort to display slices in order\n\n    # Plot the slices\n    fig, axes = plt.subplots(1, len(random_indices), figsize=(20, 5))\n    for i, idx in enumerate(random_indices):\n        axes[i].imshow(data[:, :, idx], cmap='gray')\n        axes[i].set_title(f\"Slice {idx}\")\n        axes[i].axis('off')\n\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:48:55.377479Z","iopub.execute_input":"2025-07-29T19:48:55.377872Z","iopub.status.idle":"2025-07-29T19:48:55.38622Z","shell.execute_reply.started":"2025-07-29T19:48:55.377843Z","shell.execute_reply":"2025-07-29T19:48:55.385201Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_random_slices(seg_nii_list[1])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-29T19:49:21.425331Z","iopub.execute_input":"2025-07-29T19:49:21.426165Z","iopub.status.idle":"2025-07-29T19:49:23.146027Z","shell.execute_reply.started":"2025-07-29T19:49:21.426129Z","shell.execute_reply":"2025-07-29T19:49:23.145059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}