本文整理汇总了Python中rasterio.features.rasterize方法的典型用法代码示例。如果您正苦于以下问题:Python features.rasterize方法的具体用法?Python features.rasterize怎么用?Python features.rasterize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rasterio.features
的用法示例。
在下文中一共展示了features.rasterize方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: burn
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def burn(tile, features, size):
"""Burn tile with features.
Args:
tile: the mercantile tile to burn.
features: the geojson features to burn.
size: the size of burned image.
Returns:
image: rasterized file of size with features burned.
"""
# the value you want in the output raster where a shape exists
burnval = 1
shapes = ((geometry, burnval) for feature in features for geometry in feature_to_mercator(feature))
bounds = mercantile.xy_bounds(tile)
transform = from_bounds(*bounds, size, size)
return rasterize(shapes, out_shape=(size, size), transform=transform)
示例2: burn
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def burn(polys, zoom):
bounds = find_extrema(polys)
tilerange = tile_extrema(bounds, zoom)
afftrans = make_transform(tilerange, zoom)
burn = features.rasterize(
((project_geom(geom['geometry']), 255) for geom in polys),
out_shape=((tilerange['y']['max'] - tilerange['y']['min'], tilerange['x']['max'] - tilerange['x']['min'])),
transform=afftrans,
all_touched=True)
xys = np.fliplr(np.dstack(np.where(burn))[0])
xys[:, 0] += tilerange['x']['min']
xys[:, 1] += tilerange['y']['min']
return np.append(xys, np.zeros((xys.shape[0], 1), dtype=np.uint8) + zoom, axis=1)
示例3: _determine_method
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def _determine_method(lon, lat):
""" find method to be used -> prefers faster methods"""
if equally_spaced(lon, lat):
return "rasterize"
if _equally_spaced_on_split_lon(lon) and equally_spaced(lat):
split_point = _find_splitpoint(lon)
flipped_lon = np.hstack((lon[split_point:], lon[:split_point]))
if equally_spaced(flipped_lon):
return "rasterize_flip"
else:
return "rasterize_split"
return "shapely"
示例4: add_parser
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def add_parser(subparser):
parser = subparser.add_parser(
"rasterize", help="rasterize features to label masks", formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("features", type=str, help="path to GeoJSON features file")
parser.add_argument("tiles", type=str, help="path to .csv tiles file")
parser.add_argument("out", type=str, help="directory to write converted images")
parser.add_argument("--dataset", type=str, required=True, help="path to dataset configuration file")
parser.add_argument("--zoom", type=int, required=True, help="zoom level of tiles")
parser.add_argument("--size", type=int, default=512, help="size of rasterized image tiles in pixels")
parser.set_defaults(func=main)
示例5: _mask_rasterize_no_offset
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def _mask_rasterize_no_offset(lon, lat, polygons, numbers, fill=np.NaN, **kwargs):
""" Rasterize a list of (geometry, fill_value) tuples onto the given coordinates.
This only works for 1D lat and lon arrays.
for internal use: does not check valitity of input
"""
# TODO: use only this function once https://github.com/mapbox/rasterio/issues/1844
# is resolved
from rasterio import features
shapes = zip(polygons, numbers)
transform = _transform_from_latlon(lon, lat)
out_shape = (len(lat), len(lon))
raster = features.rasterize(
shapes,
out_shape=out_shape,
fill=fill,
transform=transform,
dtype=np.float,
**kwargs
)
return raster
示例6: main
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def main(args):
dataset = load_config(args.dataset)
classes = dataset["common"]["classes"]
colors = dataset["common"]["colors"]
assert len(classes) == len(colors), "classes and colors coincide"
assert len(colors) == 2, "only binary models supported right now"
bg = colors[0]
fg = colors[1]
os.makedirs(args.out, exist_ok=True)
# We can only rasterize all tiles at a single zoom.
assert all(tile.z == args.zoom for tile in tiles_from_csv(args.tiles))
with open(args.features) as f:
fc = json.load(f)
# Find all tiles the features cover and make a map object for quick lookup.
feature_map = collections.defaultdict(list)
for i, feature in enumerate(tqdm(fc["features"], ascii=True, unit="feature")):
if feature["geometry"]["type"] != "Polygon":
continue
try:
for tile in burntiles.burn([feature], zoom=args.zoom):
feature_map[mercantile.Tile(*tile)].append(feature)
except ValueError as e:
print("Warning: invalid feature {}, skipping".format(i), file=sys.stderr)
continue
# Burn features to tiles and write to a slippy map directory.
for tile in tqdm(list(tiles_from_csv(args.tiles)), ascii=True, unit="tile"):
if tile in feature_map:
out = burn(tile, feature_map[tile], args.size)
else:
out = np.zeros(shape=(args.size, args.size), dtype=np.uint8)
out_dir = os.path.join(args.out, str(tile.z), str(tile.x))
os.makedirs(out_dir, exist_ok=True)
out_path = os.path.join(out_dir, "{}.png".format(tile.y))
if os.path.exists(out_path):
prev = np.array(Image.open(out_path))
out = np.maximum(out, prev)
out = Image.fromarray(out, mode="P")
palette = make_palette(bg, fg)
out.putpalette(palette)
out.save(out_path, optimize=True)
示例7: accuracy
# 需要导入模块: from rasterio import features [as 别名]
# 或者: from rasterio.features import rasterize [as 别名]
def accuracy(grid_in, guess_in, aoi_in, buffer_amount=0.01):
"""Measure accuracy against a specified grid 'truth' file.
Parameters
----------
grid_in : str, Path
Path to vector truth file.
guess_in : str, Path
Path to guess output from guess2geom.
aoi_in : str, Path
Path to AOI feature.
buffer_amount : float, optional (default 0.01.)
Leeway in decimal degrees in calculating equivalence.
0.01 DD equals approximately 1 mile at the equator.
"""
if isinstance(aoi_in, gpd.GeoDataFrame):
aoi = aoi_in
else:
aoi = gpd.read_file(aoi_in)
grid = gpd.read_file(grid_in)
grid_clipped = clip_line_poly(grid, aoi)
grid_buff = grid_clipped.buffer(buffer_amount)
guesses_reader = rasterio.open(guess_in)
guesses = guesses_reader.read(1)
grid_for_raster = [(row.geometry) for _, row in grid_clipped.iterrows()]
grid_raster = rasterize(
grid_for_raster,
out_shape=guesses_reader.shape,
fill=1,
default_value=0,
all_touched=True,
transform=guesses_reader.transform,
)
grid_buff_raster = rasterize(
grid_buff,
out_shape=guesses_reader.shape,
fill=1,
default_value=0,
all_touched=True,
transform=guesses_reader.transform,
)
grid_raster = flip_arr_values(grid_raster)
grid_buff_raster = flip_arr_values(grid_buff_raster)
tp = true_positives(guesses, grid_buff_raster)
fn = false_negatives(guesses, grid_raster)
return tp, fn