It is possible to iterate over points/vertices by directly accessing the vector geometry through pygrass.
# Get and plot the coordinates of all of the points in a vector file.
# Then generalize this to lines (this will probably work for boundaries
# too).
# I'm answering it for both here because (1) this is the way I worked
# through the problem, and (2) I think it makes intuitive sense because
# points are simpler and lines are just points connected in an order.
# Written 02 Feb 2015 by Andrew Wickert
# Released to the Public Domain
from grass.pygrass import vector
import numpy as np
from matplotlib import pyplot as plt
############
## POINTS ##
############
data = vector.VectorTopo(NameOfVectorString) # Create a VectorTopo object
data.open('r') # Open this object for reading
# Get the points and append them to the list -- these are point objects.
# These display the coordinates and retain a lot of GRASS GIS functionality.
pointsList = []
for i in range(len(data)):
pointsList.append(data.read(i+1)) # GRASS vectors seem to be indexed starting at 1
# But for my purposes, it's often nice to just have a numpy array of the actual
# coordinate values
coords = []
for i in range(len(data)):
coords.append(data.read(i+1).coords()) # gives a tuple
coords = np.array(coords)
# To see if the points look correct
plt.figure()
plt.plot(coords[:,0], coords[:,1], 'ko')
plt.show()
# And of course you could do better plotting with a tool like Basemap.
# (http://matplotlib.org/basemap/)
###########
## LINES ##
###########
lines = vector.VectorTopo(NameOfVectorString)
lines.open('r')
# On looking at this, each entry in "lines" is a line with multiple points.
# As output, I would like a list of numpy arrays of these points.
def get_vertices(_line):
"""
Extract vertices in line, in order, and places them in a numpy array
"""
outline = []
for vertex in _line:
outline.append(vertex.coords())
outline = np.array(outline)
return outline
LineCoordArrays = []
for i in range(len(lines)):
LineCoordArrays.append( get_vertices(lines[i+1]) )
# Plot them all in whatever color they appear
plt.figure( figsize = (8,8) )
for line in LineCoordArrays:
plt.plot(line[:,0], line[:,1])
plt.show()
I should mention that this problem has bothered me for quite some time! I have for >1 year used the answer provided by @gene, and it worked well, but now that I have found this method, I think it is more the "right way". I really appreciate its organization of lines, and while I have not yet tried it with enclosed lines or areas, I expect that it will organize these nicely as well.