repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
liuxb555/earthengine-py-examples
Join/intersect.py
<filename>Join/intersect.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def intersect(state): nPowerPlants = ee.List(state.get('power_plants')).size() # Return the state feature with a new property: power plant count. return state.set('n_power_plants', nPowerPlants) # Load the primary 'collection': US state boundaries. states = ee.FeatureCollection('TIGER/2018/States') # Load the secondary 'collection': power plants. powerPlants = ee.FeatureCollection('WRI/GPPD/power_plants') # Define a spatial filter as geometries that intersect. spatialFilter = ee.Filter.intersects(**{ 'leftField': '.geo', 'rightField': '.geo', 'maxError': 10 }) # Define a save all join. saveAllJoin = ee.Join.saveAll(**{ 'matchesKey': 'power_plants', }) # Apply the join. intersectJoined = saveAllJoin.apply(states, powerPlants, spatialFilter) # Add power plant count per state as a property. intersectJoined = intersectJoined.map(intersect) # intersectJoined = intersectJoined.map(function(state) { # # Get "power_plant" intersection list, count how many intersected this state. # nPowerPlants = ee.List(state.get('power_plants')).size() # # Return the state feature with a new property: power plant count. # return state.set('n_power_plants', nPowerPlants) # }) print(intersectJoined.getInfo()) # # Make a bar chart for the number of power plants per state. # chart = ui.Chart.feature.byFeature(intersectJoined, 'NAME', 'n_power_plants') \ # .setChartType('ColumnChart') \ # .setSeriesNames({n_power_plants: 'Power plants'}) \ # .setOptions({ # title: 'Power plants per state', # hAxis: {title: 'State'}, # vAxis: {title: 'Frequency'}}) # # Print the chart to the console. # print(chart) # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/hydrosheds_dem.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('WWF/HydroSHEDS/03CONDEM') elevation = dataset.select('b1') elevationVis = { 'min': -50.0, 'max': 3000.0, 'gamma': 2.0, } Map.setCenter(-121.652, 38.022, 8) Map.addLayer(elevation, elevationVis, 'Elevation') dataset = ee.Image('WWF/HydroSHEDS/03VFDEM') elevation = dataset.select('b1') elevationVis = { 'min': -50.0, 'max': 3000.0, 'gamma': 2.0, } Map.setCenter(-121.652, 38.022, 8) Map.addLayer(elevation, elevationVis, 'Elevation Void Filled') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Water/glcf_global_inland_water.py
<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.ImageCollection('GLCF/GLS_WATER') water = dataset.select('water').mosaic() waterVis = { 'min': 1.0, 'max': 4.0, 'palette': ['FAFAFA', '00C5FF', 'DF73FF', '828282', 'CCCCCC'], } Map.setCenter(-79.3094, 44.5693, 8) Map.addLayer(water, waterVis, 'Water') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/metadata_aggregation.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def cal_area(feature): num = ee.Number.parse(feature.get('areasqkm')) return feature.set('areasqkm', num) # Load watersheds from a data table. sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06') \ .filterBounds(ee.Geometry.Rectangle(-127.18, 19.39, -62.75, 51.29)) \ .map(cal_area) # Display the table and print its first element. # Map.addLayer(sheds, {}, 'watersheds') Map.addLayer(ee.Image().paint(sheds, 1, 2), {}, 'watersheds') print('First watershed', sheds.first().getInfo()) # Print the number of watersheds. print('Count:', sheds.size().getInfo()) # Print stats for an area property. # print('Area stats:', sheds.aggregate_stats('areasqkm').getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Algorithms/resampling.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat image over San Francisco, California, UAS. landsat = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20160323') # Set display and visualization parameters. Map.setCenter(-122.37383, 37.6193, 15) visParams = {'bands': ['B4', 'B3', 'B2'], 'max': 0.3} # Display the Landsat image using the default nearest neighbor resampling. # when reprojecting to Mercator for the Code Editor map. Map.addLayer(landsat, visParams, 'original image') # Force the next reprojection on this image to use bicubic resampling. resampled = landsat.resample('bicubic') # Display the Landsat image using bicubic resampling. Map.addLayer(resampled, visParams, 'resampled') # Display the map. Map
liuxb555/earthengine-py-examples
Image/expressions.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 8 image. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') # Compute the EVI using an expression. evi = image.expression( '2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', { 'NIR': image.select('B5'), 'RED': image.select('B4'), 'BLUE': image.select('B2') }) Map.centerObject(image, 9) Map.addLayer(evi, {'min': -1, 'max': 1, 'palette': ['FF0000', '00FF00']}, "EVI") # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/filtering_by_calendar_range.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) roi = ee.Geometry.Point([-99.2182, 46.7824]) # find images acquired during June and July collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \ .filterBounds(roi) \ .filter(ee.Filter.calendarRange(6, 7, 'month')) \ .sort('DATE_ACQUIRED') print(collection.size().getInfo()) first = collection.first() propertyNames = first.propertyNames() print(propertyNames.getInfo()) time_start = ee.Date(first.get('system:time_start')).format("YYYY-MM-dd") print(time_start.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/column_statistics_multiple.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) fromFT = ee.FeatureCollection("users/wqs/Pipestem/Pipestem_HUC10") geom = fromFT.geometry() Map.centerObject(fromFT) Map.addLayer(ee.Image().paint(geom, 0, 2), {}, 'Watersheds') stats = fromFT.reduceColumns(**{ 'reducer': ee.Reducer.sum().repeat(2), 'selectors': ['AreaSqKm', 'AreaAcres'] # weightSelectors: ['weight'] }).getInfo() print(stats) # Display the map. Map
liuxb555/earthengine-py-examples
Image/conditional_operations.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 8 image. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') # Create NDVI and NDWI spectral indices. ndvi = image.normalizedDifference(['B5', 'B4']) ndwi = image.normalizedDifference(['B3', 'B5']) # Create a binary layer using logical operations. bare = ndvi.lt(0.2).And(ndwi.lt(0)) # Mask and display the binary layer. Map.setCenter(-122.3578, 37.7726, 12) Map.setOptions('satellite') Map.addLayer(bare.updateMask(bare), {}, 'bare') # Display the map. Map
liuxb555/earthengine-py-examples
AssetManagement/export_table.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) fromFT = ee.FeatureCollection('ft:1CLldB-ULPyULBT2mxoRNv7enckVF0gCQoD2oH7XP') polys = fromFT.geometry() centroid = polys.centroid() lng, lat = centroid.getInfo()['coordinates'] # print("lng = {}, lat = {}".format(lng, lat)) # Map.setCenter(lng, lat, 10) # Map.addLayer(fromFT) count = fromFT.size().getInfo() Map.setCenter(lng, lat, 10) for i in range(2, 2 + count): fc = fromFT.filter(ee.Filter.eq('system:index', str(i))) Map.addLayer(fc) # Display the map. Map
liuxb555/earthengine-py-examples
Gena/map_get_center.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # add some data to the Map dem = ee.Image("AHN/AHN2_05M_RUW") Map.addLayer(dem, {'min': -5, 'max': 50, 'palette': ['000000', 'ffffff'] }, 'DEM', True) # zoom in somewhere Map.setCenter(4.4585, 52.0774, 14) # TEST center= Map.getCenter() # add bounds to the map Map.addLayer(center, { 'color': 'red' }, 'center') # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/sort_by_cloud_and_date.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # This function masks the input with a threshold on the simple cloud score. def cloudMask(img): cloudscore = ee.Algorithms.Landsat.simpleCloudScore(img).select('cloud') return img.updateMask(cloudscore.lt(50)) # Load a Landsat 5 image collection. collection = ee.ImageCollection('LANDSAT/LT5_L1T_TOA') \ .filterDate('2008-04-01', '2010-04-01') \ .filterBounds(ee.Geometry.Point(-122.2627, 37.8735)) \ .map(cloudMask) \ .select(['B4', 'B3']) \ .sort('system:time_start', True) #Sort the collection in chronological order. print(collection.size().getInfo()) first = collection.first().get('system:id') print(first.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
NAIP/ndwi_timeseries.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def subsetNAIP(img_col, startTime, endTime, fc): img = img_col.filterDate(startTime, endTime).filterBounds(fc).mosaic().clip(fc) return img def calNDWI(image, threshold): """A function to compute NDWI.""" ndwi = image.normalizedDifference(['G', 'N']) ndwiViz = {'min': 0, 'max': 1, 'palette': ['00FFFF', '0000FF']} ndwiMasked = ndwi.updateMask(ndwi.gte(threshold)) ndwi_bin = ndwiMasked.gt(0) patch_size = ndwi_bin.connectedPixelCount(500, True) large_patches = patch_size.eq(500) large_patches = large_patches.updateMask(large_patches) opened = large_patches.focal_min(1).focal_max(1) return opened def rasterToVector(img, fc): vec = img.reduceToVectors(geometry=fc, eightConnected=True, maxPixels=59568116121, crs=img.projection(), scale=1) return vec def exportToDrive(vec, filename): taskParams = { 'driveFolder': 'image', 'fileFormat': 'KML' } task = ee.batch.Export.table(vec, filename, taskParams) task.start() years = [2014] threshold = 0.3 # years = [2003, 2004, 2005, 2006, 2009, 2010, 2012, 2014, 2015] collection = ee.ImageCollection('USDA/NAIP/DOQQ') fromFT = ee.FeatureCollection('ft:1CLldB-ULPyULBT2mxoRNv7enckVF0gCQoD2oH7XP') # count = fromFT.size().getInfo() # print(count) polys = fromFT.geometry() centroid = polys.centroid() lng, lat = centroid.getInfo()['coordinates'] # print("lng = {}, lat = {}".format(lng, lat)) values = fromFT.reduceColumns(ee.Reducer.toList(2), ['system:index', 'name']).getInfo()['list'] # print(values) # Map.setCenter(lng, lat, 10) vis = {'bands': ['N', 'R', 'G']} for year in years: # year = 2015 startTime = ee.Date(str(year) + '-01-01') endTime = ee.Date(str(year) + '-12-31') # year = startTime.get('year').getInfo() # print(year) for (id, name) in values: watershed = fromFT.filter(ee.Filter.eq('system:index', str(id))) filename = "Y" + str(year) + "_" + str(id) + "_" + str(name).replace(" ", "_") print(filename) image = subsetNAIP(collection, startTime, endTime, watershed) ndwi = calNDWI(image, threshold) vector = rasterToVector(ndwi, watershed) exportToDrive(vector, filename) # Map.addLayer(image, vis) # Map.addLayer(vector) # for i in range(2, 2 + count): # watershed = fromFT.filter(ee.Filter.eq('system:index', str(i))) # re = fc.filterBounds(watershed) # task = ee.batch.Export.table(re, 'watershed-' + str(i), taskParams) # task.start() # # # # lng_lat = ee.Geometry.Point(lng, lat) # naip = collection.filterBounds(polys) # naip_2015 = naip.filterDate('2015-01-01', '2015-12-31') # ppr = naip_2015.mosaic() # # count = naip_2015.size().getInfo() # print("Count: ", count) # # # print(naip_2015.size().getInfo()) # vis = {'bands': ['N', 'R', 'G']} # Map.setCenter(lng, lat, 12) # Map.addLayer(ppr,vis) # # Map.addLayer(polys) # # def NDWI(image): # """A function to compute NDWI.""" # ndwi = image.normalizedDifference(['G', 'N']) # ndwiViz = {'min': 0, 'max': 1, 'palette': ['00FFFF', '0000FF']} # ndwiMasked = ndwi.updateMask(ndwi.gte(0.05)) # ndwi_bin = ndwiMasked.gt(0) # patch_size = ndwi_bin.connectedPixelCount(500, True) # large_patches = patch_size.eq(500) # large_patches = large_patches.updateMask(large_patches) # opened = large_patches.focal_min(1).focal_max(1) # return opened # # ndwi_collection = naip_2015.map(NDWI) # # Map.addLayer(ndwi_collection) # # print(ndwi_collection.getInfo()) # # # downConfig = {'scale': 10, "maxPixels": 1.0E13, 'driveFolder': 'image'} # scale means resolution. # # img_lst = ndwi_collection.toList(100) # # # # taskParams = { # # 'driveFolder': 'image', # # 'driveFileNamePrefix': 'ndwi', # # 'fileFormat': 'KML' # # } # # # # for i in range(0, count): # # image = ee.Image(img_lst.get(i)) # # name = image.get('system:index').getInfo() # # print(name) # # # task = ee.batch.Export.image(image, "ndwi2-" + name, downConfig) # # # task.start() # # mosaic = ndwi_collection.mosaic().clip(polys) # fc = mosaic.reduceToVectors(eightConnected=True, maxPixels=59568116121, crs=mosaic.projection(), scale=1) # # Map.addLayer(fc) # taskParams = { # 'driveFolder': 'image', # 'driveFileNamePrefix': 'water', # 'fileFormat': 'KML' # } # # count = fromFT.size().getInfo() # Map.setCenter(lng, lat, 10) # # for i in range(2, 2 + count): # watershed = fromFT.filter(ee.Filter.eq('system:index', str(i))) # re = fc.filterBounds(watershed) # # task = ee.batch.Export.table(re, 'watershed-' + str(i), taskParams) # # task.start() # # Map.addLayer(fc) # # # # lpc = fromFT.filter(ee.Filter.eq('name', 'Little Pipestem Creek')) # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/us_physiography.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('CSP/ERGo/1_0/US/physiography') physiography = dataset.select('constant') physiographyVis = { 'min': 1100.0, 'max': 4220.0, } Map.setCenter(-105.4248, 40.5242, 8) Map.addLayer(physiography, physiographyVis, 'Physiography') # Display the map. Map
liuxb555/earthengine-py-examples
Gena/map_center_object.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # get a single feature countries = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017") country = countries.filter(ee.Filter.eq('country_na', 'Ukraine')) Map.addLayer(country, { 'color': 'orange' }, 'feature collection layer') # TEST: center feature on a map Map.centerObject(country, 6) # Display the map. Map
liuxb555/earthengine-py-examples
Algorithms/landsat_path_row_limit.py
<filename>Algorithms/landsat_path_row_limit.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) point = ee.Geometry.Point(-98.7011, 47.2624) collection = ee.ImageCollection('LANDSAT/LC8_L1T_TOA') \ .filterBounds(point) \ .filterDate('2016-01-01', '2018-12-31') # print(collection) new_col = ee.Algorithms.Landsat.pathRowLimit(collection, 15, 100) # print(new_col) median = new_col.median() vis = {'bands': ['B5', 'B4', 'B3'], 'max': 0.3} Map.setCenter(-98.7011, 47.2624, 10) Map.addLayer(median, vis, 'Median') # Display the map. Map
liuxb555/earthengine-py-examples
GetStarted/09_a_complete_example.py
<filename>GetStarted/09_a_complete_example.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # This function gets NDVI from a Landsat 8 image. def addNDVI(image): return image.addBands(image.normalizedDifference(['B5', 'B4'])) # This function masks cloudy pixels. def cloudMask(image): clouds = ee.Algorithms.Landsat.simpleCloudScore(image).select(['cloud']) return image.updateMask(clouds.lt(10)) # Load a Landsat collection, map the NDVI and cloud masking functions over it. collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \ .filterBounds(ee.Geometry.Point([-122.262, 37.8719])) \ .filterDate('2014-03-01', '2014-05-31') \ .map(addNDVI) \ .map(cloudMask) # Reduce the collection to the mean of each pixel and display. meanImage = collection.reduce(ee.Reducer.mean()) vizParams = {'bands': ['B5_mean', 'B4_mean', 'B3_mean'], 'min': 0, 'max': 0.5} Map.setCenter(-122.262, 37.8719, 10) Map.addLayer(meanImage, vizParams, 'mean') # Load a region in which to compute the mean and display it. counties = ee.FeatureCollection('TIGER/2016/Counties') santaClara = ee.Feature(counties.filter( ee.Filter.eq('NAME', 'Santa Clara')).first()) Map.addLayer(ee.Image().paint(santaClara, 0, 2), { 'palette': 'yellow'}, 'Santa Clara') # Get the mean of NDVI in the region. mean = meanImage.select(['nd_mean']).reduceRegion(**{ 'reducer': ee.Reducer.mean(), 'geometry': santaClara.geometry(), 'scale': 30 }) # Print mean NDVI for the region. print('Santa Clara spring mean NDVI:', mean.get('nd_mean').getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Visualization/us_counties.py
<filename>Visualization/us_counties.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.FeatureCollection('TIGER/2018/Counties') visParams = { 'palette': ['purple', 'blue', 'green', 'yellow', 'orange', 'red'], 'min': 0, 'max': 50, 'opacity': 0.8, } # Turn the strings into numbers dataset = dataset.map(lambda f: f.set('STATEFP', ee.Number.parse(f.get('STATEFP')))) image = ee.Image().float().paint(dataset, 'STATEFP') countyOutlines = ee.Image().float().paint(**{ 'featureCollection': dataset, 'color': 'black', 'width': 1 }) Map.setCenter(-99.844, 37.649, 5) Map.addLayer(image, visParams, 'TIGER/2018/Counties') Map.addLayer(countyOutlines, {}, 'county outlines') # Map.addLayer(dataset, {}, 'for Inspector', False) # Display the map. Map
liuxb555/earthengine-py-examples
Image/symbology.py
<filename>Image/symbology.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) cover = ee.Image('MODIS/051/MCD12Q1/2012_01_01').select('Land_Cover_Type_1') igbpPalette = [ 'aec3d4', '152106', '225129', '369b47', '30eb5b', '387242', '6a2325', 'c3aa69', 'b76031', 'd9903d', '91af40', '111149', 'cdb33b', 'cc0013', '33280d', 'd7cdcc', 'f7e084', '6f6f6f' ] Map.setCenter(-99.229, 40.413, 5) Map.addLayer(cover, {'min': 0, 'max': 17, 'palette': igbpPalette}, 'MODIS Land Cover') # Display the map. Map
liuxb555/earthengine-py-examples
Visualization/landsat_symbology.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) geometry = ee.Geometry.Point([-122.30287513732901, 37.441115780341605]) landsat = ee.ImageCollection("LANDSAT/LC08/C01/T1") \ .filterDate('2016-01-01', '2017-01-01') \ .filterBounds(geometry) composite = ee.Algorithms.Landsat.simpleComposite(**{ 'collection': landsat, 'asFloat': True }) rgbVis = {'bands': ["B4", "B3", "B2"], 'min':0, 'max': 0.3} nirVis = {'bands': ["B5", "B4", "B3"], 'min':0, 'max': [0.5, 0.3, 0.3]} tempVis = {'bands': ["B10"], 'min': 280, 'max': 310, 'palette': ["blue", "red", "orange", "yellow"]} Map.addLayer(composite, rgbVis, "RGB") Map.addLayer(composite, nirVis, "False Color") Map.addLayer(composite, tempVis, "Thermal") Map.centerObject(ee.FeatureCollection(geometry), 10) # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/alos_global_dsm.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('JAXA/ALOS/AW3D30_V1_1') elevation = dataset.select('AVE') elevationVis = { 'min': 0.0, 'max': 4000.0, 'palette': ['0000ff', '00ffff', 'ffff00', 'ff0000', 'ffffff'], } Map.setCenter(136.85, 37.37, 4) Map.addLayer(elevation, elevationVis, 'Elevation') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/global_power_plant_database.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Visualization for WRI/GPPD/power_plants # https:#code.earthengine.google.com/9efbd726e4a8ba9b8b56ba94f1267678 table = ee.FeatureCollection("WRI/GPPD/power_plants") # Get a color from a fuel fuelColor = ee.Dictionary({ 'Coal': '000000', 'Oil': '593704', 'Gas': 'BC80BD', 'Hydro': '0565A6', 'Nuclear': 'E31A1C', 'Solar': 'FF7F00', 'Waste': '6A3D9A', 'Wind': '5CA2D1', 'Geothermal': 'FDBF6F', 'Biomass': '229A00' }) # List of fuels to add to the map fuels = ['Coal', 'Oil', 'Gas', 'Hydro', 'Nuclear', 'Solar', 'Waste', 'Wind', 'Geothermal', 'Biomass'] # /** # * Computes size from capacity and color from fuel type. # * # * @param {!ee.Geometry.Point} pt A point # * @return {!ee.Geometry.Point} Input point with added style dictionary. # */ def addStyle(pt): size = ee.Number(pt.get('capacitymw')).sqrt().divide(10).add(2) color = fuelColor.get(pt.get('fuel1')) return pt.set('styleProperty', ee.Dictionary({'pointSize': size, 'color': color})) # Make a FeatureCollection out of the power plant data table pp = ee.FeatureCollection(table).map(addStyle) # print(pp.first()) # /** # * Adds power plants of a certain fuel type to the map. # * # * @param {string} fuel A fuel type # */ def addLayer(fuel): # print(fuel) Map.addLayer(pp.filter(ee.Filter.eq('fuel1', fuel)).style({'styleProperty': 'styleProperty', 'neighborhood': 50}), {}, fuel, True, 0.65) # Apply `addLayer` to each record in `fuels` for fuel in fuels: Map.addLayer(pp.filter(ee.Filter.eq('fuel1', fuel)).style(**{'styleProperty': 'styleProperty', 'neighborhood': 50}), {}, fuel, True, 0.65) # Display the map. Map
liuxb555/earthengine-py-examples
Image/convolutions.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load and display an image. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') Map.setCenter(-121.9785, 37.8694, 11) Map.addLayer(image, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'input image') # Define a boxcar or low-pass kernel. # boxcar = ee.Kernel.square({ # 'radius': 7, 'units': 'pixels', 'normalize': True # }) boxcar = ee.Kernel.square(7, 'pixels', True) # Smooth the image by convolving with the boxcar kernel. smooth = image.convolve(boxcar) Map.addLayer(smooth, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'smoothed') # Define a Laplacian, or edge-detection kernel. laplacian = ee.Kernel.laplacian8(1, False) # Apply the edge-detection kernel. edgy = image.convolve(laplacian) Map.addLayer(edgy, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'edges') # Display the map. Map
liuxb555/earthengine-py-examples
Reducer/min_max_reducer.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load and filter the Sentinel-2 image collection. collection = ee.ImageCollection('COPERNICUS/S2') \ .filterDate('2016-01-01', '2016-12-31') \ .filterBounds(ee.Geometry.Point([-81.31, 29.90])) # Reduce the collection. extrema = collection.reduce(ee.Reducer.minMax()) # print(extrema.getInfo()) min_image = extrema.select(0) max_image = extrema.select(1) Map.setCenter(-81.31, 29.90, 10) Map.addLayer(min_image, {}, 'Min image') Map.addLayer(max_image, {}, 'Max image') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/us_census_roads.py
<reponame>liuxb555/earthengine-py-examples<filename>Datasets/Vectors/us_census_roads.py<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) fc = ee.FeatureCollection('TIGER/2016/Roads') Map.setCenter(-73.9596, 40.7688, 12) Map.addLayer(fc, {}, 'Census roads') # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/filtering_by_metadata.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) region = ee.Geometry.Polygon( [[[121.89674377441406, 11.91539248304918], [121.98291778564453, 11.93218823174339], [121.95236206054688, 12.020516709145957], [121.86378679003906, 12.006748772470699]]]) # Image Collection collection = ee.ImageCollection('COPERNICUS/S2') \ .filterDate('2017-03-01', '2017-04-04') \ .filterBounds(region) \ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 20) # Map.addLayer(collection, {'min': 0, 'max': 3000, # 'bands': ["B4", "B3", "B2"]}, 'TOA') print(collection.size().getInfo()) first = collection.first() Map.centerObject(first, 10) Map.addLayer(first, {'min': 0, 'max': 3000, 'bands': ["B4", "B3", "B2"]}, 'TOA') # Display the map. Map
liuxb555/earthengine-py-examples
Image/extract_value_to_points.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Input imagery is a cloud-free Landsat 8 composite. l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1') image = ee.Algorithms.Landsat.simpleComposite(**{ 'collection': l8.filterDate('2018-01-01', '2018-12-31'), 'asFloat': True }) # Use these bands for prediction. bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11'] # Load training points. The numeric property 'class' stores known labels. points = ee.FeatureCollection('GOOGLE/EE/DEMOS/demo_landcover_labels') # This property of the table stores the land cover labels. label = 'landcover' # Overlay the points on the imagery to get training. training = image.select(bands).sampleRegions(**{ 'collection': points, 'properties': [label], 'scale': 30 }) # Define visualization parameters in an object literal. vizParams = {'bands': ['B5', 'B4', 'B3'], 'min': 0, 'max': 1, 'gamma': 1.3} Map.centerObject(points, 10) Map.addLayer(image, vizParams, 'Image') Map.addLayer(points, {'color': "yellow"}, 'Training points') first = training.first() print(first.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/count_features.py
#!/usr/bin/env python """Count features example. Count Panoramio photos near SF that mention bridges. """ import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) Map.setCenter(-122.39, 37.7857, 12) photos_near_sf = ee.FeatureCollection('GOOGLE/EE/DEMOS/sf-photo-locations') bridge_photos = photos_near_sf.filter( ee.Filter().Or(ee.Filter.stringContains('title', 'Bridge'), ee.Filter.stringContains('title', 'bridge'))) Map.addLayer(photos_near_sf, {'color': '0040b0'}, "Photos near SF") Map.addLayer(bridge_photos, {'color': 'e02070'}, "Bridge photos") print ('There are %d bridge photos around SF.' % bridge_photos.size().getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Image/download.py
#!/usr/bin/env python """Download example.""" import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Get a download URL for an image. image1 = ee.Image('srtm90_v4') path = image1.getDownloadUrl({ 'scale': 30, 'crs': 'EPSG:4326', 'region': '[[-120, 35], [-119, 35], [-119, 34], [-120, 34]]' }) print(path) vis_params = {'min': 0, 'max': 3000} Map.addLayer(image1, vis_params) # Display the map. Map
liuxb555/earthengine-py-examples
Algorithms/landsat_surface_reflectance.py
<reponame>liuxb555/earthengine-py-examples<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # You can access pre-computed surface reflectance images directly from the SR collections. For example, to load a Landsat 7 surface reflectance image, use: srImage = ee.Image('LANDSAT/LE07/C01/T1_SR/LE07_044034_19990707') # The surface reflectance datasets for Collection 1 Landsat 4 through 7 are: surfaceReflectanceL4 = ee.ImageCollection('LANDSAT/LT04/C01/T1_SR') surfaceReflectanceL5 = ee.ImageCollection('LANDSAT/LT05/C01/T1_SR') surfaceReflectanceL7 = ee.ImageCollection('LANDSAT/LE07/C01/T1_SR') Map.centerObject(srImage, 9) Map.addLayer(srImage, {'bands': ['B4', 'B3', 'B2']}, 'Landsat Surface Reflectance') # Map.addLayer(srImage) # print(srImage.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Image/gradients.py
<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 8 image and select the panchromatic band. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8') # Compute the image gradient in the X and Y directions. xyGrad = image.gradient() # Compute the magnitude of the gradient. gradient = xyGrad.select('x').pow(2) \ .add(xyGrad.select('y').pow(2)).sqrt() # Compute the direction of the gradient. direction = xyGrad.select('y').atan2(xyGrad.select('x')) # Display the results. Map.setCenter(-122.054, 37.7295, 10) Map.addLayer(direction, {'min': -2, 'max': 2}, 'direction') Map.addLayer(gradient, {'min': -7, 'max': 7}, 'gradient') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/resolve_ecoregions.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def set_color(f): c = ee.String(f.get('COLOR')).slice(1) return f \ .set('R', ee.Number.parse(c.slice(0, 2), 16)) \ .set('G', ee.Number.parse(c.slice(2, 4), 16)) \ .set('B', ee.Number.parse(c.slice(4, 6), 16)) fc = ee.FeatureCollection('RESOLVE/ECOREGIONS/2017') \ .map(lambda f: set_color(f)) base = ee.Image(0).mask(0).toInt8() Map.addLayer(base.paint(fc, 'R') .addBands(base.paint(fc, 'G') .addBands(base.paint(fc, 'B'))), {'gamma': 0.3}) # # Load a FeatureCollection from a table dataset: 'RESOLVE' ecoregions. # ecoregions = ee.FeatureCollection('RESOLVE/ECOREGIONS/2017') # # Display as default and with a custom color. # Map.addLayer(ecoregions, {}, 'default display', False) # Map.addLayer(ecoregions, {'color': 'FF0000'}, 'colored', False) # Map.addLayer(ecoregions.draw(**{'color': '006600', 'strokeWidth': 5}), {}, 'drawn', False) # # Create an empty image into which to paint the features, cast to byte. # empty = ee.Image().byte() # # Paint all the polygon edges with the same number and 'width', display. # outline = empty.paint(**{ # 'featureCollection': ecoregions, # 'color': 1, # 'width': 3 # }) # Map.addLayer(outline, {'palette': 'FF0000'}, 'edges') # Display the map. Map
liuxb555/earthengine-py-examples
Gena/hillshade_and_water.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) from ee_plugin.contrib import palettes dem = ee.Image("JAXA/ALOS/AW3D30_V1_1").select('MED') dem = dem.updateMask(dem.gt(0)) palette = palettes.cb['Pastel1'][7] #palette = ['black', 'white'] rgb = dem.visualize(**{'min': 0, 'max': 5000, 'palette': palette }) hsv = rgb.unitScale(0, 255).rgbToHsv() extrusion = 30 weight = 0.7 hs = ee.Terrain.hillshade(dem.multiply(extrusion), 315, 35).unitScale(10, 250).resample('bicubic') hs = hs.multiply(weight).add(hsv.select('value').multiply(1 - weight)) hsv = hsv.addBands(hs.rename('value'), ['value'], True) rgb = hsv.hsvToRgb() Map.addLayer(rgb, {}, 'ALOS DEM', True, 0.5) water_occurrence = ( ee.Image("JRC/GSW1_0/GlobalSurfaceWater") .select('occurrence') .divide(100) .unmask(0) .resample('bicubic') ) palette = ["ffffcc","ffeda0","fed976","feb24c","fd8d3c","fc4e2a","e31a1c","bd0026","800026"][::-1][1:] land = ee.Image("users/gena/land_polygons_image").mask() Map.addLayer(water_occurrence.mask(water_occurrence.multiply(2).multiply(land)), {'min': 0, 'max': 1, 'palette': palette}, 'water occurrence', True) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/add_area_column.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) fromFT = ee.FeatureCollection("users/wqs/Pipestem/Pipestem_HUC10") # This function computes the feature's geometry area and adds it as a property. def addArea(feature): return feature.set({'areaHa': feature.geometry().area().divide(100 * 100)}) # Map the area getting function over the FeatureCollection. areaAdded = fromFT.map(addArea) # Print the first feature from the collection with the added property. first = areaAdded.first() print('First feature: ', first.getInfo()) print("areaHa: ", first.get("areaHa").getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/select_by_attributes.py
#!/usr/bin/env python """Select by attributes """ import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Select North Dakota and South Dakota fc = ee.FeatureCollection('TIGER/2018/States') \ .filter(ee.Filter.Or( ee.Filter.eq('STUSPS', 'ND'), ee.Filter.eq('STUSPS', 'SD'), )) image = ee.Image().paint(fc, 0, 2) # Map.setCenter(-99.844, 37.649, 5) Map.centerObject(fc, 6) Map.addLayer(image, {'palette': 'FF0000'}, 'TIGER/2018/States') # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/convert_imagecollection_to_image.py
<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) images = ee.ImageCollection('MODIS/MCD43A4') \ .filterDate('2017-01-01', '2017-01-31') \ .select(['Nadir_Reflectance_Band1']) # unmask to ensure we have the same number of values everywhere images = images.map(lambda i: i.unmask(-1)) # convert to array array = images.toArray() # convert to an image bandNames = images.aggregate_array('system:index') image = array.arrayProject([0]).arrayFlatten([bandNames]) print(image.getInfo()) bandNames = image.bandNames() print(bandNames.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/srtm_topo_diversity.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('CSP/ERGo/1_0/Global/SRTM_topoDiversity') srtmTopographicDiversity = dataset.select('constant') srtmTopographicDiversityVis = { 'min': 0.0, 'max': 1.0, } Map.setCenter(-111.313, 39.724, 6) Map.addLayer( srtmTopographicDiversity, srtmTopographicDiversityVis, 'SRTM Topographic Diversity') # Display the map. Map
liuxb555/earthengine-py-examples
Image/rename_bands.py
<reponame>liuxb555/earthengine-py-examples<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image('LANDSAT/LC8_L1T/LC80260412017023LGN00') b5 = image.select('B5') Map.centerObject(image, 10) Map.addLayer(image, {}, 'Band 5') selected = image.select(["B5", 'B4', 'B3'], ['Nir', 'Red', 'Green']) Map.addLayer(selected, {}, "Renamed bands") print(selected.bandNames().getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Visualization/nwi_wetlands_symbology.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # NWI legend: https://www.fws.gov/wetlands/Data/Mapper-Wetlands-Legend.html def nwi_add_color(fc): emergent = ee.FeatureCollection( fc.filter(ee.Filter.eq('WETLAND_TY', 'Freshwater Emergent Wetland'))) emergent = emergent.map(lambda f: f.set( 'R', 127).set('G', 195).set('B', 28)) # print(emergent.first()) forested = fc.filter(ee.Filter.eq( 'WETLAND_TY', 'Freshwater Forested/Shrub Wetland')) forested = forested.map(lambda f: f.set('R', 0).set('G', 136).set('B', 55)) pond = fc.filter(ee.Filter.eq('WETLAND_TY', 'Freshwater Pond')) pond = pond.map(lambda f: f.set('R', 104).set('G', 140).set('B', 192)) lake = fc.filter(ee.Filter.eq('WETLAND_TY', 'Lake')) lake = lake.map(lambda f: f.set('R', 19).set('G', 0).set('B', 124)) riverine = fc.filter(ee.Filter.eq('WETLAND_TY', 'Riverine')) riverine = riverine.map(lambda f: f.set( 'R', 1).set('G', 144).set('B', 191)) fc = ee.FeatureCollection(emergent.merge( forested).merge(pond).merge(lake).merge(riverine)) base = ee.Image(0).mask(0).toInt8() img = base.paint(fc, 'R') \ .addBands(base.paint(fc, 'G') .addBands(base.paint(fc, 'B'))) return img fromFT = ee.FeatureCollection("users/wqs/Pipestem/Pipestem_HUC10") Map.addLayer(ee.Image().paint(fromFT, 0, 2), {}, 'Watershed') huc8_id = '10160002' nwi_asset_path = 'users/wqs/NWI-HU8/HU8_' + huc8_id + '_Wetlands' # NWI wetlands for the clicked watershed clicked_nwi_huc = ee.FeatureCollection(nwi_asset_path) nwi_color = nwi_add_color(clicked_nwi_huc) Map.centerObject(clicked_nwi_huc, 10) Map.addLayer(nwi_color, {'gamma': 0.3, 'opacity': 0.7}, 'NWI Wetlands Color') # Display the map. Map
liuxb555/earthengine-py-examples
Image/relational_operators.py
<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a 2012 nightlights image. nl2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012') lights = nl2012.select('stable_lights') # Define arbitrary thresholds on the 6-bit stable lights band. zones = lights.gt(30).add(lights.gt(55)).add(lights.gt(62)) # Display the thresholded image as three distinct zones near Paris. palette = ['000000', '0000FF', '00FF00', 'FF0000'] Map.setCenter(2.373, 48.8683, 8) Map.addLayer(zones, {'min': 0, 'max': 3, 'palette': palette}, 'development zones') # Create zones using an expression, display. zonesExp = nl2012.expression( "(b('stable_lights') > 62) ? 3" + ": (b('stable_lights') > 55) ? 2" + ": (b('stable_lights') > 30) ? 1" + ": 0" ) Map.addLayer(zonesExp, {'min': 0, 'max': 3, 'palette': palette}, 'development zones (ternary)') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/select_columns.py
<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) fc = ee.FeatureCollection('TIGER/2018/States') print(fc.first().getInfo()) new_fc = fc.select(['STUSPS', 'NAME', 'ALAND'], ['abbr', 'name', 'area']) print(new_fc.first().getInfo()) propertyNames = new_fc.first().propertyNames() print(propertyNames.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Array/array_sorting.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Define an arbitrary region of interest as a point. roi = ee.Geometry.Point(-122.26032, 37.87187) # Use these bands. bandNames = ee.List(['B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11']) # Load a Landsat 8 collection. collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \ .select(bandNames) \ .filterBounds(roi) \ .filterDate('2014-06-01', '2014-12-31') \ .map(lambda image: ee.Algorithms.Landsat.simpleCloudScore(image)) # Convert the collection to an array. array = collection.toArray() # Label of the axes. imageAxis = 0 bandAxis = 1 # Get the cloud slice and the bands of interest. bands = array.arraySlice(bandAxis, 0, bandNames.length()) clouds = array.arraySlice(bandAxis, bandNames.length()) # Sort by cloudiness. sorted = bands.arraySort(clouds) # Get the least cloudy images, 20% of the total. numImages = sorted.arrayLength(imageAxis).multiply(0.2).int() leastCloudy = sorted.arraySlice(imageAxis, 0, numImages) # Get the mean of the least cloudy images by reducing along the image axis. mean = leastCloudy.arrayReduce(**{ 'reducer': ee.Reducer.mean(), 'axes': [imageAxis] }) # Turn the reduced array image into a multi-band image for display. meanImage = mean.arrayProject([bandAxis]).arrayFlatten([bandNames]) Map.centerObject(ee.FeatureCollection(roi), 12) Map.addLayer(meanImage, {'bands': ['B5', 'B4', 'B2'], 'min': 0, 'max': 0.5}, 'Mean Image') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/map_function.py
<filename>FeatureCollection/map_function.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def addArea(feature): return feature.set({'areaHa': feature.geometry().area().divide(100 * 100)}) # Load watersheds from a data table. sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06') # This function computes the feature's geometry area and adds it as a property. # addArea = function(feature) { # return feature.set({areaHa: feature.geometry().area().divide(100 * 100)}) # } # Map the area getting function over the FeatureCollection. areaAdded = sheds.map(addArea) # Print the first feature from the collection with the added property. print('First feature:', areaAdded.first().getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Reducer/mean_std_image.py
<reponame>liuxb555/earthengine-py-examples<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 8 image. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318') # Combine the mean and standard deviation reducers. reducers = ee.Reducer.mean().combine(**{ 'reducer2': ee.Reducer.stdDev(), 'sharedInputs': True }) # Use the combined reducer to get the mean and SD of the image. stats = image.reduceRegion(**{ 'reducer': reducers, 'bestEffort': True, }) # Display the dictionary of band means and SDs. print(stats.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Visualization/image_clipping.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') centroid = image.geometry().centroid().coordinates() lon = centroid.get(0).getInfo() lat = centroid.get(1).getInfo() # Create an NDWI image, define visualization parameters and display. ndwi = image.normalizedDifference(['B3', 'B5']) ndwiViz = {'min': 0.5, 'max': 1, 'palette': ['00FFFF', '0000FF']} # Mask the non-watery parts of the image, where NDWI < 0.4. ndwiMasked = ndwi.updateMask(ndwi.gte(0.4)) # Create visualization layers. imageRGB = image.visualize(**{'bands': ['B5', 'B4', 'B3'], 'max': 0.5}) ndwiRGB = ndwiMasked.visualize(**{ 'min': 0.5, 'max': 1, 'palette': ['00FFFF', '0000FF'] }) # Mosaic the visualization layers and display (or export). mosaic = ee.ImageCollection([imageRGB, ndwiRGB]).mosaic() Map.setCenter(lon, lat, 10) Map.addLayer(mosaic, {}, 'mosaic', False) # Create a circle by drawing a 20000 meter buffer around a point. roi = ee.Geometry.Point([-122.4481, 37.7599]).buffer(20000) # Display a clipped version of the mosaic. Map.addLayer(mosaic.clip(roi), {}, "roi") # Display the map. Map
liuxb555/earthengine-py-examples
Reducer/stats_of_an_image_region.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load input imagery: Landsat 7 5-year composite. image = ee.Image('LANDSAT/LE7_TOA_5YEAR/2008_2012') # print(image.getInfo()) # Load an input region: Sierra Nevada. region = ee.Feature(ee.FeatureCollection('EPA/Ecoregions/2013/L3') \ .filter(ee.Filter.eq('us_l3name', 'Sierra Nevada')) \ .first()) # Reduce the region. The region parameter is the Feature geometry. meanDictionary = image.reduceRegion(**{ 'reducer': ee.Reducer.mean(), 'geometry': region.geometry(), 'scale': 30, 'maxPixels': 1e9 }) # The result is a Dictionary. Print it. Map.centerObject(region, 9) Map.addLayer(image, {'bands': ['B4', 'B3', 'B2']}, 'Landsat-7') Map.addLayer(ee.Image().paint(region, 1, 3), {'palette': 'green'}, 'Mean Image') print(meanDictionary.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Image/set_image_properties.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def addDate(image): # parse date stored in 'system:index' date = ee.Date(image.get('system:index')) # format date, see http:#www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html str = date.format('YYYY-mm-dd') return image.set({'Date': str}) # point = ee.Geometry.Point(-122.262, 37.8719) # start = ee.Date('2014-06-01') # finish = ee.Date('2014-10-01') # filteredCollection = ee.ImageCollection('LANDSAT/LC08/C01/T1') \ # .filterBounds(point) \ # .filterDate(start, finish) \ # .sort('CLOUD_COVER', True) filteredCollection = ee.ImageCollection('users/sdavidcomer/L7maskedNDVIdated') # Bring in image collection # ndvi = ee.ImageCollection('users/sdavidcomer/L7maskedNDVIdated') # Map addDate over image collection result = filteredCollection.map(addDate) print(result.first().get('Date').getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/set_properties.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Make a feature and set some properties. feature = ee.Feature(ee.Geometry.Point([-122.22599, 37.17605])) \ .set('genus', 'Sequoia').set('species', 'sempervirens') # Get a property from the feature. species = feature.get('species') print(species.getInfo()) # Set a new property. feature = feature.set('presence', 1) # Overwrite the old properties with a new dictionary. newDict = {'genus': 'Brachyramphus', 'species': 'marmoratus'} feature = feature.set(newDict) # Check the result. print(feature.getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Array/array_transformations.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) import math # This function masks the input with a threshold on the simple cloud score. def cloudMask(img): cloudscore = ee.Algorithms.Landsat.simpleCloudScore(img).select('cloud') return img.updateMask(cloudscore.lt(50)) # cloudMask = function(img) { # cloudscore = ee.Algorithms.Landsat.simpleCloudScore(img).select('cloud') # return img.updateMask(cloudscore.lt(50)) # } # This function computes the predictors and the response from the input. def makeVariables(image): # Compute time of the image in fractional years relative to the Epoch. year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) # Compute the season in radians, one cycle per year. season = year.multiply(2 * math.pi) # Return an image of the predictors followed by the response. return image.select() \ .addBands(ee.Image(1)) \ .addBands(year.rename('t')) \ .addBands(season.sin().rename('sin')) \ .addBands(season.cos().rename('cos')) \ .addBands(image.normalizedDifference().rename('NDVI')) \ .toFloat() # Load a Landsat 5 image collection. collection = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA') \ .filterDate('2008-04-01', '2010-04-01') \ .filterBounds(ee.Geometry.Point(-122.2627, 37.8735)) \ .map(cloudMask) \ .select(['B4', 'B3']) \ .sort('system:time_start', True) # # This function computes the predictors and the response from the input. # makeVariables = function(image) { # # Compute time of the image in fractional years relative to the Epoch. # year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) # # Compute the season in radians, one cycle per year. # season = year.multiply(2 * Math.PI) # # Return an image of the predictors followed by the response. # return image.select() \ # .addBands(ee.Image(1)) # 0. constant \ # .addBands(year.rename('t')) # 1. linear trend \ # .addBands(season.sin().rename('sin')) # 2. seasonal \ # .addBands(season.cos().rename('cos')) # 3. seasonal \ # .addBands(image.normalizedDifference().rename('NDVI')) # 4. response \ # .toFloat() # } # Define the axes of variation in the collection array. imageAxis = 0 bandAxis = 1 # Convert the collection to an array. array = collection.map(makeVariables).toArray() # Check the length of the image axis (number of images). arrayLength = array.arrayLength(imageAxis) # Update the mask to ensure that the number of images is greater than or # equal to the number of predictors (the linear model is solveable). array = array.updateMask(arrayLength.gt(4)) # Get slices of the array according to positions along the band axis. predictors = array.arraySlice(bandAxis, 0, 4) response = array.arraySlice(bandAxis, 4) # Compute coefficients the easiest way. coefficients3 = predictors.matrixSolve(response) # Turn the results into a multi-band image. coefficientsImage = coefficients3 \ .arrayProject([0]) \ .arrayFlatten([ ['constant', 'trend', 'sin', 'cos'] ]) print(coefficientsImage.getInfo()) Map.setCenter(-122.2627, 37.8735, 10) Map.addLayer(coefficientsImage, {}, 'coefficientsImage') # Display the map. Map
liuxb555/earthengine-py-examples
Image/select_bands.py
<filename>Image/select_bands.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load an image. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318') band345 = image.select(['B[3-5]']) bandNames = band345.bandNames() print(bandNames.getInfo()) # Define visualization parameters in an object literal. vizParams = {'bands': ['B5', 'B4', 'B3'], 'min': 5000, 'max': 15000, 'gamma': 1.3} # Center the map on the image and display. Map.centerObject(image, 9) Map.addLayer(band345, vizParams, 'Landsat 8 False color') # Display the map. Map
liuxb555/earthengine-py-examples
Image/clamp.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # ee.Image.clamp() example. # Clamp the values of all bands in an image to lie within the specified range. # Values below the low value of that range are set to low value, values above # the high value of that range are set to the high value. image = ee.Image('CGIAR/SRTM90_V4') clamped = image.clamp(1000, 2000) Map.setCenter(-121.753, 46.855, 9) Map.addLayer(image, {'min': 0, 'max': 4300}, 'Full stretch') Map.addLayer(clamped, {'min': 0, 'max': 4300}, 'Clamped') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/minimum_bounding_geometry.py
<reponame>liuxb555/earthengine-py-examples<filename>FeatureCollection/minimum_bounding_geometry.py<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) HUC10 = ee.FeatureCollection("USGS/WBD/2017/HUC10") HUC08 = ee.FeatureCollection('USGS/WBD/2017/HUC08') roi = HUC08.filter(ee.Filter.eq('name', 'Pipestem')) Map.centerObject(roi, 10) Map.addLayer(ee.Image().paint(roi, 0, 1), {}, 'HUC8') bound = ee.Geometry(roi.geometry()).bounds() Map.addLayer(ee.Image().paint(bound, 0, 1), {'palette': 'red'}, "Minimum bounding geometry") # Display the map. Map
liuxb555/earthengine-py-examples
Image/zero_crossing.py
<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Mark pixels where the elevation crosses 1000m value and compare # that to pixels that are exactly equal to 1000m. elev = ee.Image('CGIAR/SRTM90_V4') # A zero-crossing is defined as any pixel where the right, # bottom, or diagonal bottom-right pixel has the opposite sign. image = elev.subtract(1000).zeroCrossing() Map.setCenter(-121.68148, 37.50877, 13) Map.addLayer(image, {'min': 0, 'max': 1, 'opacity': 0.5}, 'Crossing 1000m') exact = elev.eq(1000) Map.addLayer(exact.updateMask(exact), {'palette': 'red'}, 'Exactly 1000m') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/us_cropland.py
# Metadata: https://developers.google.com/earth-engine/datasets/catalog/USDA_NASS_CDL import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.ImageCollection('USDA/NASS/CDL') \ .filter(ee.Filter.date('2017-01-01', '2018-12-31')) \ .first() cropLandcover = dataset.select('cropland') Map.setCenter(-100.55, 40.71, 4) Map.addLayer(cropLandcover, {}, 'Crop Landcover') # Display the map. Map
liuxb555/earthengine-py-examples
AssetManagement/exporting_data.py
<reponame>liuxb555/earthengine-py-examples<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image('USDA/NAIP/DOQQ/m_4609915_sw_14_1_20100629') # downConfig = {'scale':30, "maxPixels": 1.0E13, 'driveFolder':'test', 'CRS': 'EPGS:31983', 'region': roiExample } # # task = ee.batch.Export.image(image.select( ['B2', 'B3' ,'B4', 'B5', 'B6']).toDouble(), 'sirgas20023sPy', downConfig) # task.start() downConfig = {'scale': 10, "maxPixels": 1.0E13, 'driveFolder': 'image'} # scale means resolution. task = ee.batch.Export.image(image, "10m", downConfig) task.start() # Display the map. Map
liuxb555/earthengine-py-examples
Algorithms/landsat_simple_composite.py
<filename>Algorithms/landsat_simple_composite.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a raw Landsat 5 ImageCollection for a single year. collection = ee.ImageCollection('LANDSAT/LT05/C01/T1') \ .filterDate('2010-01-01', '2010-12-31') # Create a cloud-free composite with default parameters. composite = ee.Algorithms.Landsat.simpleComposite(collection) # Create a cloud-free composite with custom parameters for # cloud score threshold and percentile. customComposite = ee.Algorithms.Landsat.simpleComposite(**{ 'collection': collection, 'percentile': 75, 'cloudScoreRange': 5 }) # Display the composites. Map.setCenter(-122.3578, 37.7726, 10) Map.addLayer(composite, {'bands': ['B4', 'B3', 'B2'], 'max': 128}, 'TOA composite') Map.addLayer(customComposite, {'bands': ['B4', 'B3', 'B2'], 'max': 128}, 'Custom TOA composite') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/alos_topo_diversity.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('CSP/ERGo/1_0/Global/ALOS_topoDiversity') alosTopographicDiversity = dataset.select('constant') alosTopographicDiversityVis = { 'min': 0.0, 'max': 1.0, } Map.setCenter(-111.313, 39.724, 6) Map.addLayer( alosTopographicDiversity, alosTopographicDiversityVis, 'ALOS Topographic Diversity') # Display the map. Map
liuxb555/earthengine-py-examples
Image/hough_transform.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # An example finding linear features using the HoughTransform. # Load an image and compute NDVI. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_033032_20170719') ndvi = image.normalizedDifference(['B5', 'B4']) # Apply a Canny edge detector. canny = ee.Algorithms.CannyEdgeDetector(**{ 'image': ndvi, 'threshold': 0.4 }).multiply(255) # Apply the Hough transform. h = ee.Algorithms.HoughTransform(**{ 'image': canny, 'gridSize': 256, 'inputThreshold': 50, 'lineThreshold': 100 }) # Display. Map.setCenter(-103.80140, 40.21729, 13) Map.addLayer(image, {'bands': ['B4', 'B3', 'B2'], 'max': 0.3}, 'source_image') Map.addLayer(canny.updateMask(canny), {'min': 0, 'max': 1, 'palette': 'blue'}, 'canny') Map.addLayer(h.updateMask(h), {'min': 0, 'max': 1, 'palette': 'red'}, 'hough') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/usda_naip.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) roi = ee.FeatureCollection('TIGER/2018/States') \ .filter(ee.Filter.eq('STUSPS', 'ND')); dataset = ee.ImageCollection('USDA/NAIP/DOQQ') \ .filter(ee.Filter.date('2016-01-01', '2017-12-31'))\ .filterBounds(roi) TrueColor = dataset.select(['N', 'R', 'G']).mosaic() TrueColorVis = { 'min': 0.0, 'max': 255.0, } # Map.setCenter(-73.9958, 40.7278, 15) Map.centerObject(roi, 8) Map.addLayer(TrueColor, TrueColorVis, 'True Color') # Display the map. Map
liuxb555/earthengine-py-examples
Image/pixel_lon_lat.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Draws 60 lat/long lines per degree using the pixelLonLat() function. # Create an image in which the value of each pixel is its # coordinates in minutes. img = ee.Image.pixelLonLat().multiply(60.0) # Get the decimal part and check if it's less than a small delta. img = img.subtract(img.floor()).lt(0.05) # The pixels less than the delta are the grid, in both directions. grid = img.select('latitude').Or(img.select('longitude')) # Draw the grid. Map.setCenter(-122.09228, 37.42330, 12) Map.addLayer(grid.updateMask(grid), {'palette': '008000'}, 'Graticule') # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/map_function.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # This function adds a band representing the image timestamp. def addTime(image): return image.addBands(image.metadata('system:time_start')) def conditional(image): return ee.Algorithms.If(ee.Number(image.get('SUN_ELEVATION')).gt(40), image, ee.Image(0)) # Load a Landsat 8 collection for a single path-row. collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \ .filter(ee.Filter.eq('WRS_PATH', 44)) \ .filter(ee.Filter.eq('WRS_ROW', 34)) # Map the function over the collection and display the result. print(collection.map(addTime).getInfo()) # Load a Landsat 8 collection for a single path-row. collection = ee.ImageCollection('LANDSAT/LC8_L1T_TOA') \ .filter(ee.Filter.eq('WRS_PATH', 44)) \ .filter(ee.Filter.eq('WRS_ROW', 34)) # This function uses a conditional statement to return the image if # the solar elevation > 40 degrees. Otherwise it returns a zero image. # conditional = function(image) { # return ee.Algorithms.If(ee.Number(image.get('SUN_ELEVATION')).gt(40), # image, # ee.Image(0)) # } # Map the function over the collection, convert to a List and print the result. print('Expand this to see the result: ', collection.map(conditional).getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Array/quality_mosaic.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Array-based quality mosaic. # Returns a mosaic built by sorting each stack of pixels by the first band # in descending order, and taking the highest quality pixel. # function qualityMosaic(bands) { def qualityMosaic(bands): # Convert to an array, and declare names for the axes and indices along the # band axis. array = bands.toArray() imageAxis = 0 bandAxis = 1 qualityIndex = 0 valuesIndex = 1 # Slice the quality and values off the main array, and sort the values by the # quality in descending order. quality = array.arraySlice(bandAxis, qualityIndex, qualityIndex + 1) values = array.arraySlice(bandAxis, valuesIndex) valuesByQuality = values.arraySort(quality.multiply(-1)) # Get an image where each pixel is the array of band values where the quality # band is greatest. Note that while the array is 2-D, the first axis is # length one. best = valuesByQuality.arraySlice(imageAxis, 0, 1) # Project the best 2D array down to a single dimension, and convert it back # to a regular scalar image by naming each position along the axis. Note we # provide the original band names, but slice off the first band since the # quality band is not part of the result. Also note to get at the band names, # we have to do some kind of reduction, but it won't really calculate pixels # if we only access the band names. bandNames = bands.min().bandNames().slice(1) return best.arrayProject([bandAxis]).arrayFlatten([bandNames]) # } # Load the l7_l1t collection for the year 2000, and make sure the first band # is our quality measure, in this case the normalized difference values. l7 = ee.ImageCollection('LANDSAT/LE07/C01/T1') \ .filterDate('2000-01-01', '2001-01-01') withNd = l7.map(lambda image: image.normalizedDifference(['B4', 'B3']).addBands(image)) # Build a mosaic using the NDVI of bands 4 and 3, essentially showing the # greenest pixels from the year 2000. greenest = qualityMosaic(withNd) # Select out the color bands to visualize. An interesting artifact of this # approach is that clouds are greener than water. So all the water is white. rgb = greenest.select(['B3', 'B2', 'B1']) Map.addLayer(rgb, {'gain': [1.4, 1.4, 1.1]}, 'Greenest') Map.setCenter(-90.08789, 16.38339, 11) # Display the map. Map
liuxb555/earthengine-py-examples
Array/decorrelation_stretch.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Decorrelation Stretch def dcs(image, region, scale): # function dcs(image, region, scale) { bandNames = image.bandNames() # The axes are numbered, so to make the following code more # readable, give the axes names. imageAxis = 0 bandAxis = 1 # Compute the mean of each band in the region. means = image.reduceRegion(ee.Reducer.mean(), region, scale) # Create a constant array image from the mean of each band. meansArray = ee.Image(means.toArray()) # Collapse the bands of the image into a 1D array per pixel, # with images along the first axis and bands along the second. arrays = image.toArray() # Perform element-by-element subtraction, which centers the # distribution of each band within the region. centered = arrays.subtract(meansArray) # Compute the covariance of the bands within the region. covar = centered.reduceRegion(**{ 'reducer': ee.Reducer.centeredCovariance(), 'geometry': region, 'scale': scale }) # Get the 'array' result and cast to an array. Note this is a # single array, not one array per pixel, and represents the # band-to-band covariance within the region. covarArray = ee.Array(covar.get('array')) # Perform an eigen analysis and slice apart the values and vectors. eigens = covarArray.eigen() eigenValues = eigens.slice(bandAxis, 0, 1) eigenVectors = eigens.slice(bandAxis, 1) # Rotate by the eigenvectors, scale to a variance of 30, and rotate back. i = ee.Array.identity(bandNames.length()) variance = eigenValues.sqrt().matrixToDiag() scaled = i.multiply(30).divide(variance) rotation = eigenVectors.transpose() \ .matrixMultiply(scaled) \ .matrixMultiply(eigenVectors) # Reshape the 1-D 'normalized' array, so we can left matrix multiply # with the rotation. This requires embedding it in 2-D space and # transposing. transposed = centered.arrayRepeat(bandAxis, 1).arrayTranspose() # Convert rotated results to 3 RGB bands, and shift the mean to 127. return transposed.matrixMultiply(ee.Image(rotation)) \ .arrayProject([bandAxis]) \ .arrayFlatten([bandNames]) \ .add(127).byte() # } image = ee.Image('MODIS/006/MCD43A4/2002_07_04') Map.setCenter(-52.09717, -7.03548, 7) # View the original bland image. rgb = [0, 3, 2] Map.addLayer(image.select(rgb), {'min': -100, 'max': 2000}, 'Original Image') # Stretch the values within an interesting region. region = ee.Geometry.Rectangle(-57.04651, -8.91823, -47.24121, -5.13531) Map.addLayer(dcs(image, region, 1000).select(rgb), {}, 'DCS Image') # Display the region in which covariance stats were computed. Map.addLayer(ee.Image().paint(region, 0, 2), {}, 'Region') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/idw_interpolation.py
<filename>FeatureCollection/idw_interpolation.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) def sampling(sample): lat = sample.get('latitude') lon = sample.get('longitude') ch4 = sample.get('ch4') return ee.Feature(ee.Geometry.Point([lon, lat]), {'ch4': ch4}) # Import two weeks of S5P methane and composite by mean. ch4 = ee.ImageCollection('COPERNICUS/S5P/OFFL/L3_CH4') \ .select('CH4_column_volume_mixing_ratio_dry_air') \ .filterDate('2019-08-01', '2019-08-15') \ .mean() \ .rename('ch4') # Define an area to perform interpolation over. aoi = ee.Geometry.Polygon( [[[-95.68487605978851, 43.09844605027055], [-95.68487605978851, 37.39358590079781], [-87.96148738791351, 37.39358590079781], [-87.96148738791351, 43.09844605027055]]], {}, False) # Sample the methane composite to generate a FeatureCollection. samples = ch4.addBands(ee.Image.pixelLonLat()) \ .sample(**{'region': aoi, 'numPixels': 1500, 'scale':1000, 'projection': 'EPSG:4326'}) \ .map(sampling) # Combine mean and standard deviation reducers for efficiency. combinedReducer = ee.Reducer.mean().combine(**{ 'reducer2': ee.Reducer.stdDev(), 'sharedInputs': True}) # Estimate global mean and standard deviation from the points. stats = samples.reduceColumns(**{ 'reducer': combinedReducer, 'selectors': ['ch4']}) # Do the interpolation, valid to 70 kilometers. interpolated = samples.inverseDistance(**{ 'range': 7e4, 'propertyName': 'ch4', 'mean': stats.get('mean'), 'stdDev': stats.get('stdDev'), 'gamma': 0.3}) # Define visualization arguments. band_viz = { 'min': 1800, 'max': 1900, 'palette': ['0D0887', '5B02A3', '9A179B', 'CB4678', 'EB7852', 'FBB32F', 'F0F921']} # Display to map. # Map.centerObject(ee.FeatureCollection(aoi), 7) Map.addLayer(ch4, band_viz, 'CH4') # Map.addLayer(interpolated, band_viz, 'CH4 Interpolated') # Display the map. Map
liuxb555/earthengine-py-examples
Image/object_based.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Make an area of interest geometry centered on San Francisco. point = ee.Geometry.Point(-122.1899, 37.5010) aoi = point.buffer(10000) # Import a Landsat 8 image, subset the thermal band, and clip to the # area of interest. kelvin = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318') \ .select(['B10'], ['kelvin']) \ .clip(aoi) # Display the thermal band. # Map.centerObject(point, 13) Map.setCenter(-122.1899, 37.5010, 13) Map.addLayer(kelvin, {'min': 288, 'max': 305}, 'Kelvin') # Threshold the thermal band to set hot pixels as value 1 and not as 0. hotspots = kelvin.gt(303) \ .selfMask() \ .rename('hotspots') # Display the thermal hotspots on the Map. Map.addLayer(hotspots, {'palette': 'FF0000'}, 'Hotspots') # Uniquely label the hotspot image objects. objectId = hotspots.connectedComponents(**{ 'connectedness': ee.Kernel.plus(1), 'maxSize': 128 }) # Display the uniquely ID'ed objects to the Map. Map.addLayer(objectId.randomVisualizer(), {}, 'Objects') # Compute the number of pixels in each object defined by the "labels" band. objectSize = objectId.select('labels') \ .connectedPixelCount(**{ 'maxSize': 128, 'eightConnected': False }) # Display object pixel count to the Map. Map.addLayer(objectSize, {}, 'Object n pixels') # Get a pixel area image. pixelArea = ee.Image.pixelArea() # Multiply pixel area by the number of pixels in an object to calculate # the object area. The result is an image where each pixel # of an object relates the area of the object in m^2. objectArea = objectSize.multiply(pixelArea) # Display object area to the Map. Map.addLayer(objectArea, {}, 'Object area m^2') # Threshold the `objectArea` image to define a mask that will mask out # objects below a given size (1 hectare in this case). areaMask = objectArea.gte(10000) # Update the mask of the `objectId` layer defined previously using the # minimum area mask just defined. objectId = objectId.updateMask(areaMask) Map.addLayer(objectId, {}, 'Large hotspots') # Make a suitable image for `reduceConnectedComponents()` by adding a label # band to the `kelvin` temperature image. kelvin = kelvin.addBands(objectId.select('labels')) # Calculate the mean temperature per object defined by the previously added # "labels" band. patchTemp = kelvin.reduceConnectedComponents(**{ 'reducer': ee.Reducer.mean(), 'labelBand': 'labels' }) # Display object mean temperature to the Map. Map.addLayer( patchTemp, {'min': 303, 'max': 304, 'palette': ['yellow', 'red']}, 'Mean temperature' ) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/random_samples.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Define an arbitrary region in which to compute random points. region = ee.Geometry.Rectangle(-119.224, 34.669, -99.536, 50.064) # Create 1000 random points in the region. randomPoints = ee.FeatureCollection.randomPoints(region) # Display the points. Map.centerObject(randomPoints) Map.addLayer(randomPoints, {}, 'random points') # Display the map. Map
liuxb555/earthengine-py-examples
Image/pixel_area.py
<filename>Image/pixel_area.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Displays the decreasing area covered by a single pixel at # higher latitudes using the Image.pixelArea() function. # Create an image in which the value of each pixel is its area. img = ee.Image.pixelArea() Map.setCenter(0, 0, 3) Map.addLayer(img, {'min': 2e8, 'max': 4e8, 'opacity': 0.85}, 'pixel area') # Display the map. Map
liuxb555/earthengine-py-examples
qgis_to_geemap.py
<reponame>liuxb555/earthengine-py-examples """This script is used to convert Earth Engine QGIS examples to geemap. """ import os import geemap from pathlib import Path def conversion(in_file, out_file): in_file = os.path.abspath(in_file) out_file = os.path.abspath(out_file) out_dir = os.path.dirname(out_file) if not os.path.exists(out_dir): os.makedirs(out_dir) out_lines = [] with open(in_file) as f: in_lines = f.readlines() for line in in_lines: if line.strip().startswith('# GitHub URL'): pass elif line.strip() != 'from ee_plugin import Map': out_lines.append(line) else: out_lines.append('import geemap\n') out_lines.append('\n# Create a map centered at (lat, lon).\n') out_lines.append( 'Map = geemap.Map(center=[40, -100], zoom=4)\n') out_lines.append('\n# Display the map.') out_lines.append('\nMap\n') with open(out_file, 'w') as f: f.writelines(out_lines) def conversion_dir(in_dir, out_dir): in_dir = os.path.abspath(in_dir) out_dir = os.path.abspath(out_dir) in_files = list(Path(in_dir).rglob('*.py')) for index, in_file in enumerate(in_files): in_file = str(in_file) if in_file.endswith('qgis_basemaps.py') or in_file.endswith('convert_js_to_python.py'): continue print('Processing {}/{}: {}...'.format(index + 1, len(in_files), in_file)) out_file = in_file.replace(in_dir, out_dir) parent_dir = os.path.dirname(out_file) if not os.path.exists(parent_dir): os.makedirs(parent_dir) conversion(in_file, out_file) out_dir = os.path.join(os.path.expanduser('~'), 'Downloads') if not os.path.isdir(out_dir): os.makedirs(out_dir) qgis_repo_url = 'https://github.com/giswqs/qgis-earthengine-examples' qgis_repo_name = os.path.basename(qgis_repo_url) qgis_repo_dir = os.path.join(out_dir, qgis_repo_name) if not os.path.exists(qgis_repo_dir): geemap.clone_github_repo( qgis_repo_url, os.path.join(out_dir, qgis_repo_dir)) conversion_dir(qgis_repo_dir, os.getcwd())
liuxb555/earthengine-py-examples
Image/image_metadata.py
<filename>Image/image_metadata.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image('LANDSAT/LC8_L1T/LC80440342014077LGN00') bandNames = image.bandNames() print('Band names: ', bandNames.getInfo()) # ee.List b1proj = image.select('B1').projection() print('Band 1 projection: ', b1proj.getInfo()) # ee.Projection b1scale = image.select('B1').projection().nominalScale() print('Band 1 scale: ', b1scale.getInfo()) # ee.Number b8scale = image.select('B8').projection().nominalScale() print('Band 8 scale: ', b8scale.getInfo()) # ee.Number properties = image.propertyNames() print('Metadata properties: ', properties.getInfo()) # ee.List cloudiness = image.get('CLOUD_COVER') print('CLOUD_COVER: ', cloudiness.getInfo()) # ee.Number date = ee.Date(image.get('system:time_start')) print('Timestamp: ', date.getInfo()) # ee.Date # Display the map. Map
liuxb555/earthengine-py-examples
MachineLearning/cart_classifier.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Input imagery is a cloud-free Landsat 8 composite. l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1') image = ee.Algorithms.Landsat.simpleComposite(**{ 'collection': l8.filterDate('2018-01-01', '2018-12-31'), 'asFloat': True }) # Use these bands for prediction. bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11'] # Load training points. The numeric property 'class' stores known labels. points = ee.FeatureCollection('GOOGLE/EE/DEMOS/demo_landcover_labels') # This property of the table stores the land cover labels. label = 'landcover' # Overlay the points on the imagery to get training. training = image.select(bands).sampleRegions(**{ 'collection': points, 'properties': [label], 'scale': 30 }) # Train a CART classifier with default parameters. trained = ee.Classifier.cart().train(training, label, bands) # Classify the image with the same bands used for training. classified = image.select(bands).classify(trained) # Display the inputs and the results. Map.centerObject(points, 11) Map.addLayer(image, {'bands': ['B4', 'B3', 'B2'], 'max': 0.4}, 'image') Map.addLayer(classified, {'min': 0, 'max': 2, 'palette': ['red', 'green', 'blue']}, 'classification') # Display the map. Map
liuxb555/earthengine-py-examples
Algorithms/CloudMasking/landsat8_toa_reflectance_qa_band.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # This example demonstrates the use of the Landsat 8 QA band to mask clouds. # Function to mask clouds using the quality band of Landsat 8. # maskL8 = function(image) { def maskL8(image): qa = image.select('BQA') #/ Check that the cloud bit is off. # See https:#www.usgs.gov/land-resources/nli/landsat/landsat-collection-1-level-1-quality-assessment-band mask = qa.bitwiseAnd(1 << 4).eq(0) return image.updateMask(mask) # } # Map the function over one year of Landsat 8 TOA data and take the median. composite = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') \ .filterDate('2016-01-01', '2016-12-31') \ .map(maskL8) \ .median() # Display the results in a cloudy place. Map.setCenter(114.1689, 22.2986, 12) Map.addLayer(composite, {'bands': ['B4', 'B3', 'B2'], 'max': 0.3}, "Image") # Display the map. Map
liuxb555/earthengine-py-examples
Image/image_displacement.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) import math # Load the two images to be registered. image1 = ee.Image('SKYSAT/GEN-A/PUBLIC/ORTHO/MULTISPECTRAL/s01_20150502T082736Z') image2 = ee.Image('SKYSAT/GEN-A/PUBLIC/ORTHO/MULTISPECTRAL/s01_20150305T081019Z') # Use bicubic resampling during registration. image1Orig = image1.resample('bicubic') image2Orig = image2.resample('bicubic') # Choose to register using only the 'R' bAnd. image1RedBAnd = image1Orig.select('R') image2RedBAnd = image2Orig.select('R') # Determine the displacement by matching only the 'R' bAnds. displacement = image2RedBAnd.displacement(**{ 'referenceImage': image1RedBAnd, 'maxOffset': 50.0, 'patchWidth': 100.0 }) # Compute image offset And direction. offset = displacement.select('dx').hypot(displacement.select('dy')) angle = displacement.select('dx').atan2(displacement.select('dy')) # Display offset distance And angle. Map.addLayer(offset, {'min':0, 'max': 20}, 'offset') Map.addLayer(angle, {'min': -math.pi, 'max': math.pi}, 'angle') Map.setCenter(37.44,0.58, 15) # Use the computed displacement to register all Original bAnds. registered = image2Orig.displace(displacement) # Show the results of co-registering the images. visParams = {'bands': ['R', 'G', 'B'], 'max': 4000} Map.addLayer(image1Orig, visParams, 'Reference') Map.addLayer(image2Orig, visParams, 'BefOre Registration') Map.addLayer(registered, visParams, 'After Registration') alsoRegistered = image2Orig.register(**{ 'referenceImage': image1Orig, 'maxOffset': 50.0, 'patchWidth': 100.0 }) Map.addLayer(alsoRegistered, visParams, 'Also Registered') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/us_census_tracts.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.FeatureCollection('TIGER/2010/Tracts_DP1') visParams = { 'min': 0, 'max': 4000, 'opacity': 0.8, } # Turn the strings into numbers dataset = dataset.map(lambda f: f.set('shape_area', ee.Number.parse(f.get('dp0010001')))) # Map.setCenter(-103.882, 43.036, 8) image = ee.Image().float().paint(dataset, 'dp0010001') Map.addLayer(image, visParams, 'TIGER/2010/Tracts_DP1') # Map.addLayer(dataset, {}, 'for Inspector', False) # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Water/jrc_monthly_recurrence.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.ImageCollection('JRC/GSW1_1/MonthlyRecurrence').first() monthlyRecurrence = dataset.select('monthly_recurrence') monthlyRecurrenceVis = { 'min': 0.0, 'max': 100.0, 'palette': ['ffffff', 'ffbbbb', '0000ff'], } Map.setCenter(-51.482, -0.835, 9) Map.addLayer(monthlyRecurrence, monthlyRecurrenceVis, 'Monthly Recurrence') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/merge_feature_collections.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) SD = ee.FeatureCollection('TIGER/2018/States') \ .filter(ee.Filter.eq('STUSPS', 'SD')) ND = ee.FeatureCollection('TIGER/2018/States') \ .filter(ee.Filter.eq('STUSPS', 'ND')) states = SD.merge(ND) Map.centerObject(states, 6) Map.addLayer(ee.Image().paint(states, 0, 2), {}, 'Dakotas') # print(states.size().getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
HowEarthEngineWorks/DeferredExecution.py
import ee image = ee.Image('CGIAR/SRTM90_V4') operation = image.add(10) # print(operation.getInfo()) print(operation) # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/overview.py
<filename>ImageCollection/overview.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Create arbitrary constant images. constant1 = ee.Image(1) constant2 = ee.Image(2) # Create a collection by giving a list to the constructor. collectionFromConstructor = ee.ImageCollection([constant1, constant2]) print('collectionFromConstructor: ', collectionFromConstructor.getInfo()) # Create a collection with fromImages(). collectionFromImages = ee.ImageCollection.fromImages( [ee.Image(3), ee.Image(4)]) print('collectionFromImages: ', collectionFromImages.getInfo()) # Merge two collections. mergedCollection = collectionFromConstructor.merge(collectionFromImages) print('mergedCollection: ', mergedCollection.getInfo()) # # Create a toy FeatureCollection # features = ee.FeatureCollection( # [ee.Feature({}, {'foo': 1}), ee.Feature({}, {'foo': 2})]) # # Create an ImageCollection from the FeatureCollection # # by mapping a function over the FeatureCollection. # images = features.map(function(feature) { # return ee.Image(ee.Number(feature.get('foo'))) # }) # # Print the resultant collection. # print('Image collection: ', images) # Display the map. Map
liuxb555/earthengine-py-examples
Visualization/color_by_attribute.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) fc = ee.FeatureCollection('TIGER/2018/States') print(fc.first().getInfo()) # Use this empty image for paint(). empty = ee.Image().byte() palette = ['green', 'yellow', 'orange', 'red'] states = empty.paint(**{ 'featureCollection': fc, 'color': 'ALAND', }) Map.addLayer(states, {'palette': palette}, 'US States') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/us_ned_physio_diversity.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('CSP/ERGo/1_0/US/physioDiversity') physiographicDiversity = dataset.select('b1') physiographicDiversityVis = { 'min': 0.0, 'max': 1.0, } Map.setCenter(-94.625, 39.825, 7) Map.addLayer( physiographicDiversity, physiographicDiversityVis, 'Physiographic Diversity') # Display the map. Map
liuxb555/earthengine-py-examples
Image/edge_detection.py
<reponame>liuxb555/earthengine-py-examples<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 8 image, select the panchromatic band. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8') # Perform Canny edge detection and display the result. canny = ee.Algorithms.CannyEdgeDetector(**{ 'image': image, 'threshold': 10, 'sigma': 1 }) Map.setCenter(-122.054, 37.7295, 10) Map.addLayer(canny, {}, 'canny') # Perform Hough transform of the Canny result and display. hough = ee.Algorithms.HoughTransform(canny, 256, 600, 100) Map.addLayer(hough, {}, 'hough') # Load a Landsat 8 image, select the panchromatic band. image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').select('B8') Map.addLayer(image, {'max': 12000}) # Define a "fat" Gaussian kernel. fat = ee.Kernel.gaussian(**{ 'radius': 3, 'sigma': 3, 'units': 'pixels', 'normalize': True, 'magnitude': -1 }) # Define a "skinny" Gaussian kernel. skinny = ee.Kernel.gaussian(**{ 'radius': 3, 'sigma': 1, 'units': 'pixels', 'normalize': True, }) # Compute a difference-of-Gaussians (DOG) kernel. dog = fat.add(skinny) # Compute the zero crossings of the second derivative, display. zeroXings = image.convolve(dog).zeroCrossing() Map.setCenter(-122.054, 37.7295, 10) Map.addLayer(zeroXings.updateMask(zeroXings), {'palette': 'FF0000'}, 'zero crossings') # Display the map. Map
liuxb555/earthengine-py-examples
Gena/basic_image.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image.pixelLonLat() \ .add([180, 90]).divide([360, 180]) # image = image.multiply(50).sin() Map.setCenter(0, 28, 2.5) Map.addLayer(image, {}, 'coords', True) # Display the map. Map
liuxb555/earthengine-py-examples
GetStarted/01_hello_world.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # traditional python string print('Hello world!') # Earth Eninge object print(ee.String('Hello World from Earth Engine!').getInfo()) print(ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318').getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/world_database_on_protected_areas.py
<filename>Datasets/Vectors/world_database_on_protected_areas.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.FeatureCollection('WCMC/WDPA/current/polygons') visParams = { 'palette': ['2ed033', '5aff05', '67b9ff', '5844ff', '0a7618', '2c05ff'], 'min': 0.0, 'max': 1550000.0, 'opacity': 0.8, } image = ee.Image().float().paint(dataset, 'REP_AREA') Map.setCenter(41.104, -17.724, 6) Map.addLayer(image, visParams, 'WCMC/WDPA/current/polygons') # Map.addLayer(dataset, {}, 'for Inspector', False) dataset = ee.FeatureCollection('WCMC/WDPA/current/points') styleParams = { 'color': '#4285F4', 'width': 1, } protectedAreaPoints = dataset.style(**styleParams) # Map.setCenter(110.57, 0.88, 4) Map.addLayer(protectedAreaPoints, {}, 'WCMC/WDPA/current/points') # Display the map. Map
liuxb555/earthengine-py-examples
Array/spectral_unmixing.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Array-based spectral unmixing. # Create a mosaic of Landsat 5 images from June through September, 2007. allBandMosaic = ee.ImageCollection('LANDSAT/LT05/C01/T1') \ .filterDate('2007-06-01', '2007-09-30') \ .select('B[0-7]') \ .median() # Create some representative endmembers computed previously by sampling # the Landsat 5 mosaic. urbanEndmember = [88, 42, 48, 38, 86, 115, 59] vegEndmember = [50, 21, 20, 35, 50, 110, 23] waterEndmember = [51, 20, 14, 9, 7, 116, 4] # Compute the 3x7 pseudo inverse. endmembers = ee.Array([urbanEndmember, vegEndmember, waterEndmember]) inverse = ee.Image(endmembers.matrixPseudoInverse().transpose()) # Convert the bands to a 2D 7x1 array. The toArray() call concatenates # pixels from each band along the default axis 0 into a 1D vector per # pixel, and the toArray(1) call concatenates each band (in this case # just the one band of 1D vectors) along axis 1, forming a 2D array. inputValues = allBandMosaic.toArray().toArray(1) # Matrix multiply the pseudo inverse of the endmembers by the pixels to # get a 3x1 set of endmembers fractions from 0 to 1. unmixed = inverse.matrixMultiply(inputValues) # Create and show a colored image of the endmember fractions. Since we know # the result has size 3x1, project down to 1D vectors at each pixel (since the # second axis is pointless now), and then flatten back to a regular scalar # image. colored = unmixed \ .arrayProject([0]) \ .arrayFlatten([['urban', 'veg', 'water']]) Map.setCenter(-98.4, 19, 11) # Load a hillshade to use as a backdrop. Map.addLayer(ee.Algorithms.Terrain(ee.Image('CGIAR/SRTM90_V4')).select('hillshade')) Map.addLayer(colored, {'min': 0, 'max': 1}, 'Unmixed (red=urban, green=veg, blue=water)') # Display the map. Map
liuxb555/earthengine-py-examples
Reducer/median_reducer.py
<filename>Reducer/median_reducer.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load an image collection, filtered so it's not too much data. collection = ee.ImageCollection('LANDSAT/LT05/C01/T1') \ .filterDate('2008-01-01', '2008-12-31') \ .filter(ee.Filter.eq('WRS_PATH', 44)) \ .filter(ee.Filter.eq('WRS_ROW', 34)) # Compute the median in each band, each pixel. # Band names are B1_median, B2_median, etc. median = collection.reduce(ee.Reducer.median()) # The output is an Image. Add it to the map. vis_param = {'bands': ['B4_median', 'B3_median', 'B2_median'], 'gamma': 1.6} Map.setCenter(-122.3355, 37.7924, 9) Map.addLayer(median, vis_param, 'Median') # Display the map. Map
liuxb555/earthengine-py-examples
Image/spectral_unmixing.py
<reponame>liuxb555/earthengine-py-examples<filename>Image/spectral_unmixing.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 5 image and select the bands we want to unmix. bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'] image = ee.Image('LANDSAT/LT05/C01/T1/LT05_044034_20080214') \ .select(bands) Map.setCenter(-122.1899, 37.5010, 10) # San Francisco Bay Map.addLayer(image, {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 128}, 'image') # Define spectral endmembers. urban = [88, 42, 48, 38, 86, 115, 59] veg = [50, 21, 20, 35, 50, 110, 23] water = [51, 20, 14, 9, 7, 116, 4] # Unmix the image. fractions = image.unmix([urban, veg, water]) Map.addLayer(fractions, {}, 'unmixed') # Display the map. Map
liuxb555/earthengine-py-examples
Image/image_overview.py
<gh_stars>10-100 import ee image1 = ee.Image(1) print(image1) print(image1.getInfo()) image2 = ee.Image(2) image3 = ee.Image.cat([image1, image2]) print(image3.getInfo()) multiband = ee.Image([1, 2, 3]) print(multiband) renamed = multiband.select(['constant','constant_1','constant_2'],['band1','band2','band3']) print(renamed) # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/select_by_strings.py
<reponame>liuxb555/earthengine-py-examples<filename>FeatureCollection/select_by_strings.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) #!/usr/bin/env python """Select by strings """ # Select states with "A" in its name fc = ee.FeatureCollection('TIGER/2018/States') \ .filter(ee.Filter.stringContains('STUSPS', 'A')) image = ee.Image().paint(fc, 0, 2) Map.centerObject(fc, 6) Map.addLayer(image, {'palette': 'FF0000'}, '*A*') # Select states its name starting with 'A' fc = ee.FeatureCollection('TIGER/2018/States') \ .filter(ee.Filter.stringStartsWith('STUSPS', 'A')) image = ee.Image().paint(fc, 0, 2) Map.addLayer(image, {'palette': '0000FF'}, 'A*') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/usgs_watershed_boundary.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.FeatureCollection('USGS/WBD/2017/HUC02') styleParams = { 'fillColor': '000070', 'color': '0000be', 'width': 3.0, } regions = dataset.style(**styleParams) Map.setCenter(-96.8, 40.43, 4) Map.addLayer(regions, {}, 'USGS/WBD/2017/HUC02') dataset = ee.FeatureCollection('USGS/WBD/2017/HUC04') styleParams = { 'fillColor': '5885E3', 'color': '0000be', 'width': 3.0, } subregions = dataset.style(**styleParams) Map.setCenter(-110.904, 36.677, 7) Map.addLayer(subregions, {}, 'USGS/WBD/2017/HUC04') dataset = ee.FeatureCollection('USGS/WBD/2017/HUC06') styleParams = { 'fillColor': '588593', 'color': '587193', 'width': 3.0, } basins = dataset.style(**styleParams) Map.setCenter(-96.8, 40.43, 7) Map.addLayer(basins, {}, 'USGS/WBD/2017/HUC06') dataset = ee.FeatureCollection('USGS/WBD/2017/HUC08') styleParams = { 'fillColor': '2E8593', 'color': '587193', 'width': 2.0, } subbasins = dataset.style(**styleParams) Map.setCenter(-96.8, 40.43, 8) Map.addLayer(subbasins, {}, 'USGS/WBD/2017/HUC08') dataset = ee.FeatureCollection('USGS/WBD/2017/HUC10') styleParams = { 'fillColor': '2E85BB', 'color': '2E5D7E', 'width': 1.0, } watersheds = dataset.style(**styleParams) Map.setCenter(-96.8, 40.43, 9) Map.addLayer(watersheds, {}, 'USGS/WBD/2017/HUC10') dataset = ee.FeatureCollection('USGS/WBD/2017/HUC12') styleParams = { 'fillColor': '2E85BB', 'color': '2E5D7E', 'width': 0.1, } subwatersheds = dataset.style(**styleParams) Map.setCenter(-96.8, 40.43, 10) Map.addLayer(subwatersheds, {}, 'USGS/WBD/2017/HUC12') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Water/jrc_metadata.py
<filename>Datasets/Water/jrc_metadata.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('JRC/GSW1_1/Metadata') detectionsObservations = dataset.select(['detections', 'valid_obs', 'total_obs']) visParams = { 'min': 100.0, 'max': 900.0, } Map.setCenter(4.72, -2.48, 2) Map.addLayer(detectionsObservations, visParams, 'Detections/Observations') # Display the map. Map
liuxb555/earthengine-py-examples
FeatureCollection/creating_feature.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Create an ee.Geometry. polygon = ee.Geometry.Polygon([ [[-35, -10], [35, -10], [35, 10], [-35, 10], [-35, -10]] ]) # Create a Feature from the Geometry. polyFeature = ee.Feature(polygon, {'foo': 42, 'bar': 'tart'}) print(polyFeature.getInfo()) Map.addLayer(polyFeature, {}, 'feature') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/us_ned.py
<filename>Datasets/Terrain/us_ned.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.Image('USGS/NED') elevation = dataset.select('elevation') elevationVis = { 'min': 0.0, 'max': 4000.0, 'gamma': 1.6, } Map.setCenter(-100.55, 40.71, 5) Map.addLayer(elevation, elevationVis, 'Elevation') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Terrain/canada_dem.py
<filename>Datasets/Terrain/canada_dem.py import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.ImageCollection('NRCan/CDEM') elevation = dataset.select('elevation').mosaic() elevationVis = { 'min': -50.0, 'max': 1500.0, 'palette': ['0905ff', 'ffefc4', 'ffffff'], } Map.setCenter(-139.3643, 63.3213, 9) Map.addLayer(elevation, elevationVis, 'Elevation') # Display the map. Map
liuxb555/earthengine-py-examples
NAIP/from_name.py
<reponame>liuxb555/earthengine-py-examples<gh_stars>10-100 import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image('USDA/NAIP/DOQQ/m_3712213_sw_10_1_20140613') Map.setCenter(-122.466123, 37.769833, 17) Map.addLayer(image, {'bands': ['N', 'R','G']}, 'NAIP') # Display the map. Map
liuxb555/earthengine-py-examples
Image/convert_bands_to_image_collection.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318') print("Number of bands:", image.bandNames().size().getInfo()) imageCollection = ee.ImageCollection(image.bandNames().map(lambda b: image.select([b]))) print("ImageCollection size: ", imageCollection.size().getInfo()) # Display the map. Map
liuxb555/earthengine-py-examples
ImageCollection/linear_fit.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Compute the trend of nighttime lights from DMSP. # Add a band containing image date as years since 1990. def createTimeBand(img): year = img.date().difference(ee.Date('1990-01-01'), 'year') return ee.Image(year).float().addBands(img) # function createTimeBand(img) { # year = img.date().difference(ee.Date('1990-01-01'), 'year') # return ee.Image(year).float().addBands(img) # } # Fit a linear trend to the nighttime lights collection. collection = ee.ImageCollection('NOAA/DMSP-OLS/CALIBRATED_LIGHTS_V4') \ .select('avg_vis') \ .map(createTimeBand) fit = collection.reduce(ee.Reducer.linearFit()) # Display a single image Map.addLayer(ee.Image(collection.select('avg_vis').first()), {'min': 0, 'max': 63}, 'stable lights first asset') # Display trend in red/blue, brightness in green. Map.setCenter(30, 45, 4) Map.addLayer(fit, {'min': 0, 'max': [0.18, 20, -0.18], 'bands': ['scale', 'offset', 'scale']}, 'stable lights trend') # Display the map. Map
liuxb555/earthengine-py-examples
Datasets/Vectors/us_epa_ecoregions.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) dataset = ee.FeatureCollection('EPA/Ecoregions/2013/L3') visParams = { 'palette': ['0a3b04', '1a9924', '15d812'], 'min': 23.0, 'max': 3.57e+11, 'opacity': 0.8, } image = ee.Image().float().paint(dataset, 'shape_area') Map.setCenter(-99.814, 40.166, 5) Map.addLayer(image, visParams, 'EPA/Ecoregions/2013/L3') # Map.addLayer(dataset, {}, 'for Inspector', False) dataset = ee.FeatureCollection('EPA/Ecoregions/2013/L4') visParams = { 'palette': ['0a3b04', '1a9924', '15d812'], 'min': 0.0, 'max': 67800000000.0, 'opacity': 0.8, } image = ee.Image().float().paint(dataset, 'shape_area') Map.setCenter(-99.814, 40.166, 5) Map.addLayer(image, visParams, 'EPA/Ecoregions/2013/L4') # Map.addLayer(dataset, {}, 'for Inspector', False) # Display the map. Map
liuxb555/earthengine-py-examples
Visualization/ndwi_symbology.py
import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # This function gets NDVI from Landsat 5 imagery. def getNDWI(image): return image.normalizedDifference(['B3', 'B5']) image1 = ee.Image('LANDSAT/LT05/C01/T1_TOA/LT05_044034_19900604') # Compute NDVI from the scene. ndvi1 = getNDWI(image1) ndwiParams = {'palette': ['#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858']} Map.centerObject(image1, 10) Map.addLayer(ndvi1, ndwiParams, 'NDWI') # Display the map. Map
liuxb555/earthengine-py-examples
Algorithms/sentinel-1_filtering.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load the Sentinel-1 ImageCollection. sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD') \ .filterBounds(ee.Geometry.Point(-122.37383, 37.6193)) # Filter by metadata properties. vh = sentinel1 \ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \ .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH')) \ .filter(ee.Filter.eq('instrumentMode', 'IW')) # Filter to get images from different look angles. vhAscending = vh.filter(ee.Filter.eq('orbitProperties_pass', 'ASCENDING')) vhDescending = vh.filter(ee.Filter.eq('orbitProperties_pass', 'DESCENDING')) # Create a composite from means at different polarizations and look angles. composite = ee.Image.cat([ vhAscending.select('VH').mean(), ee.ImageCollection(vhAscending.select('VV').merge(vhDescending.select('VV'))).mean(), vhDescending.select('VH').mean() ]).focal_median() # Display as a composite of polarization and backscattering characteristics. Map.setCenter(-122.37383, 37.6193, 10) Map.addLayer(composite, {'min': [-25, -20, -25], 'max': [0, 10, 0]}, 'composite') # Display the map. Map
liuxb555/earthengine-py-examples
GetStarted/06_reducing.py
<reponame>liuxb555/earthengine-py-examples import ee import geemap # Create a map centered at (lat, lon). Map = geemap.Map(center=[40, -100], zoom=4) # Load a Landsat 8 collection. collection = ee.ImageCollection('LANDSAT/LC08/C01/T1') \ .filterBounds(ee.Geometry.Point(-122.262, 37.8719)) \ .filterDate('2014-01-01', '2014-12-31') \ .sort('CLOUD_COVER') # Compute the median of each pixel for each band of the 5 least cloudy scenes. median = collection.limit(5).reduce(ee.Reducer.median()) # Define visualization parameters in an object literal. vizParams = {'bands': ['B5_median', 'B4_median', 'B3_median'], 'min': 5000, 'max': 15000, 'gamma': 1.3} Map.setCenter(-122.262, 37.8719, 10) Map.addLayer(median, vizParams, 'Median image') # Display the map. Map