Skip to content

Instantly share code, notes, and snippets.

@grovduck
Last active November 15, 2017 21:32
Show Gist options
  • Save grovduck/7fcccba74961ca6d332195a4eccf79d4 to your computer and use it in GitHub Desktop.
Save grovduck/7fcccba74961ca6d332195a4eccf79d4 to your computer and use it in GitHub Desktop.
[Bounded random points] Generate random points using a rasterio dataset as boundary #rasterio #numpy #algorithms
def generate_random_points(r, num_points):
"""
Generate random points with replacement using a raster as a bound. Points
will be the centers of pixels in the raster
Parameters
----------
r: rasterio.RasterReader
The raster to use as the bounding area
num_points: int
The number of points to generate
Returns
-------
points: list of tuples
The X,Y coordinates of random pixel centers
"""
# Get dimensions and cellsize of raster
w, h = r.meta['width'], r.meta['height']
cs = r.affine.a / 2.0
# Create the functions to generate the random points
rand = lambda lim: np.random.randint(lim)
to_xy = lambda rc: r.ul(*rc)
center = lambda xy: (xy[0] + cs, xy[1] - cs)
# Generate the list of points
return [center(to_xy(((rand(h), rand(w))))) for i in xrange(num_points)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment