Python polygon get points

How to get list of points inside a polygon in python?

Try this code. poly_coords are the coordinates of your polygon, ‘coord’ is coordinate of point you want to check if it is inside the polygon.

def testP(coord, poly_coords): """ The coordinates should be in the form of list of x and y """ test1 = n.array(poly_coords) test2 = n.vstack((poly_coords[1:], poly_coords[:1])) test = test2-test1 m = test[:,1]/test[:,0] c = test1[:,1]-m*test1[:,0] xval = (coord[1]-c)/m print 'xVal:\t'; print xval print (test1[:,0]-xval)*(test2[:,0]-xval) check = n.where((xval>=coord[0])&((test1[:,0]-xval)*(test2[:,0]-xval)<0))[0] print check print len(check) if len(check)%2==0: return False else: return True 

If you want to make it even faster, take out the part of algo related to polygon, slope and offset and run the rest of code using 'map' function. Something like this:

test1 = n.array( your polygon) test2 = n.vstack((test1[1:], test1[:1])) test = test2-test1 m = test[:,1]/test[:,0] c = test1[:,1]-m*test1[:,0] def testP(coord): """ The coordinates should be in the form of list of x and y """ global test, test1, test2, m,c xval = (coord[1]-c)/m check = n.where((xval>=coord[0])&((test1[:,0]-xval)*(test2[:,0]-xval)<0))[0] if len(check)%2==0: return False else: return True coords = n.array(( your coords in x,y )) map (testP, coords) 

You can remove 'print' commands if you want. This code is made for python 2.7

You can use a numpy matrix like a binary image, which can be used with Opencv for example or other image processing libs, Solution 1 So a matrix which size is L x H where

L=max(x) - min (x) H=max(y) - min (y) 

As entry we have your list of tuple(x,y) you gave above which name is poly for example :

import numpy as np matrix =np.zeros((L,H),dtype=np.int32) # you can use np.uint8 if unsigned x ,y 

So we have now a matrix of Size L x H filled with 0, we put now 1 at polygon points positions

I think you can simple do that

matrix[poly]=1 # which will put 1 at each (x,y) of the list **poly** 

we interpret this as a binary (black/white) image which have a contour drawn on it Assume we want to detect this new contour

import cv2 # opencv import ContoursListe,hierarchy = cv2.findContours(self.thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) poly2=ContoursListe[0] # we take the first only contour 

Note : poly2 is containing a list of points of your polygon and all points forming it, i mean all points of each vertices of your polygon which is what you need can find useful !! you can use cv2.CHAIN_APPROX_SIMPLE parameter to get poly2 containing only end points of the polygon lines which is lighter and which was our input 🙂 important :the type of poly2 is numpy array ,its shape is (n,1,2) and not (n,2)

Now we draw this contour on this image(matrix) and will fill it too 🙂

now we have a matrix where there is 1 on each points forming and filling the polygon , "thickness=-1" has forced to fill this contour, you can put set thickness = 1 to get only the borders if you want to translate, you can do it by adding parameter offset(xtran,ytrans)

to get the indices of all theses points simply call

list_of_points_indices=numpy.nonzero(matrix) 

Which is smarter is to directly transform your list of points (poly) to a contour format (poly2) and draw it on the matrix

poly2=poly.reshape(-1,1,2).astype(np.int32) 

and draw it on the Matrix matrix

matrix =np.zeros((L,H),dtype=np.int32) cv2.drawContours(matrix,[poly2],-1,(1),thickness=-1) 

And get the list of this points with :

list_of_points_indices=numpy.nonzero(matrix) 

Play with thickness to fill or not the polygon , see solution 1 for more details.

Читайте также:  Удаление переменных сессии примеры php

Cherif KAOUA 835

I think drawing the polygon and filling it is a good start, you're going to need something like that anyway and those algorithms are usually fine tuned in C. But don't use a RGB image, use a black/white image, and use numpy.where() to find the pixels where it's 1.

According to this question, the mahotas library has a fill_polygon function that works with numpy arrays.

I'm starting the following code from your function (I would subtract the minx and maxx too) but note that I can't test it at all, I'm not on my dev machine.

