{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":61446,"databundleVersionId":6962461,"sourceType":"competition"},{"sourceId":7338830,"sourceType":"datasetVersion","datasetId":4256085}],"dockerImageVersionId":30627,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nfrom keras.models import load_model\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport tifffile as tiff\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import plot_model\nfrom sklearn.model_selection import train_test_split\nimport os\nimport numpy as np\nimport random\nfrom tqdm.notebook import tqdm\n\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Activation, Concatenate\n\ndef preprocess_image(path):\n    # Load the image using tifffile\n    image = tiff.imread(path)\n    shape = image.shape\n    shape = [shape[0], shape[1]]\n    \n    # If the image has more than one channel, extract just one channel\n    if image.ndim > 2 and image.shape[2] > 1:\n        image = image[..., 0]\n    \n    # Normalize the image to [0, 1] range\n    image = image / 255.0\n    \n    # Convert image to a TensorFlow tensor\n    image_tensor = tf.convert_to_tensor(image, dtype=tf.float32)\n    \n    # Add a channel dimension if it does not exist\n    if image_tensor.ndim == 2:\n        image_tensor = image_tensor[..., tf.newaxis]\n    \n    # Ensure image tensor is 3D at this point\n    if image_tensor.ndim != 3:\n        raise ValueError('Image tensor must be 3 dimensions [height, width, channels]')\n    \n    # Resize the image to the desired size\n    image_tensor = tf.image.resize(image_tensor, [512, 512])\n    \n    return image_tensor, shape","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-05T07:57:12.103121Z","iopub.execute_input":"2024-01-05T07:57:12.103762Z","iopub.status.idle":"2024-01-05T07:57:30.222380Z","shell.execute_reply.started":"2024-01-05T07:57:12.103731Z","shell.execute_reply":"2024-01-05T07:57:30.221444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_encode(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\nimport gc\nmodels   = [load_model('/kaggle/input/segnet-models-for-senhoa-comp/'+i, compile = False) for i in os.listdir('/kaggle/input/segnet-models-for-senhoa-comp') if i.endswith('f.keras')]\nclfModel = load_model('/kaggle/input/segnet-models-for-senhoa-comp/finalClassifier.keras')\n\ndef predictImage(image_path):\n    image, shape = preprocess_image(image_path)\n    image        = np.array(image).reshape((-1, 512, 512, 1))\n    print(shape)\n    outputs = []\n    from tqdm.notebook import tqdm\n    prevdice = 0\n    for model in tqdm(models, total = len(models)):\n        print('============ Predicting images ==========')\n        pred  = model.predict(image)\n        outputs.append(pred)\n        gc.collect()\n    \n    outputs  = np.stack(outputs, axis =3)\n    clfPred  = (clfModel.predict(outputs.reshape((-1,512,512,16)))>0.8).astype(np.uint8)\n    clfPred = tf.image.resize(clfPred.reshape((512,512,1)), shape, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR).numpy()\n    clfPred  = rle_encode(clfPred)\n    gc.collect()\n    return clfPred","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:57:30.223952Z","iopub.execute_input":"2024-01-05T07:57:30.224479Z","iopub.status.idle":"2024-01-05T07:57:43.104993Z","shell.execute_reply.started":"2024-01-05T07:57:30.224451Z","shell.execute_reply":"2024-01-05T07:57:43.103598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load test images (assuming similar folder structure as training)\ntest_base_path = '/kaggle/input/blood-vessel-segmentation/test'\ntest_image_files = []\n\nfor dataset in os.listdir(test_base_path):\n    images_path = os.path.join(test_base_path, dataset, 'images')\n    if os.path.isdir(images_path):\n        test_image_files += sorted([os.path.join(images_path, f) for f in os.listdir(images_path) if f.endswith('.tif')])\n        \nimport pandas as pd\n\nids = [f'{p.split(\"/\")[-3]}_{os.path.basename(p).split(\".\")[0]}' for p in test_image_files]","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:57:43.106431Z","iopub.execute_input":"2024-01-05T07:57:43.106757Z","iopub.status.idle":"2024-01-05T07:57:43.130552Z","shell.execute_reply.started":"2024-01-05T07:57:43.106728Z","shell.execute_reply":"2024-01-05T07:57:43.129662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rles = [predictImage(imPath) for imPath in test_image_files]\n\nsubmission = pd.DataFrame({\n    \"id\": ids,\n    \"rle\": rles\n})","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:57:43.132545Z","iopub.execute_input":"2024-01-05T07:57:43.132870Z","iopub.status.idle":"2024-01-05T07:58:27.282977Z","shell.execute_reply.started":"2024-01-05T07:57:43.132839Z","shell.execute_reply":"2024-01-05T07:58:27.282196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:58:27.284004Z","iopub.execute_input":"2024-01-05T07:58:27.284260Z","iopub.status.idle":"2024-01-05T07:58:27.303701Z","shell.execute_reply.started":"2024-01-05T07:58:27.284238Z","shell.execute_reply":"2024-01-05T07:58:27.302724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:58:27.304856Z","iopub.execute_input":"2024-01-05T07:58:27.305152Z","iopub.status.idle":"2024-01-05T07:58:27.312945Z","shell.execute_reply.started":"2024-01-05T07:58:27.305128Z","shell.execute_reply":"2024-01-05T07:58:27.312145Z"},"trusted":true},"execution_count":null,"outputs":[]}]}