我想:
1
,字段外的像素设置为0
Cde:
import fiona
import rasterio
import rasterio.mask
import pycrs
def masked_raster(input_file, raster_file):
# Create a masked version of the input raster where pixels falling within one of the fields are set to `1` and pixels outside the fields are set to `0`
data = rasterio.open(raster_file)
#creating the a bounding box with Shapely
## WGS84 coordinates
minx, miny = 24.60, 60.00
maxx, maxy = 25.22, 60.35
bbox = box(minx, miny, maxx, maxy)
#inserting the bounding box into GeoDataFrame
geo = geopandas.GeoDataFrame({'geometry': bbox}, index=[0], crs=from_epsg(4326))
#Re-project into the same coordinate system as the raster data
geo = geo.to_crs(crs=data.crs.data)
#get the coordinates of the geometry in a proper format of rasterio
def getFeatures(gdf):
"""Function to parse features from GeoDataFrame in such a manner that rasterio wants them"""
import json
return [json.loads(gdf.to_json())['features'][0]['geometry']]
#Getting the geometry coordinates by using the function
coordinates = getFeatures(geo)
# mask to clip the raster with the polygon using the coords variable
out_img, out_transform = mask(data, shapes=coordinates, crop=True)
out_img = rasterio.open(raster_file).read()
return out_img
def reproject_raster(raster_file, dst_crs):
# Reproject the input raster to the provided CRS
src = rasterio.open(raster_file)
# Parse EPSG code
epsg_code = int(data.crs.data['init'][5:])
#copy metadata
out_meta = raster_file.meta.copy()
#update the metadata with new dimensions, transform (affine) and CRS
out_meta.update({"driver": "GTiff", "height": out_img.shape[1], "width": out_img.shape[2], "transform": out_transform, "crs": pycrs.parser.from_epsg_code(epsg_code).to_proj4()})
#save the clipped raster to disk
with rasterio.open(out_tif, "w", **out_meta) as dst:
dst.write(out_img)
dst = src
return dst
# Run this to validate your function works correctly
assert masked_raster('crops.geojson', 'crops.tif')[0].sum() == 1144636.0, "Sorry wrong answer"
assert str(reproject_raster('crops.tif', 'EPSG:4326').crs) == 'EPSG:4326', "Sorry wrong answer"
print("Congratulations, all is working just fine !!!")
谢谢大家,我设法找到了解决我错误的方法: rasterio.tools.mask.mask(在较新的版本中,它是rasterio.mask.mask)包括一个选项invert。当invert=True时,该掩码将应用于与形状重叠的像素,而不是形状外部的区域
所以我改变了:
致:
错误已修复。这是我重写的完整代码。虽然我没有得到预期的输出,但是没有错误,这只是它必须满足断言要求的部分,必须被修复
相关问题 更多 >
编程相关推荐