本文整理汇总了Python中rasterio.drivers函数的典型用法代码示例。如果您正苦于以下问题:Python drivers函数的具体用法?Python drivers怎么用?Python drivers使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了drivers函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(npy_in,tif_out,tif_like):
arr_in = np.load(npy_in)
locs = arr_in[:,:2].astype(np.int)
## "un-flatten" to array shape of basin raster
# get correct shape and coordinates
with rs.drivers():
with rs.open(tif_like) as src:
profile = src.profile
w,h = (src.width, src.height)
aff = src.affine
ndv = src.get_nodatavals()
x,y = [i.astype(np.int) for i in (~aff * (locs[:,0],locs[:,1]))]
# construct 3d array
arr_out = np.ones((w,h,arr_in.shape[1]-2),dtype=np.float32)
arr_out[:] = ndv
arr_out[x,y,:] = arr_in[:,2:]
arr_out = np.swapaxes(arr_out,0,2)
# update output profile to get correct # of bands and compression mechanism
profile.update(
count = arr_out.shape[0],
compress = 'DEFLATE')
## output Tiff file
with rs.drivers():
with rs.open(tif_out, 'w', **profile) as dst:
dst.write(arr_out)
示例2: test_drivers
def test_drivers():
with rasterio.drivers() as m:
assert driver_count() > 0
assert type(m) == DriverManager
n = rasterio.drivers()
assert driver_count() > 0
assert type(n) == DummyManager
示例3: test_drivers
def test_drivers():
with rasterio.drivers() as m:
assert driver_count() > 0
assert type(m) == GDALEnv
n = rasterio.drivers()
assert driver_count() > 0
assert type(n) == GDALEnv
示例4: _src
def _src(self):
""" An optionally memoized generator on time series datasets
"""
if self.keep_open:
if not hasattr(self, '_src_open'):
with rasterio.drivers():
self._src_open = [rasterio.open(f, 'r') for
f in self.df['filename']]
for _src in self._src_open:
yield _src
else:
with rasterio.drivers():
for f in self.df['filename']:
yield rasterio.open(f, 'r')
示例5: test_mask_crop
def test_mask_crop(runner, tmpdir, basic_feature, pixelated_image):
"""
In order to test --crop option, we need to use a transform more similar to
a normal raster, with a negative y pixel size.
"""
image = pixelated_image
outfilename = str(tmpdir.join("pixelated_image.tif"))
kwargs = {
"crs": {"init": "epsg:4326"},
"transform": Affine(1, 0, 0, 0, -1, 0),
"count": 1,
"dtype": rasterio.uint8,
"driver": "GTiff",
"width": image.shape[1],
"height": image.shape[0],
"nodata": 255,
}
with rasterio.drivers():
with rasterio.open(outfilename, "w", **kwargs) as out:
out.write_band(1, image)
output = str(tmpdir.join("test.tif"))
truth = numpy.zeros((4, 3))
truth[1:3, 0:2] = 1
result = runner.invoke(
features.mask, [outfilename, output, "--crop", "--geojson-mask", "-"], input=json.dumps(basic_feature)
)
assert result.exit_code == 0
assert os.path.exists(output)
with rasterio.open(output) as out:
assert numpy.array_equal(truth, out.read(1, masked=True).filled(0))
示例6: write_band
def write_band(self, output_band, output_file, image_data):
# colormaps will overwrite our transparency masks so we will manually
# create three RGB bands
self.output("Applying ColorMap", normal=True, arrow=True)
self.cmap[0] = (0, 0, 0, 255)
v_manual_colormap = numpy.vectorize(self.manual_colormap, otypes=[numpy.uint8])
rgb_bands = []
for i in range(3):
rgb_bands.append(v_manual_colormap(output_band, i))
with rasterio.drivers(GDAL_TIFF_INTERNAL_MASK=True):
with rasterio.open(output_file, 'w', driver='GTiff',
width=image_data['shape'][1],
height=image_data['shape'][0],
count=3,
dtype=numpy.uint8,
nodata=0,
photometric='RGB',
transform=image_data['dst_transform'],
crs=self.dst_crs) as output:
for i in range(3):
output.write_band(i+1, rgb_bands[i])
self.output("Writing to file", normal=True, color='green', indent=1)
return output_file
示例7: test_rasterize_supported_dtype
def test_rasterize_supported_dtype(basic_geometry):
""" Supported data types should return valid results """
with rasterio.drivers():
supported_types = (
('int16', -32768),
('int32', -2147483648),
('uint8', 255),
('uint16', 65535),
('uint32', 4294967295),
('float32', 1.434532),
('float64', -98332.133422114)
)
for dtype, default_value in supported_types:
truth = numpy.zeros(DEFAULT_SHAPE, dtype=dtype)
truth[2:4, 2:4] = default_value
result = rasterize(
[basic_geometry],
out_shape=DEFAULT_SHAPE,
default_value=default_value,
dtype=dtype
)
assert numpy.array_equal(result, truth)
assert numpy.dtype(result.dtype) == numpy.dtype(truth.dtype)
result = rasterize(
[(basic_geometry, default_value)],
out_shape=DEFAULT_SHAPE
)
if numpy.dtype(dtype).kind == 'f':
assert numpy.allclose(result, truth)
else:
assert numpy.array_equal(result, truth)
示例8: test_shapes
def test_shapes(basic_image):
""" Test creation of shapes from pixel values """
with rasterio.drivers():
results = list(shapes(basic_image))
assert len(results) == 2
shape, value = results[0]
assert shape == {
'coordinates': [
[(2, 2), (2, 5), (5, 5), (5, 2), (2, 2)]
],
'type': 'Polygon'
}
assert value == 1
shape, value = results[1]
assert shape == {
'coordinates': [
[(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)],
[(2, 2), (5, 2), (5, 5), (2, 5), (2, 2)]
],
'type': 'Polygon'
}
assert value == 0
示例9: shapes
def shapes(image, mask=None, connectivity=4, transform=IDENTITY):
"""Yields a (shape, image_value) pair for each feature in the image.
The shapes are GeoJSON-like dicts and the image values are ints.
Features are found using a connected-component labeling algorithm.
The image must be of unsigned 8-bit integer (rasterio.byte or
numpy.uint8) data type. If a mask is provided, pixels for which the
mask is `False` will be excluded from feature generation.
"""
if np.dtype(image.dtype) != np.dtype(rasterio.ubyte):
raise ValueError("Image must be dtype uint8/ubyte")
if mask is not None and np.dtype(mask.dtype) != np.dtype(rasterio.bool_):
raise ValueError("Mask must be dtype rasterio.bool_")
if connectivity not in (4, 8):
raise ValueError("Connectivity Option must be 4 or 8")
transform = guard_transform(transform)
with rasterio.drivers():
for s, v in _shapes(image, mask, connectivity, transform.to_gdal()):
yield s, v
示例10: test_data_dir_2
def test_data_dir_2(tmpdir):
kwargs = {
"crs": {'init': 'epsg:4326'},
"transform": (-114, 0.2, 0, 46, 0, -0.1),
"count": 1,
"dtype": rasterio.uint8,
"driver": "GTiff",
"width": 10,
"height": 10
# these files have undefined nodata.
}
with rasterio.drivers():
with rasterio.open(str(tmpdir.join('b.tif')), 'w', **kwargs) as dst:
data = numpy.zeros((10, 10), dtype=rasterio.uint8)
data[0:6, 0:6] = 255
dst.write_band(1, data)
with rasterio.open(str(tmpdir.join('a.tif')), 'w', **kwargs) as dst:
data = numpy.zeros((10, 10), dtype=rasterio.uint8)
data[4:8, 4:8] = 254
dst.write_band(1, data)
return tmpdir
示例11: test_sieve_mask
def test_sieve_mask():
"""Test proper behavior of mask image, if passed int sieve"""
with rasterio.drivers():
shape = (20, 20)
image = numpy.zeros(shape, dtype=rasterio.ubyte)
image[5:15, 5:15] = 1
image[1:3, 1:3] = 2
# Blank mask has no effect, only areas smaller than size will be
# removed
mask = numpy.ones(shape, dtype=rasterio.bool_)
sieved_image = ftrz.sieve(image, 100, mask=mask)
truth = numpy.zeros_like(image)
truth[5:15, 5:15] = 1
assert numpy.array_equal(sieved_image, truth)
# Only areas within the overlap of the mask and values will be kept
mask = numpy.ones(shape, dtype=rasterio.bool_)
mask[7:10, 7:10] = False
sieved_image = ftrz.sieve(image, 100, mask=mask)
truth = numpy.zeros_like(image)
truth[7:10, 7:10] = 1
assert numpy.array_equal(sieved_image, truth)
# mask of other type than rasterio.bool_ should fail
mask = numpy.zeros(shape, dtype=rasterio.uint8)
with pytest.raises(ValueError):
ftrz.sieve(image, 100, mask=mask)
示例12: test_sieve
def test_sieve():
"""Test sieving a 10x10 feature from an ndarray."""
image = numpy.zeros((20, 20), dtype=rasterio.ubyte)
image[5:15, 5:15] = 1
# An attempt to sieve out features smaller than 100 should not change the
# image.
with rasterio.drivers():
sieved_image = ftrz.sieve(image, 100)
assert numpy.array_equal(sieved_image, image)
# Setting the size to 100 should leave us an empty, False image.
with rasterio.drivers():
sieved_image = ftrz.sieve(image, 101)
assert not sieved_image.any()
示例13: visualize_labels
def visualize_labels(geo_tiff, nlcd):
"""Make a picture with color-coded labels as pixels
:param geo_tiff: path to GeoTiff file
:param nlcd: path to NLCD .img file
"""
print "Getting labels..."
labels = get_labels_tif(geo_tiff, nlcd)
with rasterio.drivers():
with rasterio.open(geo_tiff) as src:
width = src.width
height = src.height
rgb = np.zeros((height, width, 3))
print "Getting colors for labels..."
for col in range(0, width):
for row in range(0, height):
label = labels[row + col*height]
r, g, b = const.RGB_LABELS[label]
rgb[(row, col, 0)] = r
rgb[(row, col, 1)] = g
rgb[(row, col, 2)] = b
# show image
print "Showing image now..."
plt.imshow(rgb)
plt.show()
示例14: get_labels_lat_lon
def get_labels_lat_lon(coords, nlcd):
"""Gets the labels corresponding to coordinates
1. Transforms (latitude, longitude) to the coordinate reference system
used in the NLCD data set (Alber Conical Equal Area (ACEA))
2. Transforms ACEA coordinates to pixels in the raster data set
3. Queries the labels for those pixels
None if one of the indeces of the pixel is out-of-bounds
:param coords: list of (latitude, longitude) tuples
:param main_folder: path to folder where the data folder is found
:return: list: list containing the labels corresponding to each coordinate
None for coordinates not in the NLCD data set
"""
labels = []
# transform lat, lon to Albers Conical Equal Area (ACEA)
acea = pyproj.Proj(ACEA_PROJ4)
acea_coords = [(acea(lon, lat)) for lat, lon in coords]
# open NLCD raster data set
with rasterio.drivers():
with rasterio.open(nlcd) as src:
# linear transformation between ACEA coordinates and pixels
rev = ~src.affine
# transform ACEA to pixel coordinates
pixels = [tuple(int(round(i)) for i in rev*coord) for coord in acea_coords]
for col, row in pixels:
if col < 0 or col >= src.width or row < 0 or row >= src.height:
labels.append(None)
else:
window = ((row, row+1), (col, col+1))
labels.append(src.read(1, window=window)[0,0])
return labels
示例15: test_rasterize_invalid_out_dtype
def test_rasterize_invalid_out_dtype(basic_geometry):
""" A non-supported data type for out should raise an exception """
out = numpy.zeros(DEFAULT_SHAPE, dtype=numpy.int64)
with rasterio.drivers():
with pytest.raises(ValueError):
rasterize([basic_geometry], out=out)