Skip to content

Instantly share code, notes, and snippets.

@Feyn-Man
Created December 11, 2020 11:00
Show Gist options
  • Select an option

  • Save Feyn-Man/fefd9a38224f1f1e8ca1b18dcafb06d1 to your computer and use it in GitHub Desktop.

Select an option

Save Feyn-Man/fefd9a38224f1f1e8ca1b18dcafb06d1 to your computer and use it in GitHub Desktop.
biggest_area_selector.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "biggest_area_selector.ipynb",
"provenance": [],
"authorship_tag": "ABX9TyPq2Hm3tJ9Rqc0ublJpzU+b",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/Feyn-Man/fefd9a38224f1f1e8ca1b18dcafb06d1/biggest_area_selector.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"metadata": {
"id": "6h1Gg-p_c9BO"
},
"source": [
"import numpy as np\r\n",
"from scipy import ndimage"
],
"execution_count": 1,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "kEfYfD7idHbF"
},
"source": [
"def biggest_area_selector(arr):\r\n",
" \r\n",
" \"\"\"\r\n",
" Keep the connected component with the biggest area inside of a numpy array.\r\n",
"\r\n",
" Example:\r\n",
" > arr = np.array([[1,1,1],\r\n",
" [0,1,0],\r\n",
" [0,0,0],\r\n",
" [2,2,1]])\r\n",
" \r\n",
" > biggest_area_selector(arr)\r\n",
" array([[1, 1, 1],\r\n",
" [0, 1, 0],\r\n",
" [0, 0, 0],\r\n",
" [0, 0, 0]])\r\n",
" \"\"\"\r\n",
"\r\n",
" label_arr, _ = ndimage.label(arr)\r\n",
" nonzero_labels = np.unique(label_arr)[np.unique(label_arr) > 0]\r\n",
" areas = np.bincount(label_arr.reshape((label_arr.size, )))\r\n",
" max_label = nonzero_labels[np.argmax(areas[1:])]\r\n",
" return np.where(label_arr == max_label, arr, 0)"
],
"execution_count": 2,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment