{"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":"code","source":"pip install pydicom","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\n\ndef load_dicom_series(directory):\n    # Load DICOM files from the specified directory\n    dicom_files = []\n    for root, _, files in os.walk(directory):\n        for file in files:\n            if file.endswith(\".dcm\"):\n                dicom_files.append(os.path.join(root, file))\n   \n    # Read DICOM images and sort them based on slice position\n    slices = []\n    for dicom_file in dicom_files:\n        ds = pydicom.dcmread(dicom_file)\n        slices.append(ds)\n    slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))\n   \n    return slices\n\ndef create_dicom_stack(directory, num_images):\n    # Load DICOM series\n    slices = load_dicom_series(directory)\n\n    # Get pixel data and voxel spacing from DICOM slices\n    pixel_array = np.stack([slice.pixel_array for slice in slices[:num_images]])\n    \n    # Convert MultiValue attribute to list\n    pixel_spacing = list(slices[0].PixelSpacing)\n    \n    # Get the single SliceThickness value and convert to a list\n    slice_thickness = [slices[0].SliceThickness]\n    \n    # Create the voxel spacing list by concatenating pixel spacing and slice thickness\n    voxel_spacing = pixel_spacing + slice_thickness\n    \n    # Create 3D volume\n    volume = np.zeros((num_images, pixel_array.shape[1], pixel_array.shape[2]), dtype=np.float32)\n    for i, slice in enumerate(slices[:num_images]):\n        volume[i] = slice.pixel_array\n    \n    return volume, voxel_spacing\n\n\n# Specify the parent directory containing the folders for each FLAIR image set\nparent_directory = \"/kaggle/input/rsna-miccai-brain-tumor-radiogenomic-classification/train/\"\n\n# Create a folder to save the 3D volumes\noutput_parent_folder = \"/kaggle/working/3d_volumes/\"\nos.makedirs(output_parent_folder, exist_ok=True)\n\n# Process each folder\ncount = 0\nfor folder_name in os.listdir(parent_directory):\n    folder_path = os.path.join(parent_directory, folder_name)\n    \n    # Check if the item in the parent directory is a directory and contains T2w images\n    if os.path.isdir(folder_path) and \"T2w\" in os.listdir(folder_path):\n        # Construct the directory path for T2w images\n        directory_path = os.path.join(folder_path, \"T2w\")\n        \n        # Call the function to create the DICOM stack with the first 30 images\n        dicom_stack, voxel_spacing = create_dicom_stack(directory_path, num_images=45)\n        \n        # Generate the output folder path using the parent directory structure\n        output_folder = os.path.join(output_parent_folder, folder_name)\n        os.makedirs(output_folder, exist_ok=True)\n        \n        # Generate the output file name using the folder name\n        output_file = os.path.join(output_folder, f\"{folder_name}_3d_volume.npy\")\n        \n        # Save the 3D volume as a Numpy array\n        np.save(output_file, dicom_stack)\n        \n        # Print confirmation message\n        print(count)\n        print(\"3D volume saved successfully at:\", output_file)\n        count += 1\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00513/00513_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Display the slices of the 3D volume\nfig, axes = plt.subplots(nrows=5, ncols=9, figsize=(12, 10))\n\nfor i, ax in enumerate(axes.flat):\n    ax.imshow(volume[i], cmap='gray')\n    ax.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00404/00404_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Display the slices of the 3D volume\nfig, axes = plt.subplots(nrows=5, ncols=9, figsize=(12, 10))\n\nfor i, ax in enumerate(axes.flat):\n    ax.imshow(volume[i], cmap='gray')\n    ax.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Specify the path to the folder containing the 3D volumes\nfolder_path = \"/kaggle/working/3d_volumes/\"\n\n# Get a list of all files in the folder\nvolume_files = [file for file in os.listdir(folder_path) if file.endswith(\".npy\")]\n\n# Visualize each 3D volume\nfor volume_file in volume_files:\n    # Load the 3D volume from the Numpy array\n    volume = np.load(os.path.join(folder_path, volume_file))\n\n    # Create a 3D plot\n    fig = plt.figure(figsize=(8, 8))\n    ax = fig.add_subplot(111, projection='3d')\n\n    # Set the x, y, z coordinates for plotting\n    z, y, x = volume.nonzero()\n\n    # Plot the 3D volume\n    ax.scatter(x, y, z, c=volume[z, y, x], cmap='gray')\n\n    # Set axis labels\n    ax.set_xlabel(\"X\")\n    ax.set_ylabel(\"Y\")\n    ax.set_zlabel(\"Z\")\n\n    # Set plot title as the volume file name\n    ax.set_title(volume_file)\n\n    # Show the plot\n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00404/00404_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Select a slice to display (e.g., middle slice)\nslice_index = volume.shape[0] // 2\n\n# Plot the 3D volume slice\nplt.imshow(volume[slice_index], cmap='gray')\nplt.axis('off')\nplt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00404/00404_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Create a 3D figure\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(111, projection='3d')\n\n# Generate 3D coordinates\nx, y, z = volume.nonzero()\n\n# Plot the 3D volume\nax.scatter(x, y, z, c=volume[x, y, z], cmap='gray')\n\n# Set axis labels\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\n\nplt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00404/00404_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Create a 3D figure\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(111, projection='3d')\n\n# Generate 3D coordinates\nx, y, z = volume.nonzero()\n\n# Plot the 3D volume\nscatter = ax.scatter(x, y, z, c=volume[x, y, z], cmap='gray')\n\n# Set axis labels\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\n\n# Set initial view\nax.view_init(elev=30, azim=45)\n\ndef update_view(elev, azim):\n    ax.view_init(elev=elev, azim=azim)\n\n# Create an interactive slider for rotation\nplt.subplots_adjust(left=0.25, bottom=0.25)\naxcolor = 'lightgoldenrodyellow'\nax_elev = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)\nax_azim = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)\n\nslider_elev = plt.Slider(ax_elev, 'Elevation', -90, 90, valinit=30)\nslider_azim = plt.Slider(ax_azim, 'Azimuth', -180, 180, valinit=45)\n\ndef update_rotation(val):\n    elev = slider_elev.val\n    azim = slider_azim.val\n    update_view(elev, azim)\n    fig.canvas.draw_idle()\n\nslider_elev.on_changed(update_rotation)\nslider_azim.on_changed(update_rotation)\n\nplt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install ipyvolume\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00404/00404_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Create a 3D figure\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(111, projection='3d')\n\n# Generate 3D coordinates\nx, y, z = volume.nonzero()\n\n# Plot the 3D volume\nscatter = ax.scatter(x, y, z, c=volume[x, y, z], cmap='gray')\n\n# Set axis labels\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\n\ndef update_rotation(elev, azim):\n    ax.view_init(elev=elev, azim=azim)\n    fig.canvas.draw()\n\n# Create an interactive rotation function\ndef rotate(event):\n    ax.elev += event.x\n    ax.azim += event.y\n    fig.canvas.draw()\n\n# Connect the rotation function to the mouse movement event\nfig.canvas.mpl_connect('motion_notify_event', rotate)\n\n# Show the 3D plot\nplt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.animation import FuncAnimation\n\n# Specify the path to the 3D volume file\nvolume_file = \"/kaggle/working/3d_volumes/00404/00404_3d_volume.npy\"\n\n# Load the 3D volume as a Numpy array\nvolume = np.load(volume_file)\n\n# Create a 3D figure\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(111, projection='3d')\n\n# Generate 3D coordinates\nx, y, z = volume.nonzero()\n\n# Plot the 3D volume\nscatter = ax.scatter(x, y, z, c=volume[x, y, z], cmap='gray')\n\n# Set axis labels\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\n\n# Store initial view angles\ninitial_elev = ax.elev\ninitial_azim = ax.azim\n\n# Create an interactive rotation function\ndef rotate(elev, azim):\n    ax.view_init(elev=elev, azim=azim)\n\n# Update function for animation\ndef update(frame):\n    angle = frame * 4\n    elev = np.sin(np.radians(angle)) * 30 + initial_elev\n    azim = angle + initial_azim\n    rotate(elev, azim)\n    return scatter,\n\n# Create the animation\nanimation = FuncAnimation(fig, update, frames=np.linspace(0, 90, 100), interval=50, blit=True)\n\n# Show the 3D plot\nplt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}