Skip to content

Instantly share code, notes, and snippets.

@uhho
Last active April 5, 2018 00:01
Show Gist options
  • Save uhho/3835ce8a374e9f1930357f6f58094bb9 to your computer and use it in GitHub Desktop.
Save uhho/3835ce8a374e9f1930357f6f58094bb9 to your computer and use it in GitHub Desktop.
Check if a point lies within a polygon
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# PNPOLY - Point Inclusion in Polygon Test\n",
"\n",
"Python implementation based on PNPOLY by W. Randolph Franklin\n",
"\n",
"https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def inside(point, polygon):\n",
" def pnpoly(nvert, vertx, verty, testx, testy):\n",
" i, j, c = 0, nvert - 1, 0\n",
" for i in range(nvert):\n",
" if ( ((verty[i]>testy) != (verty[j]>testy)) and (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ):\n",
" c = not c\n",
" j = i\n",
" return c\n",
" return pnpoly(polygon.shape[0], polygon[:, 0], polygon[:, 1], point[0], point[1])"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"point = np.array([1.5, 1.5])\n",
"polygon = np.array([[1, 1], [1, 2], [2, 2], [2, 1]]);\n",
"\n",
"inside(point, polygon)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment