{"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 pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport rasterio\nfrom rasterio import features\nimport shapely\nfrom shapely.geometry import Point, Polygon\n\ndf = pd.read_csv(\"../input/hubmap-organ-segmentation/train.csv\")\ndf['image_path'] = '../input/hubmap-organ-segmentation/train_images/'\ndf['image_path'] = df['image_path'].str.cat(df['id'].astype(str))\ndf['image_path'] = df['image_path'] + '.tiff'\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-06-26T11:21:46.202609Z","iopub.execute_input":"2022-06-26T11:21:46.204871Z","iopub.status.idle":"2022-06-26T11:21:46.430644Z","shell.execute_reply.started":"2022-06-26T11:21:46.204795Z","shell.execute_reply":"2022-06-26T11:21:46.429145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def helper(mask, img_shape):\n  \n    canvas = np.zeros(img_shape).T\n    canvas[tuple(zip(*mask))] = 1.0\n\n      # This is the Equivalent for loop of the above command for better understanding.\n      # for pos in range(len(p_loc)):\n      #   canvas[pos[0], pos[1]] = 1\n\n    return canvas\n\ndef get_mask(rle_string, img_shape):\n    rle = [int(i) for i in rle_string.split(' ')]\n    pairs = list(zip(rle[0::2],rle[1::2]))\n\n    p_loc = []\n\n    for start, length in pairs:\n        for p_pos in range(start, start + length):\n            p_loc.append((p_pos % img_shape[1], p_pos // img_shape[0]))\n  \n    return helper(p_loc, img_shape)\n\n\ndef mask_to_polygons_layer(mask:np.array) -> shapely.geometry.Polygon:\n    \"\"\"Converting mask to polygon object\n    \n    Input:\n        mask: (np.array): Image like Mask [0,1] where all 1 are consider as masks\n        \n    Output:\n        shapely.geometry.Polygon: Polygons\n    \n    \"\"\"\n    all_polygons = []\n    for shape, value in features.shapes(mask.astype(np.int16), mask=(mask >0), transform=rasterio.Affine(1.0, 0, 0, 0, 1.0, 0)):\n        all_polygons.append(shapely.geometry.shape(shape))\n\n    all_polygons = shapely.geometry.MultiPolygon(all_polygons)\n    \n    if not all_polygons.is_valid:\n        all_polygons = all_polygons.buffer(0)\n        # Sometimes buffer() converts a simple Multipolygon to just a Polygon,\n        # need to keep it a Multi throughout\n        if all_polygons.type == 'Polygon':\n            all_polygons = shapely.geometry.MultiPolygon([all_polygons])\n    return all_polygons\n\ndef get_date(id:int) -> tuple:\n    \"\"\"Get Important data\n    \n    Input:\n        id: (int) id of the data\n        get_vals: (list) List of the cols you want to get from the data\n    \n    Output:\n        tuple:\n            int: Image id\n            tuple: Image shape (height, width)\n            image_path: Path of the image\n            image: PIL Image object \n            polygons: Polygon points list\n            mask: Mask of the image\n        \n    \"\"\"\n    get_vals = [\"id\",'img_height', 'img_width','image_path', 'rle']\n    values = list()\n    for i in get_vals:\n        values.append(list(df[df[\"id\"]==id][i].values)[0])\n\n    # Getting image data\n    img_id, img_height, img_width, image_path, rle = values\n    img_shape = (img_width, img_height)\n    image = Image.open(image_path)\n    \n    mask = get_mask(rle, img_shape)\n    \n    # Converting Mask to Polygon\n    polygons = mask_to_polygons_layer(mask)\n    polygons = [list(poly.exterior.coords) for poly in list(polygons)]\n    return (img_id, img_shape, image_path, image, polygons, mask)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-06-26T11:21:46.433196Z","iopub.execute_input":"2022-06-26T11:21:46.433584Z","iopub.status.idle":"2022-06-26T11:21:46.450639Z","shell.execute_reply.started":"2022-06-26T11:21:46.433550Z","shell.execute_reply":"2022-06-26T11:21:46.449237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Draw Polygon","metadata":{}},{"cell_type":"code","source":"import math\nfrom PIL import Image, ImageDraw\nfrom PIL import ImagePath \n  \nfor part in df['organ'].unique():\n    \n    idx = list(df[df['organ']==part][\"id\"].values)[0]\n    \n    img_id, img_shape, image_path, image, polygons, mask = get_date(idx)\n    img1 = ImageDraw.Draw(image) \n\n    for points in polygons:\n        img1.polygon(points,fill=\"#eeeeee\", outline =\"blue\", width=9) \n    \n    \n    plt.figure(figsize=(20,10))\n    plt.imshow(image)\n    plt.title(part)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-26T11:21:46.452884Z","iopub.execute_input":"2022-06-26T11:21:46.453966Z","iopub.status.idle":"2022-06-26T11:22:07.887521Z","shell.execute_reply.started":"2022-06-26T11:21:46.453902Z","shell.execute_reply":"2022-06-26T11:22:07.886281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Draw Masks","metadata":{}},{"cell_type":"code","source":"for part in df['organ'].unique():\n\n  x = df[df['organ'] == part]\n  index_list = x.index\n  idx = index_list[np.random.randint(0, x.shape[0])]\n\n  class_of_scan = df.loc[idx, 'organ']\n  image_path = df.loc[idx, 'image_path']\n  id = df.loc[idx, 'id'] \n  \n  image = np.array(Image.open(image_path)) / 255\n  k = (df.loc[idx, 'img_height'], df.loc[idx, 'img_width'])\n\n  rle_string = df.loc[idx, 'rle']\n  mask = get_mask(rle_string, k)\n\n\n  fig, ax = plt.subplots(1,3, figsize=(15,15))\n  ax[0].set_title(f'Image : {id}')\n  ax[0].imshow(image)\n\n  ax[1].set_title(f'Mask : {id}')\n  ax[1].imshow(mask)\n\n  ax[2].set_title(f'{class_of_scan} Segmented : {id}')\n  ax[2].imshow(np.dstack((mask, np.zeros(mask.shape), np.argmax(image, axis=-1))))\n  plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-26T11:22:07.890238Z","iopub.execute_input":"2022-06-26T11:22:07.890959Z"},"trusted":true},"execution_count":null,"outputs":[]}]}