Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def uninvertable_reproject_params():
return ReprojectParams(
left=-120,
bottom=30,
right=-80,
top=70,
width=80,
height=80,
src_crs=CRS.from_epsg(4326),
dst_crs=CRS.from_epsg(26836),
)
def default_reproject_params():
return ReprojectParams(
left=-120,
bottom=30,
right=-80,
top=70,
width=80,
height=80,
src_crs=CRS.from_epsg(4326),
dst_crs=CRS.from_epsg(2163),
)
def test_environ_patch(gdalenv, monkeypatch):
"""PROJ_LIB is patched when rasterio._crs is imported"""
monkeypatch.delenv('GDAL_DATA', raising=False)
monkeypatch.delenv('PROJ_LIB', raising=False)
with env_ctx_if_needed():
assert CRS.from_epsg(4326) != CRS(units='m', proj='aeqd', ellps='WGS84', datum='WGS84', lat_0=-17.0, lon_0=-44.0)
def test_calculate_default_transform_dimensions():
with rasterio.open("tests/data/RGB.byte.tif") as src:
dst_width, dst_height = (113, 103)
target_transform = Affine(
0.02108612597535966,
0.0,
-78.95864996545055,
0.0,
-0.0192823863230055,
25.550873767433984,
)
dst_transform, width, height = calculate_default_transform(
src.crs,
CRS.from_epsg(4326),
src.width,
src.height,
*src.bounds,
dst_width=dst_width,
dst_height=dst_height
)
assert dst_transform.almost_equals(target_transform)
assert width == dst_width
assert height == dst_height
dst_transform, width, height = calculate_default_transform(
self.src.crs, CRS.from_epsg(self.dest_crs),
self.src.width, self.src.height, *tb,
dst_height=self.dest_tile_size[0],
dst_width=self.dest_tile_size[1])
tile_data = np.zeros(shape=(src_data.shape[0], height, width),
dtype=src_data.dtype)
rasterio.warp.reproject(
source=src_data,
destination=tile_data,
src_transform=self.src.window_transform(window),
src_crs=self.src.crs,
dst_transform=dst_transform,
dst_crs=CRS.from_epsg(self.dest_crs),
resampling=getattr(Resampling, self.resampling))
if self.nodata:
mask = np.all(tile_data != nodata,
axis=0).astype(np.uint8) * 255
elif self.alpha:
mask = self.src.read(self.alpha, window=window,
resampling=getattr(Resampling,
self.resampling))
else:
mask = None # placeholder
# else:
# tile_data, mask, window, aff_xform = read_cog_tile(
# src=self.src,
# bounds=tb,
def feature_to_mercator(feature):
"""Normalize feature and converts coords to 3857.
Args:
feature: geojson feature to convert to mercator geometry.
"""
# Ref: https://gist.github.com/dnomadb/5cbc116aacc352c7126e779c29ab7abe
src_crs = CRS.from_epsg(4326)
dst_crs = CRS.from_epsg(3857)
geometry = feature["geometry"]
if geometry["type"] == "Polygon":
xys = (zip(*part) for part in geometry["coordinates"])
xys = (list(zip(*transform(src_crs, dst_crs, *xy))) for xy in xys)
yield {"coordinates": list(xys), "type": "Polygon"}
elif geometry["type"] == "MultiPolygon":
for component in geometry["coordinates"]:
xys = (zip(*part) for part in component)
xys = (list(zip(*transform(src_crs, dst_crs, *xy))) for xy in xys)
yield {"coordinates": list(xys), "type": "Polygon"}
def _reproject(input_data, input_type, input_crs, target_crs, dest_path,
resampling_method='bicubic'):
if input_type == 'vector':
output = input_data.to_crs(epsg=target_crs)
if dest_path is not None:
output.to_file(dest_path, driver='GeoJSON')
elif input_type == 'raster':
if isinstance(input_data, rasterio.DatasetReader):
transform, width, height = calculate_default_transform(
CRS.from_epsg(input_crs), CRS.from_epsg(target_crs),
input_data.width, input_data.height, *input_data.bounds
)
kwargs = input_data.meta.copy()
kwargs.update({'crs': target_crs,
'transform': transform,
'width': width,
'height': height})
if dest_path is not None:
with rasterio.open(dest_path, 'w', **kwargs) as dst:
for band_idx in range(1, input_data.count + 1):
rasterio.warp.reproject(
source=rasterio.band(input_data, band_idx),
destination=rasterio.band(dst, band_idx),
src_transform=input_data.transform,
src_crs=input_data.crs,
from rasterio import transform, warp, windows
from rasterio._err import CPLE_OutOfMemoryError
from rasterio.crs import CRS
from rasterio.enums import ColorInterp, MaskFlags
from rasterio.features import geometry_mask
from rasterio.transform import Affine, from_bounds
from rasterio.vrt import WarpedVRT
from rasterio.warp import Resampling, transform_geom
from . import mosaic
from .stats import Timer
from .utils import Bounds, PixelCollection
EARTH_RADIUS = 6378137
WEB_MERCATOR_CRS = CRS.from_epsg(3857)
WGS84_CRS = CRS.from_epsg(4326)
LOG = logging.getLogger(__name__)
EXTENTS = {
str(WEB_MERCATOR_CRS): (
-math.pi * EARTH_RADIUS,
-math.pi * EARTH_RADIUS,
math.pi * EARTH_RADIUS,
math.pi * EARTH_RADIUS,
),
str(WGS84_CRS): (
math.degrees(-math.pi),
math.degrees(-math.pi / 2),
math.degrees(math.pi),
math.degrees(math.pi / 2),
),
}
Args:
array (numpy array, required):
three band array of RGB values of an image
bbox (tuple, required):
lon/lat bounding box for image in the form (lon_min, lat_min, lon_max, lat_max)
file_path (string, required):
file path to save the GeoTiff to
"""
bbox = np.array(bbox).reshape(2, 2)
bbox = ccrs.GOOGLE_MERCATOR.transform_points(ccrs.PlateCarree(), bbox[:, 0], bbox[:, 1]).reshape(6)
bbox = bbox[0], bbox[1], bbox[3], bbox[4]
count, height, width = array.shape
indexes = list(range(1, count + 1))
transform = rasterio.transform.from_bounds(*bbox, width=width, height=height)
crs = rasterio.crs.CRS.from_epsg(WMTS_EPSG)
with rasterio.open(file_path, 'w', driver='GTiff', height=height,
width=width, count=count, dtype=array.dtype,
crs=crs, transform=transform) as dst:
dst.write(array, indexes=indexes)
def save_to_raster(array_2d,height,width,xll_lon,yll_lon,res,no_data,output):
# save to an image
with rasterio.Env():
# Write an array as a raster band to a new 8-bit file. For
# the new file's profile, we start with the profile of the source
# profile = src.profile
crs = rasterio.crs.CRS.from_epsg(4326) # WGS 84,
x_left_top = xll_lon
y_left_top = yll_lon + res*height
profile = {'driver': 'GTiff', 'nodata': no_data, 'width': width, 'height': height, 'count': 1,
'crs': crs,
'transform': (x_left_top, res, 0.0, y_left_top , 0.0, -res),
}
# And then change the band count to 1, set the
# dtype to uint8, and specify LZW compression.
profile.update(
dtype=rasterio.float32,
count=1,
compress='lzw')
with rasterio.open(output, 'w', **profile) as dst:
dst.write(array_2d.astype(rasterio.float32), 1)