本文整理汇总了Python中rasterio.drivers函数的典型用法代码示例。如果您正苦于以下问题:Python drivers函数的具体用法?Python drivers怎么用?Python drivers使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了drivers函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:bolliger32,项目名称:snowpack_spatial_regression,代码行数:31,代码来源:pysalOutput_to_tiff.py
示例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
开发者ID:yuanshankongmeng,项目名称:rasterio,代码行数:8,代码来源:test_driver_management.py
示例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
开发者ID:KDOTGIS,项目名称:rasterio,代码行数:8,代码来源:test_driver_management.py
示例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')
开发者ID:valpasq,项目名称:yatsm,代码行数:14,代码来源:_gdal.py
示例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))
开发者ID:yukangguo,项目名称:rasterio,代码行数:35,代码来源:test_rio_features.py
示例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
开发者ID:harryjfowen,项目名称:landsat-util,代码行数:28,代码来源:ndvi.py
示例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)
开发者ID:aashish24,项目名称:rasterio,代码行数:35,代码来源:test_features.py
示例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
开发者ID:aashish24,项目名称:rasterio,代码行数:26,代码来源:test_features.py
示例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
开发者ID:AsgerPetersen,项目名称:rasterio,代码行数:25,代码来源:features.py
示例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
开发者ID:aashish24,项目名称:rasterio,代码行数:25,代码来源:test_rio_merge.py
示例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)
开发者ID:simudream,项目名称:rasterio,代码行数:29,代码来源:test_features_sieve.py
示例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()
开发者ID:simudream,项目名称:rasterio,代码行数:16,代码来源:test_features_sieve.py
示例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()
开发者ID:Planet-Labels,项目名称:Planet-Labels,代码行数:27,代码来源:handle_labels.py
示例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
开发者ID:Planet-Labels,项目名称:Planet-Labels,代码行数:32,代码来源:handle_labels.py
示例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)
开发者ID:aashish24,项目名称:rasterio,代码行数:7,代码来源:test_features.py
示例16: test_sieve_large
def test_sieve_large(basic_image):
"""
Setting the size larger than size of feature should leave us an empty image.
"""
with rasterio.drivers():
assert not numpy.any(sieve(basic_image, basic_image.sum() + 1))
开发者ID:aashish24,项目名称:rasterio,代码行数:7,代码来源:test_features.py
示例17: getFileGeoDict
def getFileGeoDict(cls,filename):
"""Get the spatial extent, resolution, and shape of grid inside ESRI grid file.
:param filename:
File name of ESRI grid file.
:returns:
- GeoDict specifying spatial extent, resolution, and shape of grid inside ESRI grid file.
- xvar array specifying X coordinates of data columns
- yvar array specifying Y coordinates of data rows
:raises DataSetException:
When the file contains a grid with more than one band.
"""
geodict = {}
with rasterio.drivers():
with rasterio.open(filename) as src:
aff = src.affine
geodict['xdim'] = aff.a
geodict['ydim'] = -1*aff.e
geodict['xmin'] = aff.xoff + geodict['xdim']/2.0
geodict['ymax'] = aff.yoff - geodict['ydim']/2.0
shp = src.shape
if len(shp) > 2:
raise DataSetException('Cannot support grids with more than one band')
geodict['nrows'] = src.height
geodict['ncols'] = src.width
geodict['xmax'] = geodict['xmin'] + (geodict['ncols']-1)*geodict['xdim']
geodict['ymin'] = geodict['ymax'] - (geodict['nrows']-1)*geodict['ydim']
xvar = np.arange(geodict['xmin'],geodict['xmax']+geodict['xdim'],geodict['xdim'])
yvar = np.arange(geodict['ymin'],geodict['ymax']+geodict['ydim'],geodict['ydim'])
return (geodict,xvar,yvar)
开发者ID:mhearne-usgs,项目名称:grid,代码行数:30,代码来源:gdal.py
示例18: main
def main(infile, outfile, with_threads=False):
with rasterio.drivers():
# Open the source dataset.
with rasterio.open(infile) as src:
# Create a destination dataset based on source params. The
# destination will be tiled, and we'll "process" the tiles
# concurrently.
meta = src.meta
del meta['transform']
meta.update(affine=src.affine)
meta.update(blockxsize=256, blockysize=256, tiled='yes')
with rasterio.open(outfile, 'w', **meta) as dst:
loop = asyncio.get_event_loop()
# With the exception of the ``yield from`` statement,
# process_window() looks like callback-free synchronous
# code. With a coroutine, we can keep the read, compute,
# and write statements close together for
# maintainability. As in the concurrent-cpu-bound.py
# example, all of the speedup is provided by
# distributing raster computation across multiple
# threads. The difference here is that we're submitting
# jobs to the thread pool asynchronously.
@asyncio.coroutine
def process_window(window):
# Read a window of data.
data = src.read(window=window)
# We run the raster computation in a separate thread
# and pause until the computation finishes, letting
# other coroutines advance.
#
# The _example.compute function modifies no Python
# objects and releases the GIL. It can execute
# concurrently.
result = numpy.zeros(data.shape, dtype=data.dtype)
if with_threads:
yield from loop.run_in_executor(
None, compute, data, result)
else:
compute(data, result)
# Write the result.
for i, arr in enumerate(result, 1):
dst.write_band(i, arr, window=window)
# Queue up the loop's tasks.
tasks = [asyncio.Task(process_window(window))
for ij, window in dst.block_windows(1)]
# Wait for all the tasks to finish, and close.
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
开发者ID:AsgerPetersen,项目名称:rasterio,代码行数:60,代码来源:async-rasterio.py
示例19: pixelated_image_file
def pixelated_image_file(tmpdir, pixelated_image):
"""
A basic raster file with a 10x10 array for testing sieve functions.
Contains data from pixelated_image.
Returns
-------
string
Filename of test raster file
"""
from affine import Affine
import rasterio
image = pixelated_image
outfilename = str(tmpdir.join('pixelated_image.tif'))
kwargs = {
"crs": {'init': 'epsg:4326'},
"transform": Affine.identity(),
"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)
return outfilename
开发者ID:aashish24,项目名称:rasterio,代码行数:33,代码来源:conftest.py
示例20: test_reproject_dst_nodata_default
def test_reproject_dst_nodata_default():
"""
If nodata is not provided, destination will be filled with 0
instead of nodata
"""
params = default_reproject_params()
with rasterio.drivers():
source = numpy.ones((params.width, params.height), dtype=numpy.uint8)
out = numpy.zeros((params.dst_width, params.dst_height),
dtype=source.dtype)
out.fill(120) # Fill with arbitrary value
reproject(
source,
out,
src_transform=params.src_transform,
src_crs=params.src_crs,
dst_transform=params.dst_transform,
dst_crs=params.dst_crs
)
assert (out == 1).sum() == 4461
assert (out == 0).sum() == (params.dst_width *
params.dst_height - 4461)
开发者ID:clembou,项目名称:rasterio,代码行数:26,代码来源:test_warp.py
注:本文中的rasterio.drivers函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论