{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nfrom skimage import io\nimport os\nimport glob\n# import imutils\n# from imutils import contours\nfrom skimage import measure\nimport argparse\n","metadata":{"_uuid":"50c6d885-7ef6-4213-8000-220740b1adb2","_cell_guid":"74d04a4a-0f2c-4aad-8d18-f8f26f10924a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-07-22T09:42:50.328002Z","iopub.execute_input":"2022-07-22T09:42:50.328442Z","iopub.status.idle":"2022-07-22T09:42:50.848281Z","shell.execute_reply.started":"2022-07-22T09:42:50.328405Z","shell.execute_reply":"2022-07-22T09:42:50.847108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2022-07-22T09:42:06.348997Z","iopub.execute_input":"2022-07-22T09:42:06.349383Z","iopub.status.idle":"2022-07-22T09:42:37.686960Z","shell.execute_reply.started":"2022-07-22T09:42:06.349353Z","shell.execute_reply":"2022-07-22T09:42:37.685901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rleToMask(rleString,height,width):\n    rows,cols = height,width\n    rleNumbers = [int(numstring) for numstring in rleString.split(' ')]\n    rlePairs = np.array(rleNumbers).reshape(-1,2)\n    img = np.zeros(rows*cols,dtype=np.uint8)\n    for index,length in rlePairs:\n        index -= 1\n        img[index:index+length] = 255\n    img = img.reshape(cols,rows)\n    img = img.T\n    return img\n\ndef plot_images(id:int,encs:str):\n    img = io.imread(f\"/Users/nishantbhansali/Desktop/hubmap/train_images/{id}.tiff\")\n    mask = rleToMask(encs,img.shape[0],img.shape[1])\n    f,(ax1,ax2,ax3) = plt.subplots(1,3,figsize = (20,16),sharey = True)\n    ax1.imshow(img)\n    ax1.set_title(\"Image\")\n    ax2.imshow(mask,cmap = 'gray')\n    ax2.set_title(\"Mask\")\n    ax3.imshow(img)\n    ax3.imshow(mask,cmap='jet', alpha=0.5)\n    ax3.set_title(\"Image+Mask\")\n    plt.show()\n\n\ndef rle_encode(img):\n    \"\"\" TBD\n    \n    Args:\n        img (np.array): \n            - 1 indicating mask\n            - 0 indicating background\n    \n    Returns: \n        run length as string formated\n    \"\"\"\n    \n    img = img.T\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)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T09:42:56.926987Z","iopub.execute_input":"2022-07-22T09:42:56.927387Z","iopub.status.idle":"2022-07-22T09:42:56.939191Z","shell.execute_reply.started":"2022-07-22T09:42:56.927355Z","shell.execute_reply":"2022-07-22T09:42:56.938154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv(\"../input/hubmap-organ-segmentation/test.csv\")\ntrain_df = pd.read_csv(\"../input/hubmap-organ-segmentation/train.csv\")\ntest_dr = \"../input/hubmap-organ-segmentation/test_images\"\ndisplay(test_df)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T09:43:01.919910Z","iopub.execute_input":"2022-07-22T09:43:01.920668Z","iopub.status.idle":"2022-07-22T09:43:02.274018Z","shell.execute_reply.started":"2022-07-22T09:43:01.920629Z","shell.execute_reply":"2022-07-22T09:43:02.272764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SMART_CIRCLE_FRAC = 0.85\ndef blob_detection(img_path,blurring = False,threshold = 240,erosion_iterations = 2,\n                    dilation_iterations = 4,pixelcount_threshold = 500,plot = True):\n    \n    image = cv2.imread(img_path)\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n    if plot:\n        fig,axes = plt.subplots(6,figsize = (35,35))\n    \n\n    if blurring:\n        blurred = cv2.GaussianBlur(gray, (11, 11), 0)\n    else:\n        blurred = gray\n\n    if plot:\n        axes[0].imshow(blurred,cmap = \"gray\")\n\n    thresh = cv2.threshold(blurred, threshold, 255, cv2.THRESH_BINARY)[1]\n    if plot:\n        axes[1].imshow(thresh,cmap = \"gray\")\n    # plt.imshow(thresh,cmap=\"gray\")\n    thresh = cv2.erode(thresh, None, iterations=erosion_iterations)\n    thresh = cv2.dilate(thresh, None, iterations=dilation_iterations)\n\n    if plot:\n        axes[2].imshow(thresh,cmap = \"gray\")\n\n    # plt.imshow(thresh,cmap=\"gray\")\n    labels = measure.label(thresh, background=0)\n    mask = np.zeros(thresh.shape, dtype=\"uint8\")\n    # loop over the unique components\n    for label in np.unique(labels):\n        # if this is the background label, ignore it\n        if label == 0:\n            continue\n        # otherwise, construct the label mask and count the\n        # number of pixels \n        labelMask = np.zeros(thresh.shape, dtype=\"uint8\")\n        labelMask[labels == label] = 255\n        numPixels = cv2.countNonZero(labelMask)\n        # if the number of pixels in the component is sufficiently\n        # large, then add it to our mask of \"large blobs\"\n        if numPixels > pixelcount_threshold:\n            mask = cv2.add(mask, labelMask)\n\n    if plot:\n        axes[3].imshow(mask,cmap = \"gray\")\n\n    h,w = mask.shape[0],mask.shape[1]\n    circle_mask = np.zeros((h,w))\n    circle_mask = cv2.circle(circle_mask, (int(np.round(h/2)), int(np.round(w/2))), int(np.round((h/2)*SMART_CIRCLE_FRAC)), 1, -1)\n    mask = mask*circle_mask\n    \n    if plot:\n        axes[4].imshow(mask,cmap = \"gray\")\n        axes[5].imshow(image)\n        axes[5].imshow(mask,cmap =\"jet\",alpha = 0.4)\n\n        \n    return mask\n        \n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T09:43:46.374356Z","iopub.execute_input":"2022-07-22T09:43:46.374751Z","iopub.status.idle":"2022-07-22T09:43:46.388374Z","shell.execute_reply.started":"2022-07-22T09:43:46.374721Z","shell.execute_reply":"2022-07-22T09:43:46.387163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# for idx,row in test_df.iterrows():\n#     print(row['id'])\n#     img_w,img_h = row['img_width'],row['img_height']\n#     mask = blob_detection()\n#     rles.append(rle_encode(mask))\n\n# test_df['rle'] = rles\n# display(test_df)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nrles = []\nfor i,row in test_df.iterrows():\n    try:\n        idx = row[\"id\"]\n        img_path = img_path = f\"../input/hubmap-organ-segmentation/test_images/{idx}.tiff\"\n\n        mask = blob_detection(img_path=img_path,threshold = 220,plot=True)\n#         gt_mask = rleToMask(row['rle'],row[\"img_width\"],row[\"img_height\"])\n#         dice_coeff.append(dice(mask,gt_mask))\n\n        # if i>4:\n        #     break\n        plt.imshow(mask,cmap = \"gray\")\n        rles.append(rle_encode(mask))\n        \n    except:\n        print(f\"error in {i}\")\n        continue\n\ntest_df['rle'] = rles\ndisplay(test_df)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T09:54:23.373172Z","iopub.execute_input":"2022-07-22T09:54:23.373654Z","iopub.status.idle":"2022-07-22T09:54:29.208144Z","shell.execute_reply.started":"2022-07-22T09:54:23.373617Z","shell.execute_reply":"2022-07-22T09:54:29.206885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = test_df[[\"id\", \"rle\"]]\ntest_df.to_csv(\"submission.csv\", index=False)\ndisplay(test_df)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T09:54:14.127126Z","iopub.execute_input":"2022-07-22T09:54:14.128226Z","iopub.status.idle":"2022-07-22T09:54:14.141904Z","shell.execute_reply.started":"2022-07-22T09:54:14.128170Z","shell.execute_reply":"2022-07-22T09:54:14.141030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}