{"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":"gpu","dataSources":[{"sourceId":61446,"databundleVersionId":6962461,"sourceType":"competition"}],"dockerImageVersionId":30626,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport tifffile\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom sklearn.model_selection import train_test_split\nfrom skimage import transform\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\ndef load_and_resize_kidney_images(image_folder_path, target_size=(128, 128)):\n    image_files = sorted([file for file in os.listdir(image_folder_path) if file.endswith(\".tif\")])\n    image_data = []\n    for file in image_files:\n        image = tifffile.imread(os.path.join(image_folder_path, file)).astype(np.float32)\n        resized_image = transform.resize(image, target_size, mode='constant')\n        image_data.append(resized_image)\n    return torch.from_numpy(np.stack(image_data))\n\nimage_folder_path = r'/kaggle/input/blood-vessel-segmentation/train/kidney_3_sparse/images'\ndata = load_and_resize_kidney_images(image_folder_path, target_size=(128, 128))\ndata = data.unsqueeze(1).float()  # Add channel dimension and convert to float\nlabels = torch.from_numpy(np.random.randint(0, 2, size=data.shape)).float()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\ndata = data.to(device)\nlabels = labels.to(device)\n\nX_train, X_temp, y_train, y_temp = train_test_split(data, labels, test_size=0.3, random_state=42)\nX_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)\n\ntrain_dataset = TensorDataset(X_train, y_train)\ntrain_dataloader = DataLoader(train_dataset, batch_size=2, shuffle=True, pin_memory=True)\n\nval_dataset = TensorDataset(X_val, y_val)\nval_dataloader = DataLoader(val_dataset, batch_size=2, shuffle=False, pin_memory=True)\n\nlabels_folder_path = r'/kaggle/input/blood-vessel-segmentation/train/kidney_3_sparse/labels'  # Adjust the path accordingly\nlabel_images = []\nfor file in sorted(os.listdir(labels_folder_path)):\n    if file.endswith(\".tif\"):\n        label_image = tifffile.imread(os.path.join(labels_folder_path, file))\n        label_images.append(torch.from_numpy(label_image).float())\n\nbatch_size = 1000\nfig = plt.figure(figsize=(10, 10))\nax = fig.add_subplot(111, projection='3d')\n\n# Remove grid background\nax.grid(False)\n\n# Set background color to white\nax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))\nax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))\nax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))\n\n# Set axis labels color to black\nax.xaxis.label.set_color('black')\nax.yaxis.label.set_color('black')\nax.zaxis.label.set_color('black')\n\n# Set tick labels color to black\nax.tick_params(axis='x', colors='black')\nax.tick_params(axis='y', colors='black')\nax.tick_params(axis='z', colors='black')\n\nfor batch_start in range(0, len(label_images), batch_size):\n    # Combine a batch of images into one 3D tensor\n    predicted_labels_batch = torch.stack(label_images[batch_start:batch_start + batch_size], dim=0)\n    predicted_labels_batch = predicted_labels_batch.to(device)\n    \n    # Iterate over each image's segmentation result in the batch\n    for i in range(predicted_labels_batch.shape[0]):\n        # Extract coordinates of non-zero values (assuming binary segmentation)\n        non_zero_coords = predicted_labels_batch[i].nonzero()\n        \n        # Check if there are non-zero values before attempting to unpack\n        if non_zero_coords.numel() > 0:\n            if non_zero_coords.dim() == 2:\n                x, y = non_zero_coords.unbind(1)\n                z = torch.full_like(x, fill_value=i + batch_start)  # Use the image index as the z-coordinate\n            elif non_zero_coords.dim() == 1:\n                x, y = non_zero_coords.unbind(0)\n                z = torch.full_like(x, fill_value=i + batch_start)  # Use the image index as the z-coordinate\n            else:\n                x, y, z = non_zero_coords.unbind(1)\n            \n            # Scatter plot with blue color, marker size, and transparency\n            ax.scatter(x.cpu(), y.cpu(), z.cpu(), c='blue', marker='o', s=2, alpha=0.5)\n\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nax.set_title('Combined 3D Segmentation Result for All Images')\n\n# Enable interactive mode for plot rotation\nplt.ion()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T11:24:26.420992Z","iopub.execute_input":"2024-05-29T11:24:26.421684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}