{"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":13851420,"sourceType":"competition"}],"dockerImageVersionId":31153,"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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\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":"2025-10-30T19:16:30.590093Z","iopub.execute_input":"2025-10-30T19:16:30.590313Z","iopub.status.idle":"2025-10-30T19:16:32.619119Z","shell.execute_reply.started":"2025-10-30T19:16:30.590291Z","shell.execute_reply":"2025-10-30T19:16:32.617981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom pathlib import Path\nimport shutil, os\n\n# === Step 1. 载入 CSV 文件 ===\ndata_root = Path(\"/kaggle/input/rsna-intracranial-aneurysm-detection\")\ndf = pd.read_csv(data_root / \"train.csv\")\n\n# === Step 2. 筛选 MRI 模态 ===\ndf_mri = df[df[\"Modality\"].str.contains(\"MR\", case=False, na=False)]\n\n# === Step 3. 检查哪些 MRI 有 segmentation 文件 ===\nseg_dir = data_root / \"segmentations\"\nseg_files = {f.stem for f in seg_dir.glob(\"*.nii*\")}\ndf_mri_seg = df_mri[df_mri[\"SeriesInstanceUID\"].isin(seg_files)]\n\nprint(f\"Found {len(df_mri_seg)} MRI cases with segmentation available.\")\ndf_mri_seg.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:18:30.941656Z","iopub.execute_input":"2025-10-30T19:18:30.942087Z","iopub.status.idle":"2025-10-30T19:18:31.213337Z","shell.execute_reply.started":"2025-10-30T19:18:30.942052Z","shell.execute_reply":"2025-10-30T19:18:31.212459Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\nimport nibabel as nib\nimport matplotlib.pyplot as plt\nfrom glob import glob\nDATA_DIR = \"/kaggle/input/rsna-intracranial-aneurysm-detection\"\nSERIES_DIR = f\"{DATA_DIR}/series\"\nSEG_DIR = f\"{DATA_DIR}/segmentations\"\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:42:55.176754Z","iopub.execute_input":"2025-10-30T19:42:55.177073Z","iopub.status.idle":"2025-10-30T19:42:55.182026Z","shell.execute_reply.started":"2025-10-30T19:42:55.177051Z","shell.execute_reply":"2025-10-30T19:42:55.180987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls /kaggle/input/rsna-intracranial-aneurysm-detection","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:43:57.062473Z","iopub.execute_input":"2025-10-30T19:43:57.062803Z","iopub.status.idle":"2025-10-30T19:43:57.20695Z","shell.execute_reply.started":"2025-10-30T19:43:57.062762Z","shell.execute_reply":"2025-10-30T19:43:57.205751Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls /kaggle/input/rsna-intracranial-aneurysm-detection/segmentations | head\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:44:17.217958Z","iopub.execute_input":"2025-10-30T19:44:17.218261Z","iopub.status.idle":"2025-10-30T19:44:17.354128Z","shell.execute_reply.started":"2025-10-30T19:44:17.218237Z","shell.execute_reply":"2025-10-30T19:44:17.352987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"nii_files = sorted(glob(os.path.join(SEG_DIR, \"*.nii\")))\n# 匹配 MRI 和 segmentation 对\npairs = []\nfor f in nii_files:\n    if f.endswith(\"_cowseg.nii\"):\n        base = f.replace(\"_cowseg.nii\", \".nii\")\n        if os.path.exists(base):\n            pairs.append((base, f))\n\nprint(f\"Found {len(pairs)} paired MRI & segmentation files.\")\nif pairs:\n    print(\"Example pair:\\n\", pairs[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:47:39.43274Z","iopub.execute_input":"2025-10-30T19:47:39.433611Z","iopub.status.idle":"2025-10-30T19:47:39.740092Z","shell.execute_reply.started":"2025-10-30T19:47:39.433581Z","shell.execute_reply":"2025-10-30T19:47:39.739039Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 选一个 pair\nmri_path, seg_path = pairs[0]\n\n# 读取 MRI 和 segmentation\nmri_img = nib.load(mri_path)\nseg_img = nib.load(seg_path)\n\nmri_data = mri_img.get_fdata()\nseg_data = seg_img.get_fdata()\n\nprint(\"MRI shape:\", mri_data.shape)\nprint(\"Segmentation shape:\", seg_data.shape)\nprint(\"Segmentation unique labels:\", np.unique(seg_data))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:47:58.200581Z","iopub.execute_input":"2025-10-30T19:47:58.200933Z","iopub.status.idle":"2025-10-30T19:48:06.864678Z","shell.execute_reply.started":"2025-10-30T19:47:58.200908Z","shell.execute_reply":"2025-10-30T19:48:06.863716Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def show_overlay(slice_idx):\n    plt.figure(figsize=(10,4))\n    plt.subplot(1,2,1)\n    plt.imshow(mri_data[:,:,slice_idx], cmap='gray')\n    plt.title(f\"MRI Slice {slice_idx}\")\n    plt.axis('off')\n\n    plt.subplot(1,2,2)\n    plt.imshow(mri_data[:,:,slice_idx], cmap='gray')\n    plt.imshow(seg_data[:,:,slice_idx], cmap='autumn', alpha=0.4)\n    plt.title(f\"Overlay Slice {slice_idx}\")\n    plt.axis('off')\n    plt.show()\n\n# 展示几层\nfor i in [1, 50, 80]:\n    show_overlay(i)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T20:15:09.712838Z","iopub.execute_input":"2025-10-30T20:15:09.713478Z","iopub.status.idle":"2025-10-30T20:15:10.975919Z","shell.execute_reply.started":"2025-10-30T20:15:09.713428Z","shell.execute_reply":"2025-10-30T20:15:10.974944Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"nonzero_ratio = np.count_nonzero(seg_data) / seg_data.size\nprint(f\"Non-zero voxel ratio: {nonzero_ratio:.6f}\")\n\nunique_vals, counts = np.unique(seg_data, return_counts=True)\nfor u, c in zip(unique_vals, counts):\n    if u != 0:\n        print(f\"Label {int(u):2d}: {c} voxels\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T19:59:22.271317Z","iopub.execute_input":"2025-10-30T19:59:22.271979Z","iopub.status.idle":"2025-10-30T19:59:26.114056Z","shell.execute_reply.started":"2025-10-30T19:59:22.271949Z","shell.execute_reply":"2025-10-30T19:59:26.112975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"summary = []\nfor mri_path, seg_path in pairs:\n    seg_data = nib.load(seg_path).get_fdata()\n    nonzero = np.count_nonzero(seg_data) / seg_data.size\n    labels = np.unique(seg_data)\n    summary.append((os.path.basename(seg_path), seg_data.shape, nonzero, labels))\n\nprint(\"Example results:\")\nfor name, shape, nonzero, labels in summary[:5]:\n    print(f\"{name:80s}  shape={shape}, nonzero_ratio={nonzero:.6f}, labels={labels}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-30T20:00:44.560178Z","iopub.execute_input":"2025-10-30T20:00:44.56049Z","iopub.status.idle":"2025-10-30T20:15:09.706315Z","shell.execute_reply.started":"2025-10-30T20:00:44.560469Z","shell.execute_reply":"2025-10-30T20:15:09.703083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}