import numpy as np import mahotas def render(poly): # removed parameter 'z' xs = [i[0] for i in poly] ys = [i[1] for i in poly] minx, maxx = min(xs), max(xs) miny, maxy = min(ys), max(ys) X = maxx - minx + 1 Y = maxy - miny + 1 newPoly = [(x - minx, y - miny) for (x, y) in poly] grid = np.zeros((X, Y), dtype=np.int8) mahotas.polygon.fill_polygon(newPoly, grid) return [(x + minx, y + miny) for (x, y) in np.where(grid)] 

RemcoGerlich 29536

Building upon RemcoGerlich's answer here's a validated function:

import numpy as np import mahotas def render(poly): """Return polygon as grid of points inside polygon. Input : poly (list of lists) Output : output (list of lists) """ xs, ys = zip(*poly) minx, maxx = min(xs), max(xs) miny, maxy = min(ys), max(ys) newPoly = [(int(x - minx), int(y - miny)) for (x, y) in poly] X = maxx - minx + 1 Y = maxy - miny + 1 grid = np.zeros((X, Y), dtype=np.int8) mahotas.polygon.fill_polygon(newPoly, grid) return [(x + minx, y + miny) for (x, y) in zip(*np.nonzero(grid))] 
poly = [ [0, 0], [0, 10], [10, 10], [10, 0] ] plt.figure(None, (5, 5)) x, y = zip(*render(poly)) plt.scatter(x, y) x, y = zip(*poly) plt.plot(x, y, c="r") plt.show() 

enter image description here

Ulf Aslak 7228

I suggest to use matplotlib contains_points()

