使用gee-py接口 根据shp矢量批量下载多个月份的哨兵数据
import os
import ee
import shapefile
ee.Initialize()
def out_districts(shp_file):
shp_name = os.path.basename(shp_file)
shp_name_without_ext = os.path.splitext(shp_name)[0]
shp_reader = shapefile.Reader(shp_file)
records = shp_reader.records()
fields = shp_reader.fields[1:]
field_names = [field[0] for field in fields]
data = []
for row in records:
attributes = {}
for i, value in enumerate(row):
attributes[field_names[i]] = value
data.append({"type": "Feature", "properties": attributes})
shapes = shp_reader.shapes()
for i in range(len(shapes)):
polygon = shapes[i].points
geometry = ee.Geometry.Polygon(polygon)
data[i]["geometry"] = geometry
geometry = ee.FeatureCollection(data)
districts = {"name": shp_name_without_ext, "geometry": geometry}
return districts
def clipImage(image, geometry):
return image.clip(geometry)
def maskS2clouds(image):
qa = image.select("QA60")
cloudBitMask = 1 << 10
cirrusBitMask = 1 << 11
mask = qa.bitwiseAnd(cloudBitMask).eq(0) and (qa.bitwiseAnd(cirrusBitMask).eq(0))
return image.updateMask(mask)
def down_sentinel(district, timePeriod):
districtGeometry = district["geometry"]
geometries = districtGeometry.toList(districtGeometry.size())
for k in range(geometries.size().getInfo()):
geometry = ee.Feature(geometries.get(k)).geometry()
for j in range(len(timePeriods)):
timePeriod = timePeriods[j]
startDate = ee.Date(timePeriod["start"])
endDate = ee.Date(timePeriod["end"])
desc = f"{district['name']}_geom{k}_month{timePeriod['name']}"
image = (
ee.ImageCollection("COPERNICUS/S2_SR")
.filterDate(startDate, endDate)
.filterBounds(geometry)
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 10))
.map(maskS2clouds)
.select(["B2", "B3", "B4", "B8"])
.map(lambda image: image.clip(geometry))
.mosaic()
)
imageRgb = image.select(["B2", "B3", "B4"])
imageRgbUint8 = imageRgb.divide(4000.0).multiply(255).toByte()
imageNir = image.select(["B8"])
imageNirUint8 = imageNir.divide(8000.0).multiply(255).toByte()
imageBgrn = imageRgbUint8.addBands(imageNirUint8)
task = ee.batch.Export.image.toDrive(
image = imageBgrn,
description = desc,
folder = district['name'],
scale = 10,
maxPixels = 1e9,
region = geometry,
fileFormat = 'GeoTIFF'
)
task.start()
if __name__ == "__main__":
timePeriods = [
{"name": "4", "start": "2022-04-01", "end": "2022-04-30"},
{"name": "5", "start": "2022-05-01", "end": "2022-05-31"},
{"name": "6", "start": "2022-06-01", "end": "2022-06-30"},
{"name": "7", "start": "2022-07-01", "end": "2022-07-31"},
{"name": "8", "start": "2022-08-01", "end": "2022-08-31"},
{"name": "9", "start": "2022-09-01", "end": "2022-09-30"},
{"name": "10", "start": "2022-10-01", "end": "2022-10-31"},
]
shp_file = r"*****.shp"
district = out_districts(shp_file)
down_sentinel(district, timePeriod)