{"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":61446,"databundleVersionId":6962461,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\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\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\n    return torch.from_numpy(np.stack(image_data))\n\nimage_folder_path = r'/kaggle/input/blood-vessel-segmentation/train/kidney_3_sparse/images'\n\n\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\n\n\nlabels = torch.from_numpy(np.random.randint(0, 2, size=data.shape)).float()\n\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\n\ntrain_dataset = TensorDataset(X_train, y_train)\ntrain_dataloader = DataLoader(train_dataset, batch_size=2, shuffle=True)\n\n\nval_dataset = TensorDataset(X_val, y_val)\nval_dataloader = DataLoader(val_dataset, batch_size=2, shuffle=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-01T09:46:25.085256Z","iopub.execute_input":"2024-01-01T09:46:25.085709Z","iopub.status.idle":"2024-01-01T09:50:19.961425Z","shell.execute_reply.started":"2024-01-01T09:46:25.085673Z","shell.execute_reply":"2024-01-01T09:50:19.960431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nlabels_folder_path = r'/kaggle/input/blood-vessel-segmentation/train/kidney_3_sparse/labels'  # Adjust the path accordingly\n\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\n\nfig = plt.figure(figsize=(10, 10))\nax = fig.add_subplot(111, projection='3d')\n\ncolors = cm.viridis(torch.linspace(0, 1, len(label_images)))\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\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 varying colors, marker size, and transparency\n            ax.scatter(x, y, z, c=colors[i + batch_start], 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\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-01T10:06:24.753427Z","iopub.execute_input":"2024-01-01T10:06:24.754020Z","iopub.status.idle":"2024-01-01T10:08:54.679262Z","shell.execute_reply.started":"2024-01-01T10:06:24.753977Z","shell.execute_reply":"2024-01-01T10:08:54.678079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}