from matplotlib.path import Path tupVerts=[(86, 52), (85, 52), (81, 53), (80, 52), (79, 48), (81, 49), (86, 53), (85, 51), (82, 54), (84, 54), (83, 49), (81, 52), (80, 50), (81, 48), (85, 50), (86, 54), (85, 54), (80, 48), (79, 50), (85, 49), (80, 51), (85, 53), (82, 49), (83, 54), (82, 53), (84, 49), (79, 49)] x, y = np.meshgrid(np.arange(300), np.arange(300)) # make a canvas with coordinates x, y = x.flatten(), y.flatten() points = np.vstack((x,y)).T p = Path(tupVerts) # make a polygon grid = p.contains_points(points) mask = grid.reshape(300,300) # now you have a mask with points inside a polygon 
  • How to get the AST-tree instead of a list when parsing in Python with ANTLR?
  • How to get a list of variable names from a c file in Python
  • How can I use Python to get the contents inside of this span tag?
  • Python Beginner: How to delete a dictionary inside a list which is also inside another list of dictionaries
  • How do I get the list of imports and dependant files from python script?
  • How to get content inside unordered list with beautifulsoup
  • How i can get random object from list in Python
  • How to get the columns names orderly acorrding to the list in python using for loop
  • how to split the list and get the last value in python
  • How to get a list of some specific weekdays within a date range in python
  • How to grow and return a list from inside a recursive function in python
  • How to convert list which contains a single string with multiple entries inside of string. Python 3
  • get substring Python inside list elements- Web Scraping
  • How to get all the values from a list that are smaller or equivalent to another list in python
  • How to get list of methods in C++ header using python with clang binding?
  • How can Python get a list from XML such as Unicode to a list?
  • How to get common tag pattern for sentences list in python with NLTK
  • How to get list of all databases and run query on it in python
  • How to get list of dict instead of using collection.defaultdict in python
  • How do i get list of subdirectories contains specific file (ie. '__main__.py) using Python
  • How can I use the yum Python module to get a list of packages that will be downloaded before accepting the transaction?
  • How to get the last item of a list in python
  • Python Selenium - How can I get timedate inside of class?
  • How do I find the density of a list of points given latitude and longitude in a 5 mile radius in Python Pandas?
  • How to get the list of csv files in a directory sorted by creation date in Python
  • Robot framework: how to get a list from a python method that returns a list
  • Python Tkinter : How do I get the canvas to update polygon coordinates every frame?
  • How to get unique substrings from list of strings with python
  • Python - How to get the last element of a list (no commas provided)
  • How to get FX Forward Rates instead of Points in BLPAPI in Python
  • How to get Youtube search result list via Python and get maximum amount of videos?
  • How to get top 3 count of names from list of dictionary in python
  • I've get a resultset by python BeautifulSoup, but I don't know how to fetch the NavigableString inside them
  • Get points of sphere in 3d list python
  • How can I get Google Calendar API status_code in Python when get list events?
  • How to get rid of blanks in Python list
  • How to scrape information inside an unordered list selenium + python
  • Python how to get element from json file that has multple elements in list
  • How to programmatically get list of trays of a Google Cloud Print enabled printer in Python in a manufacturer independant way?
  • How to get max value and min value of a given list into tuple form with out using built in max and min function from python
  • How to get the value of a span inside a li using Python Selenium webdriver?
  • How to get the html document contained inside an HTML tag using selenium in python
  • How to get all elements of list in regex in Python
  • how to get string value from a list in python
  • Split a python list without calling itertools' grouper function but get a error
  • How to remove empty entries from a list in a dictionary using python
  • How to split a string and match its substrings to a list of substrings? - Python
  • How do I get HTTP VERB from Python Requests 'Response' objects?
  • How to get all permutations of sizes from list of size n efficiently?
  • How do I list numbers in python from an external file?
Читайте также:  Графики в питоне seaborn

More Query from same tag

  • How to integrate lib into python project using docker?
  • List firewall for specific gke cluster using python api?
  • Is there a way to force type onto a value from a list of types?
  • Python: using append within recursive function - overwrites previous elements
  • How to extract nested text in Scrapy?
  • What have i done wrong? (python help)
  • How do I import a trained deep CNN model?
  • Connect the same signal from several widgets to the same function in PyQt?
  • Sending and receiving frames over the same websocket connection without blocking
  • Reading items from a csv and updating the same items in another csv
  • cdsapi era5 download to computer
  • Socket receive slower in python
  • Filtering on number of times a value appears in PySpark
  • how to apply a function based on a condition to individual column in df.groupby.agg()
  • How do I convert '12/01/2020' to a datetime object using the datetime library and the strptime method?
  • extracting tuples based on values in python
  • recv() keep returning the same data
  • Is there an NSCoding-like facility in Python?
  • Try to parse phone number from html, but get a lot of empty rows
  • Python, tictactoe, syntax error
  • How do I record text entered in the prompt function of pyautogui?
  • Missing styles module from matplotlib?
  • Pyqt5 - grid layout misbehaving
  • Issue trying to convert txt file to fits file
  • Problem installing package using setup.py
  • How to send the data from one computer to another device on the same WiFi network via python socket program?
  • python callback is still blocking
  • Sqlalchemy order_by custom ordering?
  • How can you crop an SVG Image in Python?
  • Python - how to inspect / discover list has references?
  • How can the parent widget position its child widgets?
  • Scrapy doesn't load HttpProxyMiddleware at startup
  • Performing ANOVA and mean on pandas GroupBy on undefined number of columns
  • Error when importing pyrebase with python3
  • A Small programming puzzle
Читайте также:  Вычисление определенного интеграла методом трапеций питон

Источник

Getting list of QgsPoint from polygon Layer in PyQGIS

In this moment I need to get all vertex from the polygon which represent the region bound, but I have not find the documentation about how to get it.

1 Answer 1

You need objects for QgsGeometry class. In my example (polygon layer with only one feature):

enter image description here

the next code gets the list points of the polygon layer:

layer = iface.activeLayer() feature = layer.getFeatures().next() polygon = feature.geometry().asPolygon() n = len(polygon[0]) for i in range(n): print polygon[0][i] 

After running the code at the Python Console of QGIS, I got each polygon point as a tuple:

(384465,4.45043e+06) (392424,4.46131e+06) (409514,4.45616e+06) (411269,4.44282e+06) (404480,4.43076e+06) (392541,4.43486e+06) (381773,4.44118e+06) (384465,4.45043e+06) 

Observe that the first and last points are matched.

Editing Note:

I edited my answer based in your comment. Next code uses QgsVectorLayer class constructor.

import os my_path = '/home/zeito/pyqgis_data/polygon8.shp' #this is a Linux path root,name = os.path.split(my_path) name = name[:-4] layer = QgsVectorLayer(my_path, name, 'ogr') #This is my provider: in your code is memory QgsMapLayerRegistry.instance().addMapLayer(layer) feature = layer.getFeatures().next() polygon = feature.geometry().asPolygon() n = len(polygon[0]) for i in range(n): print polygon[0][i] 

Источник

Оцените статью