{"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"}],"dockerImageVersionId":30579,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"\nfrom xgboost import XGBClassifier\n","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:10:02.346710Z","iopub.execute_input":"2024-11-15T18:10:02.347125Z","iopub.status.idle":"2024-11-15T18:10:04.407816Z","shell.execute_reply.started":"2024-11-15T18:10:02.347090Z","shell.execute_reply":"2024-11-15T18:10:04.406537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\n\nimport random\nimport time\nimport os\nimport pathlib\nimport pandas as pd\nimport numpy as np\nimport skimage\nimport tifffile as tiff\n\nfrom sklearn.mixture import GaussianMixture\nfrom scipy import ndimage as ndi\nimport skimage\nimport sklearn\nfrom sklearn.model_selection import train_test_split\n\ndef prepare():\n\n    base_path = '/kaggle/input/blood-vessel-segmentation/train'\n\n    for x in os.listdir(base_path):\n        folder_path = os.path.join(base_path,x)\n        print(folder_path)\n        print(os.listdir(folder_path))\n\n    mask_path_list = [str(x) for x in pathlib.Path(base_path).rglob('*.tif') if '/labels/' in str(x)]\n\n    mylist = []\n    for mask_path in mask_path_list:\n        if 'kidney_3_sparse' in mask_path:\n            # we skip it since dense is provided.\n            continue\n        image_path = mask_path.replace(\"/labels/\",\"/images/\")\n        if 'kidney_3_dense' in mask_path:\n            image_path = image_path.replace(\"kidney_3_dense\",\"kidney_3_sparse\")\n        assert(os.path.exists(image_path))\n        assert(os.path.exists(mask_path))\n        myitem=dict(\n            image_path=image_path,\n            mask_path=mask_path\n        )\n        mylist.append(myitem)\n\n    df = pd.DataFrame(mylist)\n    train_df=df.sample(frac=0.01,random_state=420)\n    df=df.drop(train_df.index)\n    val_df=df.sample(frac=0.01,random_state=420)\n    test_df=df.drop(val_df.index)\n    \n    os.makedirs('csvs',exist_ok=True)\n    \n    train_df=train_df.reset_index()\n    train_df.to_csv('csvs/train.csv',index=False)\n\n    val_df=val_df.reset_index()\n    val_df.to_csv('csvs/val.csv',index=False)\n    \n    test_df=test_df.reset_index()\n    test_df.to_csv('csvs/test.csv',index=False)\n\n    print(train_df.shape,val_df.shape,test_df.shape)\n\ndef readimage(mypath):\n    image = tiff.imread(mypath)\n    assert(len(image.shape)==2)\n    image = image.astype(np.float64)\n    return image\n\ndef readmask(mypath):\n    mask = tiff.imread(mypath)\n    assert(len(mask.shape)==2)\n    mask = mask > 0\n    mask = mask.astype(np.float64)\n    return mask\n\ndef normalize_image(image):\n    image = (image-np.mean(image))/np.std(image)\n    return image\n\ndef 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    mystr = ' '.join(str(x) for x in runs)\n    if mystr == \"\":\n        mystr = \"1 0\"\n    return mystr\n\ndef rle_decode(mask_rle, shape):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height,width) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n\n    return img.reshape(shape)\n","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:10:04.410240Z","iopub.execute_input":"2024-11-15T18:10:04.410760Z","iopub.status.idle":"2024-11-15T18:10:05.205703Z","shell.execute_reply.started":"2024-11-15T18:10:04.410725Z","shell.execute_reply":"2024-11-15T18:10:05.204507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prepare()","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:10:05.207089Z","iopub.execute_input":"2024-11-15T18:10:05.207458Z","iopub.status.idle":"2024-11-15T18:10:27.190999Z","shell.execute_reply.started":"2024-11-15T18:10:05.207429Z","shell.execute_reply":"2024-11-15T18:10:27.189724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"! ls -lha csvs","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:10:27.193958Z","iopub.execute_input":"2024-11-15T18:10:27.194855Z","iopub.status.idle":"2024-11-15T18:10:28.288994Z","shell.execute_reply.started":"2024-11-15T18:10:27.194812Z","shell.execute_reply":"2024-11-15T18:10:28.287467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n","metadata":{}},{"cell_type":"code","source":"#\n# sample and visualize data\n#\n\ndf = pd.read_csv('csvs/train.csv')\nfor n,row in df.iterrows():\n    \n    t0 = time.time() \n    basename = os.path.basename(row.image_path)\n    image = readimage(row.image_path)\n    image = normalize_image(image)\n    mask = readmask(row.mask_path)\n    t1 = time.time() \n    \n    t2 = time.time()\n    image_mod = skimage.transform.resize(image, (512,512), order=0)\n    mask_mod = skimage.transform.resize(mask, (512,512), order=0)\n    t3 = time.time()\n    if np.sum(mask) > 0:\n        vessel_mean = np.mean(image_mod[mask_mod>0])\n    else:\n        vessel_mean = np.nan\n    \n    X = np.expand_dims(image_mod.ravel(),axis=-1)\n    t4 = time.time()\n    gmm = GaussianMixture(n_components=2, random_state=0).fit(X)\n    t5 = time.time()\n     \n    print(t1-t0,t3-t2,t5-t4)\n    mu0 =gmm.means_[0][0]\n    var0 = gmm.covariances_[0][0][0]\n    mu1 =gmm.means_[1][0]\n    var1 = gmm.covariances_[1][0][0]\n\n    blocks=skimage.util.view_as_blocks(image_mod,(32,32))\n    background_values = []\n    for idx_x,idx_y in [[0,0],[0,-1],[-1,0],[-1,-1]]:\n        background_values.append(np.mean(blocks[:,:,idx_x,idx_y]))\n    background_mean = np.mean(background_values)\n    \n    plt.figure(n)\n    plt.subplot(212)\n    n_bins = 100\n    plt.hist(image.ravel(), bins=n_bins)\n    plt.axvline(vessel_mean,color='red')\n    plt.axvline(mu1,color='green')\n    plt.axvline(mu1-var1,color='blue',linestyle='--')\n    plt.axvline(mu0,color='green')\n    plt.axvline(mu0-var0,color='blue',linestyle='--')\n    plt.axvline(background_mean,color='black')\n    plt.title('vessel(red),mu(green),mu-sd(blue),bkgd(black)')\n    \n    plt.grid(True)\n    plt.subplot(221)\n    plt.imshow(image,cmap='gray')\n    plt.colorbar()\n    plt.subplot(222)\n    plt.imshow(mask,cmap='gray')\n    plt.title(f'mean {vessel_mean:1.1f}')\n    plt.colorbar()\n    if n>10:\n        break","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:10:28.290905Z","iopub.execute_input":"2024-11-15T18:10:28.291336Z","iopub.status.idle":"2024-11-15T18:11:01.800743Z","shell.execute_reply.started":"2024-11-15T18:10:28.291296Z","shell.execute_reply":"2024-11-15T18:11:01.799546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"prelminary thoughts formed from above samples:\n\n+ image intensity distribution likely is bimodal or unimodal.\n+ looks like image intensity distribution is bimodal at lower resolution (in histology terms: \"wholemount\" versus \"micrographs\"?).\n+ regardless of resolution, vessel structures are darker than its surroundings.\n+ shape wise, on the 2d images, vessel shape is circular or tubular due to image orientation.\n+ given the small sample size, most likely we can assume the flavors in train-set will not be representative of those in testset / real-world data. \n","metadata":{}},{"cell_type":"code","source":"\ndef process(image):\n    # prepare filter bank kernels\n    feat_list = [image]\n    for sigma in (1, 3, 10):\n        gauss_image = skimage.filters.gaussian(image, sigma=sigma)\n        feat_list.append(gauss_image)\n\n    for sigma in (1, 3):\n        for theta in range(4):\n            theta = theta / 4. * np.pi\n            for frequency in (0.05, 0.25):\n                gabor_real,_=skimage.filters.gabor(\n                    image, frequency, theta=theta, bandwidth=1,\n                    sigma_x=sigma,sigma_y=sigma,offset=0, mode='reflect', cval=0)\n                feat_list.append(gabor_real)\n\n    #image = skimage.transform.resize(image, (512,512), order=0)\n    X = np.expand_dims(image.ravel(),axis=-1)\n    gmm = GaussianMixture(n_components=2, random_state=0).fit(X)\n    mu0 =gmm.means_[0][0]\n    var0 = gmm.covariances_[0][0][0]\n    mu1 =gmm.means_[1][0]\n    var1 = gmm.covariances_[1][0][0]\n    \n    blocks=skimage.util.view_as_blocks(image_mod,(32,32))\n    background_values = []\n    for idx_x,idx_y in [[0,0],[0,-1],[-1,0],[-1,-1]]:\n        background_values.append(np.mean(blocks[:,:,idx_x,idx_y]))\n    background_mean = np.mean(background_values)\n    for val in [mu0,var0,mu1,var1,background_mean]:\n        tmp = val*np.ones_like(image)\n        feat_list.append(tmp)\n\n    new_shape = (len(feat_list),np.prod(image.shape))\n    feat = np.reshape(np.array(feat_list), new_shape).T\n    return feat\n","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:11:01.802359Z","iopub.execute_input":"2024-11-15T18:11:01.802781Z","iopub.status.idle":"2024-11-15T18:11:01.818823Z","shell.execute_reply.started":"2024-11-15T18:11:01.802742Z","shell.execute_reply":"2024-11-15T18:11:01.817467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nylist = []\nxlist = []\ndf = pd.read_csv('csvs/train.csv')\nprint(df.shape)\nwidth,height = 1024,1024\n\nfor n,row in df.iterrows():\n    image = readimage(row.image_path)\n    image = skimage.transform.resize(image, (width,height), order=0)\n    image = normalize_image(image)\n    feat = process(image)\n\n    mask = readmask(row.mask_path)\n    mask = skimage.transform.resize(mask, (width,height), order=0)\n    mask = mask>0\n    mask = np.expand_dims(mask.ravel(),axis=-1)    \n    negative_idx,_ = np.where(mask==0)\n    positive_idx,_ = np.where(mask==1)\n    random.shuffle(negative_idx)\n    random.shuffle(positive_idx)\n    print(len(positive_idx[:1000]),len(negative_idx[:3000]))\n    xlist.append(feat[positive_idx[:1000],:])\n    ylist.append(mask[positive_idx[:1000],:])\n    xlist.append(feat[negative_idx[:3000],:])\n    ylist.append(mask[negative_idx[:3000],:])\n    \n    print(n,len(df))\n\n    if n > 10:\n        break\n","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:11:01.820504Z","iopub.execute_input":"2024-11-15T18:11:01.821487Z","iopub.status.idle":"2024-11-15T18:13:20.467746Z","shell.execute_reply.started":"2024-11-15T18:11:01.821445Z","shell.execute_reply":"2024-11-15T18:13:20.466594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Xarr = np.concatenate(xlist,axis=0)\nYarr = np.concatenate(ylist,axis=0)\nprint(Xarr.shape,Yarr.shape)","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:13:20.469224Z","iopub.execute_input":"2024-11-15T18:13:20.469641Z","iopub.status.idle":"2024-11-15T18:13:20.478461Z","shell.execute_reply.started":"2024-11-15T18:13:20.469596Z","shell.execute_reply":"2024-11-15T18:13:20.477047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(Xarr,Yarr, test_size=.2)\nbst = XGBClassifier(n_estimators=2, max_depth=2, learning_rate=1, objective='binary:logistic')\n\nbst.fit(X_train, y_train)\nbst.save_model('xgb_model.json')","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:13:20.479861Z","iopub.execute_input":"2024-11-15T18:13:20.480454Z","iopub.status.idle":"2024-11-15T18:13:20.633450Z","shell.execute_reply.started":"2024-11-15T18:13:20.480415Z","shell.execute_reply":"2024-11-15T18:13:20.632555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# bst = XGBClassifier()\n# bst.load_model('xgb_model.json')","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:13:20.637382Z","iopub.execute_input":"2024-11-15T18:13:20.637839Z","iopub.status.idle":"2024-11-15T18:13:20.644656Z","shell.execute_reply.started":"2024-11-15T18:13:20.637798Z","shell.execute_reply":"2024-11-15T18:13:20.643427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# make predictions\ny_pred_train = bst.predict(X_train)\nprint(np.unique(y_pred_train))\ny_pred_test = bst.predict(X_test)\nprint(np.unique(y_pred_test))\nacc = sklearn.metrics.accuracy_score(y_train, y_pred_train)\nprint('acc train',acc)\nacc = sklearn.metrics.accuracy_score(y_test, y_pred_test)\nprint('acc \"test\"',acc)\ncm = sklearn.metrics.confusion_matrix(y_test, y_pred_test)\nprint(cm)","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:13:20.646463Z","iopub.execute_input":"2024-11-15T18:13:20.646832Z","iopub.status.idle":"2024-11-15T18:13:20.677567Z","shell.execute_reply.started":"2024-11-15T18:13:20.646800Z","shell.execute_reply":"2024-11-15T18:13:20.676347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def inference(tif_path):\n    image = readimage(tif_path)\n    original_shape = image.shape\n    image = normalize_image(image)\n    image = skimage.transform.resize(image, (width,height), order=0)\n    feat = process(image)\n    y_hat = bst.predict(feat)\n    output_mask = np.reshape(y_hat,image.shape)\n    output_mask = skimage.transform.resize(output_mask, original_shape, order=0)\n    output_mask = output_mask > 0\n    return output_mask","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:13:20.678958Z","iopub.execute_input":"2024-11-15T18:13:20.679317Z","iopub.status.idle":"2024-11-15T18:13:20.685764Z","shell.execute_reply.started":"2024-11-15T18:13:20.679286Z","shell.execute_reply":"2024-11-15T18:13:20.684594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef nosubmit():\n    df = pd.read_csv('csvs/test.csv')\n    mylist = []\n    for n,row in df.iterrows():\n        tif_path = row.image_path\n        mask_path = row.mask_path\n        dataset_id = os.path.basename(os.path.dirname(os.path.dirname(tif_path)))\n        slice_id = os.path.basename(tif_path).replace(\".tif\",\"\")\n        case_id = f'{dataset_id}_{slice_id}'\n        output_mask = inference(tif_path)\n        \n        image = readimage(tif_path)\n        mask = readmask(mask_path)\n        plt.figure(n)\n        plt.subplot(131)\n        plt.imshow(image)\n        plt.subplot(132)\n        plt.imshow(mask)\n        plt.subplot(133)\n        plt.imshow(output_mask)\n        rle_str = rle_encode(output_mask)\n        print(len(rle_str),case_id)\n        if n > 10:\n            break\n\nnosubmit()\n","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:13:20.687177Z","iopub.execute_input":"2024-11-15T18:13:20.687532Z","iopub.status.idle":"2024-11-15T18:15:33.280448Z","shell.execute_reply.started":"2024-11-15T18:13:20.687504Z","shell.execute_reply":"2024-11-15T18:15:33.279046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ndef submit():\n    test_folder = \"/kaggle/input/blood-vessel-segmentation/test\"\n    tif_list = sorted([str(x) for x in pathlib.Path(test_folder).rglob(\"*.tif\")])\n    mylist = []\n    for n,tif_path in enumerate(tif_list):\n        dataset_id = os.path.basename(os.path.dirname(os.path.dirname(tif_path)))\n        slice_id = os.path.basename(tif_path).replace(\".tif\",\"\")\n        case_id = f'{dataset_id}_{slice_id}'\n        print(case_id)\n        output_mask = inference(tif_path)\n        #plt.figure(n)\n        #plt.imshow(output_mask)\n        rle_str = rle_encode(output_mask)\n        print(len(rle_str),tif_path)\n        \n        myitem={\n            \"id\":case_id,\n            \"rle\":rle_str\n        }\n        mylist.append(myitem)\n\n    df = pd.DataFrame(mylist)\n    df.to_csv(\"submission.csv\",index=False)\n\nsubmit()","metadata":{"execution":{"iopub.status.busy":"2024-11-15T18:15:33.282323Z","iopub.execute_input":"2024-11-15T18:15:33.282803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('submission.csv')\nfor n,row in df.iterrows():\n    print(row.id,len(row.rle))","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":[]}]}