{"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":7321405,"sourceType":"datasetVersion","datasetId":4248797},{"sourceId":7446865,"sourceType":"datasetVersion","datasetId":4249221,"isSourceIdPinned":false}],"dockerImageVersionId":30627,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install ultralytics --no-index --find-links=/kaggle/input/ultralytics/ --quiet","metadata":{"execution":{"iopub.status.busy":"2024-01-02T07:47:33.828734Z","iopub.execute_input":"2024-01-02T07:47:33.829267Z","iopub.status.idle":"2024-01-02T07:47:47.629596Z","shell.execute_reply.started":"2024-01-02T07:47:33.829231Z","shell.execute_reply":"2024-01-02T07:47:47.628291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nimport cv2\nfrom ultralytics import YOLO\nimport matplotlib.pyplot as plt\nfrom glob import glob\nimport tifffile\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-02T08:30:04.390100Z","iopub.execute_input":"2024-01-02T08:30:04.390570Z","iopub.status.idle":"2024-01-02T08:30:04.398446Z","shell.execute_reply.started":"2024-01-02T08:30:04.390531Z","shell.execute_reply":"2024-01-02T08:30:04.397091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = '/kaggle/input/sennetyolov8-model/runs/segment/train/weights/last.pt'","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:04:20.633638Z","iopub.execute_input":"2024-01-02T08:04:20.634060Z","iopub.status.idle":"2024-01-02T08:04:20.639105Z","shell.execute_reply.started":"2024-01-02T08:04:20.634026Z","shell.execute_reply":"2024-01-02T08:04:20.638246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = YOLO(model_path)","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:04:21.463788Z","iopub.execute_input":"2024-01-02T08:04:21.464236Z","iopub.status.idle":"2024-01-02T08:04:21.526288Z","shell.execute_reply.started":"2024-01-02T08:04:21.464198Z","shell.execute_reply":"2024-01-02T08:04:21.525002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Preprocess_image:\n    def __init__(self, gamma = 0.35):\n        self.lookUpTable = None\n        self.gamma = gamma\n        \n        self.create_lut()\n        \n    \n    def create_lut(self):\n        self.lookUpTable = np.empty((1,256), np.uint8)\n        for i in range(256):\n            self.lookUpTable[0,i] = np.clip(pow(i / 255.0, self.gamma) * 255.0, 0, 255)\n    \n    def read_tiff(self, img_path):\n        self.img_tiff = tifffile.imread(img_path)\n    \n    def convert_tiff2rgb(self):\n        ch0 = (self.img_tiff         & 31).astype('uint8')\n        ch1 = ((self.img_tiff >> 5 ) & 31).astype('uint8')\n        ch2 = ((self.img_tiff >> 10) & 63).astype('uint8')\n        self.rgb = np.stack([ch0, ch1, ch2]).transpose(1, 2, 0)\n    \n    def gammaCorrection(self):\n        self.rgb_g_correct = cv2.LUT(self.rgb.copy(), self.lookUpTable)\n        \n    def process_image(self, img_path):\n        self.read_tiff(img_path)\n        self.convert_tiff2rgb()\n        self.gammaCorrection()\n        ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# proc_img = Preprocess_image(gamma = 0.35)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict_mask(image_path):\n    img = cv2.imread(image_path)\n#     proc_img.process_image(image_path)\n#     img = proc_img.rgb_g_correct\n    H, W, _ = img.shape\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    \n\n    results = model(img)\n    masks = None\n    for result in results:\n        if result.masks is not None:\n            for j, c_mask in enumerate(result.masks.data):\n                mask = c_mask.detach().cpu().numpy().copy()\n                \n                mask = mask * 255\n\n                mask = cv2.resize(mask, (W, H))\n                if masks is None:\n                    masks = mask\n                else:\n                    masks += mask\n                \n    if masks is None:\n#         print('mask is none')\n        masks = np.zeros((H, W)).astype('uint8')\n    masks = masks.astype('bool')\n    return img, masks","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:52:29.372823Z","iopub.execute_input":"2024-01-02T08:52:29.373297Z","iopub.status.idle":"2024-01-02T08:52:29.419570Z","shell.execute_reply.started":"2024-01-02T08:52:29.373255Z","shell.execute_reply":"2024-01-02T08:52:29.417914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '/kaggle/input/blood-vessel-segmentation/test/kidney_5/images/0002.tif'\ntest_data_addr = '/kaggle/input/blood-vessel-segmentation/test/'\n# img_path = '/kaggle/input/blood-vessel-segmentation/train/kidney_2/images/0833.tif'\n# label_path = '/kaggle/input/blood-vessel-segmentation/train/kidney_2/labels/0833.tif'","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:39:40.080465Z","iopub.execute_input":"2024-01-02T08:39:40.080885Z","iopub.status.idle":"2024-01-02T08:39:40.085981Z","shell.execute_reply.started":"2024-01-02T08:39:40.080849Z","shell.execute_reply":"2024-01-02T08:39:40.084775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# img, mask = predict_mask(img_path)\n# plt.figure(figsize = (16, 8))\n# plt.subplot(1, 2, 1)\n# plt.imshow(img)\n# plt.axis('off')\n# plt.subplot(1, 2, 2)\n# plt.imshow(mask, cmap = 'gray')\n# plt.axis('off')\n# None","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:39:40.905621Z","iopub.execute_input":"2024-01-02T08:39:40.906797Z","iopub.status.idle":"2024-01-02T08:39:40.911942Z","shell.execute_reply.started":"2024-01-02T08:39:40.906755Z","shell.execute_reply":"2024-01-02T08:39:40.910609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_encode(mask):\n    pixel = mask.flatten()\n    pixel = np.concatenate([[0], pixel, [0]])\n    run = np.where(pixel[1:] != pixel[:-1])[0] + 1\n    run[1::2] -= run[::2]\n    rle = ' '.join(str(r) for r in run)\n    if rle == '':\n        rle = '1 0'\n    return rle","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:39:41.378697Z","iopub.execute_input":"2024-01-02T08:39:41.379237Z","iopub.status.idle":"2024-01-02T08:39:41.387692Z","shell.execute_reply.started":"2024-01-02T08:39:41.379186Z","shell.execute_reply":"2024-01-02T08:39:41.386621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datasets = os.listdir(test_data_addr)\n_ids = []\n_rles = []\nfor dataset in datasets:\n    images_list = glob(f'{test_data_addr}{dataset}/images/*.tif')\n    \n    for img_path in images_list:\n        img, mask = predict_mask(img_path)\n        rle = rle_encode(mask)\n        \n        img_name = img_path.split('/')[-1].split('.')[0]\n        cid = f'{dataset}_{img_name}'\n        \n        _ids.append(cid)\n        _rles.append(rle)\n    ","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:39:41.894871Z","iopub.execute_input":"2024-01-02T08:39:41.896130Z","iopub.status.idle":"2024-01-02T08:39:43.029358Z","shell.execute_reply.started":"2024-01-02T08:39:41.896075Z","shell.execute_reply":"2024-01-02T08:39:43.028261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = pd.DataFrame({\n    'id': _ids,\n    'rle': _rles\n})","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:41:47.811082Z","iopub.execute_input":"2024-01-02T08:41:47.812059Z","iopub.status.idle":"2024-01-02T08:41:47.817391Z","shell.execute_reply.started":"2024-01-02T08:41:47.812020Z","shell.execute_reply":"2024-01-02T08:41:47.816089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:41:51.366082Z","iopub.execute_input":"2024-01-02T08:41:51.366516Z","iopub.status.idle":"2024-01-02T08:41:51.376463Z","shell.execute_reply.started":"2024-01-02T08:41:51.366477Z","shell.execute_reply":"2024-01-02T08:41:51.375429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-02T08:41:51.994159Z","iopub.execute_input":"2024-01-02T08:41:51.994876Z","iopub.status.idle":"2024-01-02T08:41:52.004549Z","shell.execute_reply.started":"2024-01-02T08:41:51.994837Z","shell.execute_reply":"2024-01-02T08:41:52.003266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"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":[]}]}