import fiona
from fiona.crs import to_string
import os
boro_file = os.path.join("..", "data", "nybb", "nybb.shp")
out_file = os.path.join("..", "data", "nybb", "nybb.geojson")
# Register format drivers with a context manager
with fiona.drivers():
# Open the shapefile (can also open directly from zip files with vfs!)
with fiona.open(boro_file) as source:
print("Feature Count: %s" % len(source))
print("Input Driver: %s" % source.driver)
meta = source.meta
meta.update(driver="GeoJSON")
if os.path.exists(out_file):
os.remove(out_file)
with fiona.open(out_file, 'w', **meta) as sink:
print("Output Driver: %s" % sink.driver)
for rec in source:
sink.write(rec)
# Did it work?
print("File Exists: %s" % os.path.exists(out_file))
import rasterio
from fiona.crs import to_string
import os
import numpy as np
image_file = os.path.join('..', 'data', 'manhattan.tif')
# Register format drivers with a context manager
with rasterio.drivers():
with rasterio.open(image_file, 'r') as source:
print(source.count, source.shape)
print(source.driver)
print(to_string(source.crs))
# Get data from each band (newer versions of rasterio use source.read())
r, g, b = map(source.read_band, (1, 2, 3))
data = np.dstack((r, g, b)) # Each band is just an ndarray!
print(type(data))
# Get the bounds of the raster (for plotting later)
bounds = source.bounds[::2] + source.bounds[1::2]
An alternative way (outside of with
context manager as above):
source = rasterio.open(image_file, 'r')
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(8, 8))
ax = plt.imshow(data, extent=bounds)
plt.show()
[Working with Rasters in Python
](../exercises/Working with Rasters in Python.ipynb)