{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":91249,"databundleVersionId":11294684,"sourceType":"competition"}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport numpy as np\nimport imageio.v2 as imageio\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import Normalize\n\n# Define paths and load data\nfolder_path = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025/train/tomo_00e047\"\noutput_path = \"/kaggle/working/\" \n\nslice_files = sorted([file for file in os.listdir(folder_path) if file.endswith('.jpg')])\nprint(f\"Found {len(slice_files)} slice files\")\n\ntemp_dir = os.path.join(output_path, \"temp_frames\")\nos.makedirs(temp_dir, exist_ok=True)\n\ndef create_multiview_animation():\n        \n    sample_indices = list(range(0, len(slice_files), 4))  # Take every 4th slice\n    \n    print(f\"Loading {len(sample_indices)} slices...\")\n    slices = [imageio.imread(os.path.join(folder_path, slice_files[i])) for i in sample_indices]\n    volume = np.stack(slices, axis=0)\n    \n    volume = (volume - np.min(volume)) / (np.max(volume) - np.min(volume))\n    \n    print(f\"Volume shape: {volume.shape}\")\n    \n    frame_files = []\n    num_frames = min(30, volume.shape[0])  # Limit number of frames\n    \n    for i in range(num_frames):\n        # Calculate positions for slices (move through the volume)\n        z_pos = int((i / num_frames) * volume.shape[0])\n        y_pos = int(volume.shape[1] / 2)\n        x_pos = int(volume.shape[2] / 2)\n        \n        # Create a figure with 3 subplots for different views\n        fig, axes = plt.subplots(1, 3, figsize=(15, 5))\n        \n        # XY plane (top-down view)\n        axes[0].imshow(volume[z_pos], cmap='gray')\n        axes[0].set_title(f\"XY Plane (z={z_pos})\")\n        axes[0].axhline(y=y_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[0].axvline(x=x_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # XZ plane (side view)\n        axes[1].imshow(volume[:, y_pos, :], cmap='gray')\n        axes[1].set_title(f\"XZ Plane (y={y_pos})\")\n        axes[1].axhline(y=z_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[1].axvline(x=x_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # YZ plane (front view)\n        axes[2].imshow(volume[:, :, x_pos], cmap='gray')\n        axes[2].set_title(f\"YZ Plane (x={x_pos})\")\n        axes[2].axhline(y=z_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[2].axvline(x=y_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # Remove ticks\n        for ax in axes:\n            ax.set_xticks([])\n            ax.set_yticks([])\n        \n        plt.tight_layout()\n        \n        # Save the frame\n        frame_file = os.path.join(temp_dir, f\"multiview_{i:03d}.png\")\n        plt.savefig(frame_file, dpi=100)\n        plt.close(fig)\n        \n        frame_files.append(frame_file)\n    \n    # Create a GIF from the frames\n    print(\"Creating GIF...\")\n    frames = [imageio.imread(f) for f in frame_files]\n    gif_path = os.path.join(output_path, \"multiview_raw.gif\")\n    imageio.mimsave(gif_path, frames, duration=0.2)\n \n    return gif_path\n\nmultiview_path = create_multiview_animation()\n\n# Clean up temp files\nprint(\"Cleaning up temporary files...\")\nfor file in os.listdir(temp_dir):\n    os.remove(os.path.join(temp_dir, file))\nos.rmdir(temp_dir)\n\nprint(\"Process complete!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-21T16:26:14.205168Z","iopub.execute_input":"2025-03-21T16:26:14.205487Z","iopub.status.idle":"2025-03-21T16:26:31.443363Z","shell.execute_reply.started":"2025-03-21T16:26:14.205463Z","shell.execute_reply":"2025-03-21T16:26:31.442346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport imageio.v2 as imageio\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import Normalize\nfrom scipy import signal  # Added import for signal.convolve2d\n\n# Define paths and load data\nfolder_path = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025/train/tomo_00e047\"\noutput_path = \"/kaggle/working/\" \nslice_files = sorted([file for file in os.listdir(folder_path) if file.endswith('.jpg')])\nprint(f\"Found {len(slice_files)} slice files\")\ntemp_dir = os.path.join(output_path, \"temp_frames\")\nos.makedirs(temp_dir, exist_ok=True)\n\ndef wiener_filter(img, kernel_size=11, noise_power=0.02):\n    \"\"\"\n    Apply Wiener filter for denoising a grayscale image.\n    \n    Parameters:\n        img: Input grayscale image\n        kernel_size: Size of the kernel (odd number)\n        noise_power: Estimated noise power\n        \n    Returns:\n        Denoised image\n    \"\"\"\n    img_norm = img.astype(np.float32) / 255.0\n    \n    # Create a local mean filter\n    kernel = np.ones((kernel_size, kernel_size)) / (kernel_size**2)\n    \n    # Compute local mean\n    img_mean = signal.convolve2d(img_norm, kernel, mode='same')\n    \n    # Compute local variance\n    img_sqr_mean = signal.convolve2d(img_norm**2, kernel, mode='same')\n    img_var = img_sqr_mean - img_mean**2\n    \n    # Ensure variance is positive\n    img_var = np.maximum(img_var, 0)\n    \n    # Apply Wiener filter formula\n    denoised = img_mean + ((img_var - noise_power) / np.maximum(img_var, noise_power)) * (img_norm - img_mean)\n    \n    denoised = np.clip(denoised, 0, 1)\n    \n    return denoised  # Return as float in [0,1] range to match volume normalization\n\ndef create_multiview_animation():\n        \n    sample_indices = list(range(0, len(slice_files), 4))  # Take every 4th slice\n    \n    print(f\"Loading {len(sample_indices)} slices...\")\n    \n    # Load slices and apply Wiener filter\n    slices = []\n    for i in sample_indices:\n        img = imageio.imread(os.path.join(folder_path, slice_files[i]))\n        # Apply Wiener filter with specified parameters\n        filtered_img = wiener_filter(img, kernel_size=11, noise_power=0.02)\n        slices.append(filtered_img)\n    \n    volume = np.stack(slices, axis=0)\n    \n    # No need to normalize again since wiener_filter already returns values in [0,1]\n    # Just make sure all values are within [0,1] range\n    volume = np.clip(volume, 0, 1)\n    \n    print(f\"Volume shape: {volume.shape}\")\n    \n    frame_files = []\n    num_frames = min(30, volume.shape[0])  # Limit number of frames\n    \n    for i in range(num_frames):\n        # Calculate positions for slices (move through the volume)\n        z_pos = int((i / num_frames) * volume.shape[0])\n        y_pos = int(volume.shape[1] / 2)\n        x_pos = int(volume.shape[2] / 2)\n        \n        # Create a figure with 3 subplots for different views\n        fig, axes = plt.subplots(1, 3, figsize=(15, 5))\n        \n        # XY plane (top-down view)\n        axes[0].imshow(volume[z_pos], cmap='gray')\n        axes[0].set_title(f\"XY Plane (z={z_pos})\")\n        axes[0].axhline(y=y_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[0].axvline(x=x_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # XZ plane (side view)\n        axes[1].imshow(volume[:, y_pos, :], cmap='gray')\n        axes[1].set_title(f\"XZ Plane (y={y_pos})\")\n        axes[1].axhline(y=z_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[1].axvline(x=x_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # YZ plane (front view)\n        axes[2].imshow(volume[:, :, x_pos], cmap='gray')\n        axes[2].set_title(f\"YZ Plane (x={x_pos})\")\n        axes[2].axhline(y=z_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[2].axvline(x=y_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # Remove ticks\n        for ax in axes:\n            ax.set_xticks([])\n            ax.set_yticks([])\n        \n        plt.tight_layout()\n        \n        # Save the frame\n        frame_file = os.path.join(temp_dir, f\"multiview_{i:03d}.png\")\n        plt.savefig(frame_file, dpi=100)\n        plt.close(fig)\n        \n        frame_files.append(frame_file)\n    \n    # Create a GIF from the frames\n    print(\"Creating GIF...\")\n    frames = [imageio.imread(f) for f in frame_files]\n    gif_path = os.path.join(output_path, \"multiview_wiener_.gif\")\n    imageio.mimsave(gif_path, frames, duration=0.2)\n \n    return gif_path\n\nmultiview_path = create_multiview_animation()\n\n# Clean up temp files\nprint(\"Cleaning up temporary files...\")\nfor file in os.listdir(temp_dir):\n    os.remove(os.path.join(temp_dir, file))\nos.rmdir(temp_dir)\nprint(\"Process complete!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-21T16:35:39.561172Z","iopub.execute_input":"2025-03-21T16:35:39.561578Z","iopub.status.idle":"2025-03-21T16:36:44.709777Z","shell.execute_reply.started":"2025-03-21T16:35:39.561552Z","shell.execute_reply":"2025-03-21T16:36:44.708463Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install bm3d\n\nimport os\nimport numpy as np\nimport imageio.v2 as imageio\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import Normalize\nimport bm3d  # Import the BM3D library\n\n# Define paths and load data\nfolder_path = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025/train/tomo_00e047\"\noutput_path = \"/kaggle/working/\" \nslice_files = sorted([file for file in os.listdir(folder_path) if file.endswith('.jpg')])\nprint(f\"Found {len(slice_files)} slice files\")\n\ntemp_dir = os.path.join(output_path, \"temp_frames\")\nos.makedirs(temp_dir, exist_ok=True)\n\ndef create_multiview_animation():\n        \n    sample_indices = list(range(0, len(slice_files), 4))  # Take every 4th slice\n    \n    print(f\"Loading {len(sample_indices)} slices...\")\n    # Load original slices\n    slices = [imageio.imread(os.path.join(folder_path, slice_files[i])) for i in sample_indices]\n    \n    # Convert images to float and normalize to [0, 1] for BM3D processing\n    normalized_slices = []\n    for img in slices:\n        img_float = img.astype(np.float32) / 255.0\n        normalized_slices.append(img_float)\n    \n    # Apply BM3D denoising to each slice\n    print(\"Applying BM3D denoising with sigma_psd=0.15...\")\n    denoised_slices = []\n    for i, img in enumerate(normalized_slices):\n        print(f\"Denoising slice {i+1}/{len(normalized_slices)}...\")\n        denoised_img = bm3d.bm3d(img, sigma_psd=0.15)\n        denoised_slices.append(denoised_img)\n    \n    # Stack slices to create volume\n    volume = np.stack(denoised_slices, axis=0)\n    \n    # Normalize the denoised volume for visualization\n    volume = (volume - np.min(volume)) / (np.max(volume) - np.min(volume))\n    \n    print(f\"Volume shape: {volume.shape}\")\n    \n    frame_files = []\n    num_frames = min(30, volume.shape[0])  # Limit number of frames\n    \n    for i in range(num_frames):\n        # Calculate positions for slices (move through the volume)\n        z_pos = int((i / num_frames) * volume.shape[0])\n        y_pos = int(volume.shape[1] / 2)\n        x_pos = int(volume.shape[2] / 2)\n        \n        # Create a figure with 3 subplots for different views\n        fig, axes = plt.subplots(1, 3, figsize=(15, 5))\n        \n        # XY plane (top-down view)\n        axes[0].imshow(volume[z_pos], cmap='gray')\n        axes[0].set_title(f\"XY Plane (z={z_pos})\")\n        axes[0].axhline(y=y_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[0].axvline(x=x_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # XZ plane (side view)\n        axes[1].imshow(volume[:, y_pos, :], cmap='gray')\n        axes[1].set_title(f\"XZ Plane (y={y_pos})\")\n        axes[1].axhline(y=z_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[1].axvline(x=x_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # YZ plane (front view)\n        axes[2].imshow(volume[:, :, x_pos], cmap='gray')\n        axes[2].set_title(f\"YZ Plane (x={x_pos})\")\n        axes[2].axhline(y=z_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        axes[2].axvline(x=y_pos, color='r', linestyle='-', linewidth=0.5, alpha=0.5)\n        \n        # Remove ticks\n        for ax in axes:\n            ax.set_xticks([])\n            ax.set_yticks([])\n        \n        plt.tight_layout()\n        \n        # Save the frame\n        frame_file = os.path.join(temp_dir, f\"multiview_{i:03d}.png\")\n        plt.savefig(frame_file, dpi=100)\n        plt.close(fig)\n        \n        frame_files.append(frame_file)\n    \n    # Create a GIF from the frames\n    print(\"Creating GIF...\")\n    frames = [imageio.imread(f) for f in frame_files]\n    gif_path = os.path.join(output_path, \"multiview_denoised.gif\")\n    imageio.mimsave(gif_path, frames, duration=0.2)\n \n    return gif_path\n\n# Make sure BM3D is installed\ntry:\n    import bm3d\nexcept ImportError:\n    print(\"Installing BM3D...\")\n    !pip install bm3d\n\n# Create the animation\nmultiview_path = create_multiview_animation()\n\n# Clean up temp files\nprint(\"Cleaning up temporary files...\")\nfor file in os.listdir(temp_dir):\n    os.remove(os.path.join(temp_dir, file))\nos.rmdir(temp_dir)\n\nprint(f\"Process complete! Denoised GIF saved at: {multiview_path}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-21T16:42:38.505490Z","iopub.execute_input":"2025-03-21T16:42:38.505893Z","iopub.status.idle":"2025-03-21T17:28:01.833049Z","shell.execute_reply.started":"2025-03-21T16:42:38.505860Z","shell.execute_reply":"2025-03-21T17:28:01.831889Z"}},"outputs":[],"execution_count":null}]}