{
  "id": 336279,
  "title": "Colored Masks",
  "url": "/competitions/hubmap-organ-segmentation/discussion/336279",
  "author_name": "",
  "post_date": "2022-07-10T10:10:13.068424800Z",
  "votes": 6,
  "comment_count": 10,
  "views": 0,
  "content": "<p>Another useful code snippet using <a href=\"https://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.label2rgb\" target=\"_blank\"><code>skimage.color.label2rgb</code></a>. </p>\n<p>This is useful function to have <strong>both the image and the masks as a colored overlay</strong>. </p>\n<p>Here is a code snippet on how to do it:</p>\n<pre><code>from skimage.color import label2rgb\nimport pandas as pd\nfrom PIL import Image\n\n#&amp;nbsp;The same old rle2mask function, very handy!\ndef rle2mask(mask_rle, shape=(256, 256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n    Source: https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode\n    '''\n    s = mask_rle.split()\n    #&amp;nbsp;print(\"The length of the RLE is:\", len(s))\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    return img.reshape(shape).T\n\n\n#&amp;nbsp;Select the image id you want to display\nimg_id = 10274\nimg_path = f\"../input/hubmap-organ-segmentation/train_images/{img_id}.tiff\"\n#&amp;nbsp;We also need the metadata to get the RLE.\ntrain_path = \"../input/hubmap-organ-segmentation/train.csv\"\n\npil_img = Image.open(img_path)\n# The image should be an array for the label2rgb\n#&amp;nbsp;function\nimg = np.asarray(pil_img)\n\n#&amp;nbsp;We get the mask from the metadata DataFrame.\ntrain_df = pd.read_csv(train_path)\nrle = train_df.loc[lambda df: df[\"id\"] == img_id, \"rle\"].values[0]\nmask = rle2mask(rle, shape=(3000, 3000))\n\n#&amp;nbsp;Play a bit with the bg_color and alpha to get different renderings.\n#&amp;nbsp;By default, the first mask will be in red unless you specify a different\n#&amp;nbsp;list of colors.\n#&amp;nbsp;If you choose bg_label=1, the background will be red.\nimg_with_colored_masks = label2rgb(mask, img, bg_label=0, \n                                                               bg_color=(1.,1.,1.), \n                                                               alpha=0.5)\nplt.imshow(img_with_colored_masks)\n</code></pre>\n<p>Here is what the result might look like:</p>\n<p><img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2F2c9fcff3f973406f5fd751fe3b1dbfd6%2FScreenshot%20from%202022-07-10%2012-05-18.png?generation=1657447799356700&amp;alt=media&amp;width=100\" alt=\"img_with_colored_masks\"></p>\n<p>I hope this is useful for exploring the masks. </p>",
  "messages": [
    {
      "id": "1850314",
      "postDate": "07/10/2022 10:10:13",
      "content": "<p>Another useful code snippet using <a href=\"https://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.label2rgb\" target=\"_blank\"><code>skimage.color.label2rgb</code></a>. </p>\n<p>This is useful function to have <strong>both the image and the masks as a colored overlay</strong>. </p>\n<p>Here is a code snippet on how to do it:</p>\n<pre><code>from skimage.color import label2rgb\nimport pandas as pd\nfrom PIL import Image\n\n#&amp;nbsp;The same old rle2mask function, very handy!\ndef rle2mask(mask_rle, shape=(256, 256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n    Source: https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode\n    '''\n    s = mask_rle.split()\n    #&amp;nbsp;print(\"The length of the RLE is:\", len(s))\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    return img.reshape(shape).T\n\n\n#&amp;nbsp;Select the image id you want to display\nimg_id = 10274\nimg_path = f\"../input/hubmap-organ-segmentation/train_images/{img_id}.tiff\"\n#&amp;nbsp;We also need the metadata to get the RLE.\ntrain_path = \"../input/hubmap-organ-segmentation/train.csv\"\n\npil_img = Image.open(img_path)\n# The image should be an array for the label2rgb\n#&amp;nbsp;function\nimg = np.asarray(pil_img)\n\n#&amp;nbsp;We get the mask from the metadata DataFrame.\ntrain_df = pd.read_csv(train_path)\nrle = train_df.loc[lambda df: df[\"id\"] == img_id, \"rle\"].values[0]\nmask = rle2mask(rle, shape=(3000, 3000))\n\n#&amp;nbsp;Play a bit with the bg_color and alpha to get different renderings.\n#&amp;nbsp;By default, the first mask will be in red unless you specify a different\n#&amp;nbsp;list of colors.\n#&amp;nbsp;If you choose bg_label=1, the background will be red.\nimg_with_colored_masks = label2rgb(mask, img, bg_label=0, \n                                                               bg_color=(1.,1.,1.), \n                                                               alpha=0.5)\nplt.imshow(img_with_colored_masks)\n</code></pre>\n<p>Here is what the result might look like:</p>\n<p><img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2F2c9fcff3f973406f5fd751fe3b1dbfd6%2FScreenshot%20from%202022-07-10%2012-05-18.png?generation=1657447799356700&amp;alt=media&amp;width=100\" alt=\"img_with_colored_masks\"></p>\n<p>I hope this is useful for exploring the masks. </p>",
      "rawMarkdown": "Another useful code snippet using [`skimage.color.label2rgb`](https://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.label2rgb). \n\nThis is useful function to have **both the image and the masks as a colored overlay**. \n\nHere is a code snippet on how to do it:\n\n\n```\nfrom skimage.color import label2rgb\nimport pandas as pd\nfrom PIL import Image\n\n# The same old rle2mask function, very handy!\ndef rle2mask(mask_rle, shape=(256, 256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n    Source: https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode\n    '''\n    s = mask_rle.split()\n    # print(\"The length of the RLE is:\", len(s))\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    return img.reshape(shape).T\n\n\n# Select the image id you want to display\nimg_id = 10274\nimg_path = f\"../input/hubmap-organ-segmentation/train_images/{img_id}.tiff\"\n# We also need the metadata to get the RLE.\ntrain_path = \"../input/hubmap-organ-segmentation/train.csv\"\n\npil_img = Image.open(img_path)\n# The image should be an array for the label2rgb\n# function\nimg = np.asarray(pil_img)\n\n# We get the mask from the metadata DataFrame.\ntrain_df = pd.read_csv(train_path)\nrle = train_df.loc[lambda df: df[\"id\"] == img_id, \"rle\"].values[0]\nmask = rle2mask(rle, shape=(3000, 3000))\n\n# Play a bit with the bg_color and alpha to get different renderings.\n# By default, the first mask will be in red unless you specify a different\n# list of colors.\n# If you choose bg_label=1, the background will be red.\nimg_with_colored_masks = label2rgb(mask, img, bg_label=0, \n                                                               bg_color=(1.,1.,1.), \n                                                               alpha=0.5)\nplt.imshow(img_with_colored_masks)\n\n```\n\nHere is what the result might look like:\n\n![img_with_colored_masks](https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2F2c9fcff3f973406f5fd751fe3b1dbfd6%2FScreenshot%20from%202022-07-10%2012-05-18.png?generation=1657447799356700&alt=media&width=100)\n\nI hope this is useful for exploring the masks.",
      "votes": null
    },
    {
      "id": "1850320",
      "postDate": "07/10/2022 10:19:02",
      "content": "<p>thanks for sharing this! it is really helpful <a href=\"https://www.kaggle.com/yassinealouini\" target=\"_blank\">@yassinealouini</a> </p>",
      "rawMarkdown": "thanks for sharing this! it is really helpful @yassinealouini",
      "votes": null
    },
    {
      "id": "1850648",
      "postDate": "07/10/2022 15:17:53",
      "content": "<p>Thanks <a href=\"https://www.kaggle.com/subhajitbag\" target=\"_blank\">@subhajitbag</a>. Glad you like it. 👌 </p>",
      "rawMarkdown": "Thanks @subhajitbag. Glad you like it. 👌",
      "votes": null
    },
    {
      "id": "1850855",
      "postDate": "07/10/2022 20:35:30",
      "content": "<p>Thanks a lot! Have you noticed this type of masks in the data? Just wondering, if it is the issue of your script or the data itself.<img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1269464%2F69b74d43e4edaf9eba229d647fb2ff53%2Fw1n_l2UyEKoyx1bon7-rE20PW2gA8oWcMwcWGq2oz7SgzPdVXoCvTtJIBn4gK4_4UhP-i8Y-819DvXWPw6AEwKzs.jpg?generation=1657485320264590&amp;alt=media\" alt=\"\"></p>",
      "rawMarkdown": "Thanks a lot! Have you noticed this type of masks in the data? Just wondering, if it is the issue of your script or the data itself.![](https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1269464%2F69b74d43e4edaf9eba229d647fb2ff53%2Fw1n_l2UyEKoyx1bon7-rE20PW2gA8oWcMwcWGq2oz7SgzPdVXoCvTtJIBn4gK4_4UhP-i8Y-819DvXWPw6AEwKzs.jpg?generation=1657485320264590&alt=media)",
      "votes": null
    },
    {
      "id": "1850926",
      "postDate": "07/10/2022 23:39:37",
      "content": "<p>Wow really interesting! It will be helpful for sure.. thanks for sharing this snippet. </p>",
      "rawMarkdown": "Wow really interesting! It will be helpful for sure.. thanks for sharing this snippet.",
      "votes": null
    },
    {
      "id": "1851248",
      "postDate": "07/11/2022 05:39:10",
      "content": "<p>That's an interesting artifact. Which image id is it? 👀</p>",
      "rawMarkdown": "That's an interesting artifact. Which image id is it? 👀",
      "votes": null
    },
    {
      "id": "1851249",
      "postDate": "07/11/2022 05:39:27",
      "content": "<p>You are welcome. 👌 </p>",
      "rawMarkdown": "You are welcome. 👌",
      "votes": null
    },
    {
      "id": "1851410",
      "postDate": "07/11/2022 08:20:11",
      "content": "<p>I don't remember which one is this particular image, but you can look into 5317, 14396, 2344. These are quite similar</p>",
      "rawMarkdown": "I don't remember which one is this particular image, but you can look into 5317, 14396, 2344. These are quite similar",
      "votes": null
    },
    {
      "id": "1851534",
      "postDate": "07/11/2022 10:32:23",
      "content": "<p>I don't have that type of artifact. You probably mess something up while decoding rle masks.</p>",
      "rawMarkdown": "I don't have that type of artifact. You probably mess something up while decoding rle masks.",
      "votes": null
    },
    {
      "id": "1851944",
      "postDate": "07/11/2022 17:00:53",
      "content": "<p>I spotted the problem. There are images of different size from (3000, 3000).</p>\n<p>So, you should change the line <br>\n <code>mask = rle2mask(rle, shape=(3000, 3000))</code><br>\ninto<br>\n<code>mask = rle2mask(rle, shape=img.shape[:2])</code></p>\n<p>In this case the all the masks will look normal.</p>",
      "rawMarkdown": "I spotted the problem. There are images of different size from (3000, 3000).\n\nSo, you should change the line \n `mask = rle2mask(rle, shape=(3000, 3000))`\ninto\n`mask = rle2mask(rle, shape=img.shape[:2])`\n\nIn this case the all the masks will look normal.",
      "votes": null
    },
    {
      "id": "1853326",
      "postDate": "07/12/2022 20:15:31",
      "content": "<p>You are right of course. Most of the images are of size <code>(3000, 3000)</code> but some aren't. Check this plot from my \"Some insights\" <a href=\"https://www.kaggle.com/competitions/hubmap-organ-segmentation/discussion/333389\" target=\"_blank\">discussion</a>:</p>\n<p><img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2Fc26a1688d25854c1c0e9154a7b5598ec%2Finbox_172860_0ca15f350b45010e20d710025cb1986d_img_width_distribution.png?generation=1657656920671560&amp;alt=media\" alt=\"img_height_distr\"></p>",
      "rawMarkdown": "You are right of course. Most of the images are of size `(3000, 3000)` but some aren't. Check this plot from my \"Some insights\" [discussion](https://www.kaggle.com/competitions/hubmap-organ-segmentation/discussion/333389):\n\n\n\n![img_height_distr](https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2Fc26a1688d25854c1c0e9154a7b5598ec%2Finbox_172860_0ca15f350b45010e20d710025cb1986d_img_width_distribution.png?generation=1657656920671560&alt=media)",
      "votes": null
    }
  ],
  "comments": [
    {
      "id": 1850320,
      "author_name": "subhajitbag",
      "author_url": "",
      "post_date": "07/10/2022 10:19:02",
      "content": "<p>thanks for sharing this! it is really helpful <a href=\"https://www.kaggle.com/yassinealouini\" target=\"_blank\">@yassinealouini</a> </p>",
      "votes": null,
      "replies": [
        {
          "id": 1850648,
          "author_name": "yassinealouini",
          "author_url": "",
          "post_date": "07/10/2022 15:17:53",
          "content": "<p>Thanks <a href=\"https://www.kaggle.com/subhajitbag\" target=\"_blank\">@subhajitbag</a>. Glad you like it. 👌 </p>",
          "votes": null,
          "replies": []
        }
      ]
    },
    {
      "id": 1850855,
      "author_name": "artichoke",
      "author_url": "",
      "post_date": "07/10/2022 20:35:30",
      "content": "<p>Thanks a lot! Have you noticed this type of masks in the data? Just wondering, if it is the issue of your script or the data itself.<img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1269464%2F69b74d43e4edaf9eba229d647fb2ff53%2Fw1n_l2UyEKoyx1bon7-rE20PW2gA8oWcMwcWGq2oz7SgzPdVXoCvTtJIBn4gK4_4UhP-i8Y-819DvXWPw6AEwKzs.jpg?generation=1657485320264590&amp;alt=media\" alt=\"\"></p>",
      "votes": null,
      "replies": [
        {
          "id": 1851248,
          "author_name": "yassinealouini",
          "author_url": "",
          "post_date": "07/11/2022 05:39:10",
          "content": "<p>That's an interesting artifact. Which image id is it? 👀</p>",
          "votes": null,
          "replies": []
        },
        {
          "id": 1851410,
          "author_name": "artichoke",
          "author_url": "",
          "post_date": "07/11/2022 08:20:11",
          "content": "<p>I don't remember which one is this particular image, but you can look into 5317, 14396, 2344. These are quite similar</p>",
          "votes": null,
          "replies": []
        },
        {
          "id": 1851534,
          "author_name": "gunesevitan",
          "author_url": "",
          "post_date": "07/11/2022 10:32:23",
          "content": "<p>I don't have that type of artifact. You probably mess something up while decoding rle masks.</p>",
          "votes": null,
          "replies": []
        },
        {
          "id": 1851944,
          "author_name": "artichoke",
          "author_url": "",
          "post_date": "07/11/2022 17:00:53",
          "content": "<p>I spotted the problem. There are images of different size from (3000, 3000).</p>\n<p>So, you should change the line <br>\n <code>mask = rle2mask(rle, shape=(3000, 3000))</code><br>\ninto<br>\n<code>mask = rle2mask(rle, shape=img.shape[:2])</code></p>\n<p>In this case the all the masks will look normal.</p>",
          "votes": null,
          "replies": []
        },
        {
          "id": 1853326,
          "author_name": "yassinealouini",
          "author_url": "",
          "post_date": "07/12/2022 20:15:31",
          "content": "<p>You are right of course. Most of the images are of size <code>(3000, 3000)</code> but some aren't. Check this plot from my \"Some insights\" <a href=\"https://www.kaggle.com/competitions/hubmap-organ-segmentation/discussion/333389\" target=\"_blank\">discussion</a>:</p>\n<p><img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2Fc26a1688d25854c1c0e9154a7b5598ec%2Finbox_172860_0ca15f350b45010e20d710025cb1986d_img_width_distribution.png?generation=1657656920671560&amp;alt=media\" alt=\"img_height_distr\"></p>",
          "votes": null,
          "replies": []
        }
      ]
    },
    {
      "id": 1850926,
      "author_name": "cid007",
      "author_url": "",
      "post_date": "07/10/2022 23:39:37",
      "content": "<p>Wow really interesting! It will be helpful for sure.. thanks for sharing this snippet. </p>",
      "votes": null,
      "replies": [
        {
          "id": 1851249,
          "author_name": "yassinealouini",
          "author_url": "",
          "post_date": "07/11/2022 05:39:27",
          "content": "<p>You are welcome. 👌 </p>",
          "votes": null,
          "replies": []
        }
      ]
    }
  ],
  "raw_markdown_by_id": {
    "1850314": "Another useful code snippet using [`skimage.color.label2rgb`](https://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.label2rgb). \n\nThis is useful function to have **both the image and the masks as a colored overlay**. \n\nHere is a code snippet on how to do it:\n\n\n```\nfrom skimage.color import label2rgb\nimport pandas as pd\nfrom PIL import Image\n\n# The same old rle2mask function, very handy!\ndef rle2mask(mask_rle, shape=(256, 256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n    Source: https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode\n    '''\n    s = mask_rle.split()\n    # print(\"The length of the RLE is:\", len(s))\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    return img.reshape(shape).T\n\n\n# Select the image id you want to display\nimg_id = 10274\nimg_path = f\"../input/hubmap-organ-segmentation/train_images/{img_id}.tiff\"\n# We also need the metadata to get the RLE.\ntrain_path = \"../input/hubmap-organ-segmentation/train.csv\"\n\npil_img = Image.open(img_path)\n# The image should be an array for the label2rgb\n# function\nimg = np.asarray(pil_img)\n\n# We get the mask from the metadata DataFrame.\ntrain_df = pd.read_csv(train_path)\nrle = train_df.loc[lambda df: df[\"id\"] == img_id, \"rle\"].values[0]\nmask = rle2mask(rle, shape=(3000, 3000))\n\n# Play a bit with the bg_color and alpha to get different renderings.\n# By default, the first mask will be in red unless you specify a different\n# list of colors.\n# If you choose bg_label=1, the background will be red.\nimg_with_colored_masks = label2rgb(mask, img, bg_label=0, \n                                                               bg_color=(1.,1.,1.), \n                                                               alpha=0.5)\nplt.imshow(img_with_colored_masks)\n\n```\n\nHere is what the result might look like:\n\n![img_with_colored_masks](https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2F2c9fcff3f973406f5fd751fe3b1dbfd6%2FScreenshot%20from%202022-07-10%2012-05-18.png?generation=1657447799356700&alt=media&width=100)\n\nI hope this is useful for exploring the masks.",
    "1850320": "thanks for sharing this! it is really helpful @yassinealouini",
    "1850648": "Thanks @subhajitbag. Glad you like it. 👌",
    "1850855": "Thanks a lot! Have you noticed this type of masks in the data? Just wondering, if it is the issue of your script or the data itself.![](https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F1269464%2F69b74d43e4edaf9eba229d647fb2ff53%2Fw1n_l2UyEKoyx1bon7-rE20PW2gA8oWcMwcWGq2oz7SgzPdVXoCvTtJIBn4gK4_4UhP-i8Y-819DvXWPw6AEwKzs.jpg?generation=1657485320264590&alt=media)",
    "1850926": "Wow really interesting! It will be helpful for sure.. thanks for sharing this snippet.",
    "1851248": "That's an interesting artifact. Which image id is it? 👀",
    "1851249": "You are welcome. 👌",
    "1851410": "I don't remember which one is this particular image, but you can look into 5317, 14396, 2344. These are quite similar",
    "1851534": "I don't have that type of artifact. You probably mess something up while decoding rle masks.",
    "1851944": "I spotted the problem. There are images of different size from (3000, 3000).\n\nSo, you should change the line \n `mask = rle2mask(rle, shape=(3000, 3000))`\ninto\n`mask = rle2mask(rle, shape=img.shape[:2])`\n\nIn this case the all the masks will look normal.",
    "1853326": "You are right of course. Most of the images are of size `(3000, 3000)` but some aren't. Check this plot from my \"Some insights\" [discussion](https://www.kaggle.com/competitions/hubmap-organ-segmentation/discussion/333389):\n\n\n\n![img_height_distr](https://www.googleapis.com/download/storage/v1/b/kaggle-forum-message-attachments/o/inbox%2F172860%2Fc26a1688d25854c1c0e9154a7b5598ec%2Finbox_172860_0ca15f350b45010e20d710025cb1986d_img_width_distribution.png?generation=1657656920671560&alt=media)"
  },
  "source": "meta"
}