def testConstructors(self): """Verifies that constructors understand valid parameters.""" from_static_method = ee.Filter.gt('foo', 1) from_computed_object = ee.Filter( ee.ApiFunction.call_('Filter.greaterThan', 'foo', 1)) self.assertEqual(from_static_method, from_computed_object) copy = ee.Filter(from_static_method) self.assertEqual(from_static_method, copy)
def generate_is( self, left, comp, right, ): if right.upper() == 'NULL': return ee.Filter().eq(left, 'null') elif right.upper().startswith('NOT') and right.upper().endswith( 'NULL'): return ee.Filter().neq(left, 'null') else: raise Exception('IS only support NULL value')
def band_intersection(image, bands): """ Returns the band names both in the image and in the list of provided band names. """ return image.bandNames().filter(ee.Filter( ee.Filter.inList('item', bands) ))
def testFilter(self): """Verifies that filtering an ImageCollection wraps the result.""" collection = ee.ImageCollection(ee.Image(1)) noop_filter = ee.Filter() filtered = collection.filter(noop_filter) self.assertTrue(isinstance(filtered, ee.ImageCollection)) self.assertEquals(ee.ApiFunction.lookup('Collection.filter'), filtered.func) self.assertEquals({'collection': collection, 'filter': noop_filter}, filtered.args)
def process_county(county_number, product): ee.Initialize() area = (ee.FeatureCollection( 'ft:1QPasan0i6O9uUlcYkjqj91D7mbnhTZCmzS4t7t_g').filter(ee.Filter().eq( 'id', county_number))) # import the RS products modis = ee.ImageCollection(product) # #modis = ee.ImageCollection('MODIS/MOD13Q1') #MCD43A4_NDVI # Define time range years = [x for x in range(2000, 2016)] aggregated = [] # Aggregate for year in years: aggregated.append(aggregate(modis, year, area)) # Make dataframes fin_dfs = [] for i in aggregated: fin_dfs.append(df_from_ee_object(i)) for df in fin_dfs: df.drop( ['time'], axis=1, inplace=True ) #(['id',"longitude","latitude","time"], axis=1, inplace = True) # Make a dict of the years with the data frames dfs_by_year = dict(zip(years, fin_dfs)) # Make the out directories for modis data and sub directories for counties outpath = os.path.join(os.getcwd(), product.replace("/", "_")) if os.path.exists(outpath): pass else: os.mkdir(outpath) county_dir = os.path.join(outpath, county_number) if os.path.exists(county_dir): pass else: os.mkdir(county_dir) for k, v in dfs_by_year.items(): v.to_csv(os.path.join(county_dir, str(k) + ".csv"))
def process_county(county_number, product): area = (ee.FeatureCollection( 'ft:15cgNIs0G_vYtNUhpYVmz0u_sPs6XrIUYpi19pjkt').filter(ee.Filter().eq( 'id', county_number))) # import the RS products imcol = ee.ImageCollection(product) # Define time range years = [x for x in range(2000, 2016)] # Aggregate aggregated = [] for year in years: aggregated.append(aggregate(imcol, year, area)) # make dfs from image cols dfs = [] for i in aggregated: dfs.append(df_from_ee_object(i)) for df in dfs: df.drop(["time"], axis=1, inplace=True) # Zip the years and dfs yearly = dict(zip(years, dfs)) # Make the out directories for modis data and sub directories for counties outpath = os.path.join(os.getcwd(), product.replace("/", "_")) if os.path.exists(outpath): pass else: os.mkdir(outpath) county_dir = os.path.join(outpath, str(county_number).zfill(3)) if os.path.exists(county_dir): pass else: os.mkdir(county_dir) for k, v in yearly.items(): v.to_csv(os.path.join(county_dir, str(k) + ".csv"))
def testMetadata(self): """Verifies that the metadata_() method works.""" self.assertEquals(ee.ApiFunction.call_('Filter.equals', 'x', 1), ee.Filter.metadata_('x', 'equals', 1)) self.assertEquals(ee.Filter.metadata_('x', 'equals', 1), ee.Filter().eq('x', 1)) self.assertEquals(ee.Filter.metadata_('x', 'EQUALS', 1), ee.Filter().eq('x', 1)) self.assertEquals(ee.Filter.metadata_('x', 'not_equals', 1), ee.Filter().neq('x', 1)) self.assertEquals(ee.Filter.metadata_('x', 'less_than', 1), ee.Filter().lt('x', 1)) self.assertEquals(ee.Filter.metadata_('x', 'not_greater_than', 1), ee.Filter().lte('x', 1)) self.assertEquals(ee.Filter.metadata_('x', 'greater_than', 1), ee.Filter().gt('x', 1)) self.assertEquals(ee.Filter.metadata_('x', 'not_less_than', 1), ee.Filter().gte('x', 1))
def containsAnyBand(collection, bands): """ Filter a collection with images cotaining any of the bands specified in parameter `bands` """ bands = ee.List(bands) # add bands as metadata collection = collection.map( lambda i: ee.Image(i).set('_BANDS_', ee.Image(i).bandNames())) band0 = ee.String(bands.get(0)) rest = ee.List(bands.slice(1)) filt0 = ee.Filter.listContains(leftField='_BANDS_', rightValue=band0) # Get filter def wrap(band, filt): band = ee.String(band) filt = ee.Filter(filt) newfilt = ee.Filter.listContains(leftField='_BANDS_', rightValue=band) return ee.Filter.Or(filt, newfilt) filt = ee.Filter(rest.iterate(wrap, filt0)) return collection.filter(filt)
def main(): # Set the Study area (upoad kml to google fusion table, use the DocID in the ft string below) padded_cn = str(county_number).zfill(3) area = (ee.FeatureCollection( 'ft:1QPasan0i6O9uUlcYkjqj91D7mbnhTZCmzS4t7t_g').filter(ee.Filter().eq( 'id', padded_cn))) bounds = area.geometry().bounds() # Set the study years years = [x for x in range(2001, 2017)] band_names = ["b1", "b2", "b3", "b4", "b5", "b6", "b7", "mask"] modis_lc = ee.ImageCollection('MODIS/006/MCD12Q1') modis_sr = ee.ImageCollection('MCD43A4') for year in years: print("Processing: " + str(year)) # Setup outfiles like: /modis/county_year_doy_band.txt moddir = os.path.join(os.getcwd(), "modis") if not os.path.exists(moddir): os.mkdir(moddir) filepath = os.path.join( moddir, "_".join([str(county_number), str(year), str(start_doy)])) outpaths = [filepath + x + ".txt" for x in band_names] # call earth engine to get the data outdata = get_sr_data(modis_sr, year, start_doy, bounds) outdata.append(get_lc_data(modis_lc, year, bounds)) # save for i in range(len(outdata)): np.savetxt(outpaths[i], outdata[i]) print(" === Done ===")
def main(): # Set the Study area (upoad kml to google fusion table, use the DocID in the ft string below) padded_cn = str(county_number).zfill(3) area = (ee.FeatureCollection( 'ft:1QPasan0i6O9uUlcYkjqj91D7mbnhTZCmzS4t7t_g').filter(ee.Filter().eq( 'id', padded_cn))) bounds = area.geometry().bounds() # Set the study years years = [x for x in range(2001, 2017)] band_names = ["B1", "B2", "B3", "B4", "B5", "B6", "B7"] for year in years: print("Processing: " + str(year)) # Setup outfiles like: /landsat/county_year_doy_band.txt outdir = os.path.join(os.getcwd(), "landsat") if not os.path.exists(outdir): os.mkdir(outdir) filepath = os.path.join( outdir, "_".join([str(county_number), str(year), str(start_doy)])) outpaths = [filepath + x + ".txt" for x in band_names] # call earth engine to get the data outdata = get_data(year, start_doy, bounds) # save for i in range(len(outdata)): np.savetxt(outpaths[i], outdata[i]) print(" === Done ===")
#!/usr/bin/env python """Count features example. Count Panoramio photos near SF that mention bridges. """ from __future__ import print_function import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-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'))) ee.mapclient.addToMap(photos_near_sf, {'color': '0040b0'}) ee.mapclient.addToMap(bridge_photos, {'color': 'e02070'}) print('There are {} bridge photos around SF.' .format(bridge_photos.size().getInfo()))
# Load in Flood Scene flood = ee.Image( 'COPERNICUS/S1_GRD/S1A_IW_GRDH_1SDV_20160103T062204_20160103T062229_009326_00D7AC_C9F2' ) # Determine Orbit/Track Metadata im_meta1 = flood.getInfo() im_meta2 = im_meta1['properties'] direction = im_meta2['orbitProperties_pass'] orbit = im_meta2['relativeOrbitNumber_start'] print 'Orbit Direction: ', direction print 'Track Number: ', orbit # Load in Sentinel-1 Collection collection = ee.ImageCollection("COPERNICUS/S1_GRD") # Filter S1 Collection filter = collection.filterDate(datetime.datetime(2015,7,3), datetime.datetime(2015,11,5)).filterBounds(ft2)\ .filter(ee.Filter().eq('transmitterReceiverPolarisation', 'VH')).filter(ee.Filter().eq('instrumentMode', 'IW'))\ .filter(ee.Filter().eq('orbitProperties_pass', direction)).filter(ee.Filter().eq('relativeOrbitNumber_start', orbit)) ### Be useful to get a number of images in the collection and use in the filter.toList() command ### Theoretically there could be hundreds of images going into this calculation in the future list = filter.toList(100) metalist = list.getInfo() for image in metalist: props = image['properties'] print props['system:index'] # Create Median reference image ref = filter.median() # Median 5x5 Speckle Filter on ref and flood images ref = ref.focal_median(5, 'circle', 'pixels').select('VH') flood = flood.focal_median(5, 'circle', 'pixels').select('VH') # Clip images to AOI ref = ref.clip(ft2)
def testInList(self): """Verifies that list membership filters work.""" self.assertEquals(ee.Filter.listContains(None, None, 'foo', [1, 2]), ee.Filter.inList('foo', [1, 2])) self.assertEquals(ee.Filter.inList('foo', [1, 2]), ee.Filter().inList('foo', [1, 2]))
def ppt_anomaly_func(start_dt, end_dt): """Calculate PPT anomalies for a given time period. The climatology is currently calculated for 2006 - 2010 Args: start_dt: Starting datetime object (inclusive) end_dt: Ending datetime object (inclusive) Returns: An EarthEngine mapid object """ ## Create a filter object that selects data based on the day-of-year doy_filter = ee.Filter( ee.Filter.calendarRange(int(start_dt.strftime('%j')), int(end_dt.strftime('%j')), 'day_of_year')) ## Shortened GRIDMET collecction for calculating anomaly gridmet_test_coll = ee.ImageCollection('IDAHO_EPSCOR/GRIDMET').filterDate( start_dt, end_dt) ##'IDAHO_EPSCOR/GRIDMET').filterDate("2013", "2014").filter(doy_filter) ## Full GRIDMET collection for calculating climatology gridmet_full_coll = ee.ImageCollection('IDAHO_EPSCOR/GRIDMET').filterDate( "2006", "2010").filter(doy_filter) def gridmet_ppt_func(gridmet_image): doy = ee.Number( ee.Algorithms.Date( gridmet_image.get("system:time_start")).getRelative( 'day', 'year')).add(1).double() return gridmet_image.select(['pr'], ['PPT']).set({ 'DOY': doy, 'system:index': gridmet_image.get('system:index'), 'system:time_start': gridmet_image.get('system:time_start'), 'system:time_end': gridmet_image.get('system:time_end') }) ## Calculate PPT for the full GRIDMET climatology period and the anomaly period separately ppt_full_coll = gridmet_full_coll.map(gridmet_ppt_func) ppt_test_coll = gridmet_test_coll.map(gridmet_ppt_func) ## For each PPT image in the anomaly time period (ppt_test_coll), ## get a list of PPT images from the full time period (ppt_full_coll) for the same DOY ## Link these two collections by DOY using the join method (which was calculated and set in the PPT function) ##doy_match_filter = ee.Filter.equals(leftField='DOY', rightField='DOY') doy_match_filter = ee.Filter.equals('DOY', None, 'DOY', None) ppt_join_coll = ee.ImageCollection( ee.Join.saveAll('doy_match').apply(ppt_test_coll, ppt_full_coll, doy_match_filter)) # Calculate the mean PPT (i.e. climatology) for each DOY in the anomaly period # (PPT images were saved to the doy_match property in the join collection) def mean_func(ppt_image): return ee.Image( ee.ImageCollection.fromImages(ppt_image.get('doy_match')).mean()) mean_coll = ppt_join_coll.map(mean_func) ## Calculate the PPT anomaly (i.e. PPT - PPT_mean) for each DOY in the anomaly period ## This seems very redundant. Is there a way to do an image wise subtraction between two collections ## in order to avoid calculating the mean for the collection twice? def anomaly_func(ppt_image): return ppt_image.subtract( ee.Image( ee.ImageCollection.fromImages( ppt_image.get('doy_match')).mean())) anomaly_coll = ee.ImageCollection(ppt_join_coll.map(anomaly_func)) ## Sum of the PPT anomalies divided by the sum of the mean PPT (i.e. sum of the daily climatology) ## for all images in the anomaly time period index_image = ee.Image(anomaly_coll.sum()).divide(ee.Image( mean_coll.sum())) return index_image
#!/usr/bin/env python """Reverse mask a region. Create an image that masks everything except for the specified polygon. """ import ee from ee_plugin import Map Map.setCenter(-100, 40, 4) fc = (ee.FeatureCollection('RESOLVE/ECOREGIONS/2017').filter(ee.Filter().eq( 'ECO_NAME', 'Great Basin shrub steppe'))) # Start with a black image. empty = ee.Image(0).toByte() # Fill and outline the polygons in two colors filled = empty.paint(fc, 2) both = filled.paint(fc, 1, 5) # Mask off everything that matches the fill color. result = both.mask(filled.neq(2)) Map.addLayer(result, { 'palette': '000000,FF0000', 'max': 1, 'opacity': 0.5 }, "Basin")
import unittest import ee import re from inst.python.ee_map import * ee.Initialize() EE_TILES = 'https://earthengine.googleapis.com/map/{mapid}/{{z}}/{{x}}/{{y}}?token={token}' query = re.compile('token=(.*)') # test-cases geom = ee.Geometry.Point([-73.53522, -15.75453]) geom_viz = {"pointRadius": 10, "color": "FF0000"} eeobject_fc = ee.FeatureCollection("users/csaybar/DLdemos/train_set") image = ee.Image("LANDSAT/LC08/C01/T1/LC08_044034_20140318") collection = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")\ .filter(ee.Filter().eq("WRS_PATH", 44))\ .filter(ee.Filter().eq("WRS_ROW", 34))\ .filterDate("2014-01-01", "2015-01-01")\ .sort("CLOUD_COVER") class test_map(unittest.TestCase): def test_map_geom(self): token = query.findall(ee_map_py(eeobject=geom, vizparams=geom_viz))[0] self.assertIsNotNone(token) def test_map_fc(self): token = query.findall( ee_map_py(eeobject=eeobject_fc, vizparams=geom_viz))[0] self.assertIsNotNone(token)
def generate_in(self, left, comp, right, exist_not): filter = ee.Filter().inList(left, right) if exist_not: return filter.Not() return filter
def __init__(self, sql, geojson=None, flags=None): self._raw = sql self._parsed = sqlparse.parse(sql)[0] self.geojson = self._geojson_to_featurecollection(geojson) self.flags = flags # <-- Will be used in a later version of the code self._filters = { '<': ee.Filter().lt, '<=': ee.Filter().lte, '>': ee.Filter().gt, '>=': ee.Filter().gte, '<>': ee.Filter().neq, '=': ee.Filter().eq, '%LIKE%': ee.Filter().stringContains, '%LIKE': ee.Filter().stringEndsWith, 'LIKE%': ee.Filter().stringStartsWith, 'LIKE': ee.Filter().eq, } self._comparisons = {'AND': ee.Filter().And, 'OR': ee.Filter().Or}
def run(self): """Run method that performs all the real work""" #ee.Initialize() # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = Sentinel2DownloadDialog() # Add base map base_map = QgsProject.instance().mapLayersByName('Google Satellite') if len(base_map) == 0: urlWithParams = 'type=xyz&url=https://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D&zmax=19&zmin=0' rlayer = QgsRasterLayer(urlWithParams, 'Google Satellite', 'wms') if rlayer.isValid(): QgsProject.instance().addMapLayer(rlayer) else: self.iface.messageBar().pushMessage( "Không mở được bản đồ nền!", level=Qgis.Success, duration=5) self.laydanhsachtinh() self.dlg.comboTinh.currentIndexChanged.connect(self.laydanhsachhuyen) self.dlg.comboHuyen.currentIndexChanged.connect(self.laydanhsachxa) self.tohopmau() self.dlg.show() result = self.dlg.exec_() if result: #Get date batdau = self.dlg.dateBdau.date() ketthuc = self.dlg.dateKthuc.date() bd_date = str(batdau) kt_date = str(ketthuc) # Get info tinhchon = self.dlg.comboTinh.currentText() huyenchon = self.dlg.comboHuyen.currentText() xachon = self.dlg.comboXa.currentText() mtinh = int(self.laymacode()['tcode']) mhuyen = int(self.laymacode()['hcode']) mxa = int(self.laymacode()['xcode']) may = int(self.dlg.inputMay.text()) khoang = int(self.dlg.inputKhoang.text()) ngayBatdau = str(self.layngay(bd_date)) ngayKetthuc = str(self.layngay(kt_date)) hcxvn = ee.FeatureCollection("users/nguyenvanthi/RGX_WGS84") commune = hcxvn.filter(ee.Filter(ee.Filter.eq('MATINH', mtinh))) \ .filter(ee.Filter(ee.Filter.eq('MAHUYEN', mhuyen))) \ .filter(ee.Filter(ee.Filter.eq('MAXA', mxa))) #Get buffer sbuffer = int(self.dlg.inputBuffer.text()) if sbuffer == 0: commune_buffered = commune else: commune_buffered = commune.geometry().buffer(sbuffer) #Band combinations rgbMethod = self.dlg.comboRGB.currentIndex() if rgbMethod == 0: bands = ['B4', 'B3', 'B2'] # Natural Color elif rgbMethod == 1: bands = ['B8', 'B4', 'B3'] # Color Infrared elif rgbMethod == 2: bands = ['B12', 'B8A', 'B4'] # Short-wave Infrared elif rgbMethod == 3: bands = ['B11', 'B8', 'B2'] # Agriculture elif rgbMethod == 4: bands = ['B12', 'B11', 'B2'] # Geology else: bands = ['B4', 'B3', 'B1'] # Bathymetric S2_Collection = ee.ImageCollection("COPERNICUS/S2") \ .filterDate(ngayBatdau, ngayKetthuc).select(bands) \ .filterBounds(commune_buffered) \ .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', "less_than", may) \ .sort('CLOUD_COVERAGE_ASSESSMENT', True) #Get the first image in the collection S2 = S2_Collection.first() vizParams = { 'bands': bands, 'min': 0, 'max': 2000, 'gamma': 0.8 } image_date1 = ee.Date( S2.get('system:time_start')).format('Y-M-d').getInfo() soluonganh = S2_Collection.size().getInfo() tmp = self.khoangngay(image_date1, khoang) S22 = ee.ImageCollection("COPERNICUS/S2").filterDate(tmp['bd'], tmp['kt']) \ .select(bands) \ .filterBounds(commune_buffered) \ .median()\ .clip(commune_buffered) Map.centerObject(commune, 14) Map.addLayer( S2.clip(commune_buffered), vizParams, "S2_" + str(xachon) + "_" + image_date1 + " (Ảnh đơn)") Map.addLayer( S22, vizParams, "S2_" + str(xachon) + "_" + image_date1 + " (Tập hợp)") Map.addLayer(commune_buffered, {'color': 'red'}, "RG_" + str(xachon), False, 0.2) ### Save image to Google Drive3 ### Message bar info self.iface.messageBar().pushMessage( "Mở thành công ảnh Sentiel-2 của " + xachon + " " + huyenchon + " " + tinhchon + "!", level=Qgis.Success, duration=10) pass
def testAppend(self): """Verifies that appending filters with instance methods works.""" multi_filter = ee.Filter().eq('foo', 1).eq('bar', 2).eq('baz', 3) self.assertEquals(3, multi_filter.predicateCount())
def testStaticVersions(self): """Verifies that static filter methods are equivalent to instance ones.""" self.assertEquals(ee.Filter().eq('foo', 1), ee.Filter.eq('foo', 1)) self.assertEquals(ee.Filter().neq('foo', 1), ee.Filter.neq('foo', 1)) self.assertEquals(ee.Filter().lt('foo', 1), ee.Filter.lt('foo', 1)) self.assertEquals(ee.Filter().gt('foo', 1), ee.Filter.gt('foo', 1)) self.assertEquals(ee.Filter().lte('foo', 1), ee.Filter.lte('foo', 1)) self.assertEquals(ee.Filter().gte('foo', 1), ee.Filter.gte('foo', 1)) self.assertEquals(ee.Filter().contains('foo', 1), ee.Filter.contains('foo', 1)) self.assertEquals(ee.Filter().not_contains('foo', 1), ee.Filter.not_contains('foo', 1)) self.assertEquals(ee.Filter().starts_with('foo', 1), ee.Filter.starts_with('foo', 1)) self.assertEquals(ee.Filter().not_starts_with('foo', 1), ee.Filter.not_starts_with('foo', 1)) self.assertEquals(ee.Filter().ends_with('foo', 1), ee.Filter.ends_with('foo', 1)) self.assertEquals(ee.Filter().not_ends_with('foo', 1), ee.Filter.not_ends_with('foo', 1)) f1 = ee.Filter().And(ee.Filter().eq('foo', 1), ee.Filter().eq('foo', 2)) f2 = ee.Filter.And(ee.Filter.eq('foo', 1), ee.Filter().eq('foo', 2)) self.assertEquals(f1, f2) ring1 = ee.Geometry.Polygon(1, 2, 3, 4, 5, 6) f1 = ee.Filter().geometry(ring1) f2 = ee.Filter.geometry(ring1) self.assertEquals(f1, f2) d1 = datetime.datetime.strptime('1/1/2000', '%m/%d/%Y') d2 = datetime.datetime.strptime('1/1/2001', '%m/%d/%Y') f1 = ee.Filter().date(d1, d2) f2 = ee.Filter.date(d1, d2) self.assertEquals(f1, f2)
#!/usr/bin/env python """Composite an image collection and clip it to a boundary from a table. See also: Filtered Seasonal Composite, which filters the collection by bounds instead. """ import datetime import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-120, 37, 6) # Create a Landsat 7, median-pixel composite for Spring of 2000. collection = (ee.ImageCollection('LANDSAT/LE07/C01/T1') .filterDate(datetime.datetime(2000, 4, 1), datetime.datetime(2000, 7, 1))) image1 = collection.median() # Clip to the output image to the California state boundary. fc = (ee.FeatureCollection('TIGER/2018/States') .filter(ee.Filter().eq('NAME', 'California'))) image2 = image1.clipToCollection(fc) # Select the red, green and blue bands. image = image2.select('B3', 'B2', 'B1') ee.mapclient.addToMap(image, {'gain': [1.4, 1.4, 1.1]})
Map.setOptions('HYBRID') # %% ''' ## Add Earth Engine Python script ''' # %% Map.setCenter(-93, 40, 4) # Select the 'Sonoran desert' feature from the TNC Ecoregions fusion table. fc = ( ee.FeatureCollection('ft:1Ec8IWsP8asxN-ywSqgXWMuBaxI6pPaeh6hC64lA').filter( ee.Filter().eq('ECO_NAME', 'Sonoran desert'))) # Paint it into a blank image. image1 = ee.Image(0).mask(0) Map.addLayer(image1.paint(fc, 0, 5), {}, "TNC Ecoregions") # %% ''' ## Display Earth Engine data layers ''' # %% Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
#!/usr/bin/env python """Count features example. Count Panoramio photos near SF that mention bridges. """ import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-122.39, 37.7857, 12) photos_near_sf = ee.FeatureCollection( 'ft:1qpKIcYQMBsXLA9RLWCaV9D0Hus2cMQHhI-ViKHo') bridge_photos = photos_near_sf.filter( ee.Filter().Or(ee.Filter().contains('title', 'Bridge'), ee.Filter().contains('title', 'bridge'))) ee.mapclient.addToMap(photos_near_sf, {'color': '0040b0'}) ee.mapclient.addToMap(bridge_photos, {'color': 'e02070'}) print ('There are %d bridge photos around SF.' % bridge_photos.size().getInfo())
#!/usr/bin/env python """Composite an image collection and clip it to a boundary from a fusion table. See also: Filtered Seasonal Composite, which filters the collection by bounds instead. """ import datetime import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-110, 40, 5) # Create a Landsat 7, median-pixel composite for Spring of 2000. collection = (ee.ImageCollection('LANDSAT/LE07/C01/T1').filterDate( datetime.datetime(2000, 4, 1), datetime.datetime(2000, 7, 1))) image1 = collection.median() # Clip to the output image to the state boundary. fc = ( ee.FeatureCollection('ft:1fRY18cjsHzDgGiJiS2nnpUU3v9JPDc2HNaR7Xk8').filter( ee.Filter().eq('Name', 'California'))) image2 = image1.clipToCollection(fc) # Select the red, green and blue bands. image = image2.select('B3', 'B2', 'B1') ee.mapclient.addToMap(image, {'gain': [1.4, 1.4, 1.1]})
state = exportTable.status()['state'] while state in ['READY', 'RUNNING']: print state + '...' time.sleep(1) state = exportTable.status()['state'] print 'Done.', exportTable.status() # ============================= if __name__ == '__main__': ee.Initialize() ## example: https://ee-api.appspot.com/42582c90a626755098dce6d3274fe679 ## sums up flood cells by commune/village using time-series image collection ## Use my own Vietnamese Communes boundaries - limit for Dong Nai region only (PROC=713) fc = ee.FeatureCollection('ft:1V-cFoyZ74cySom_0v8o0nY9E7BHFDgfj_JMACvmf').filter(ee.Filter().eq('FIRST_PROC', 713)) # ee.mapclient.centerMap(107.2, 11.1, 10) # use only for checking # ee.mapclient.addToMap(fc, {'color': '800080'}) # test to see if it appears on the map ## Input images are MODIS - how about a week amount right after the 2006 flooding period.. collection = (ee.ImageCollection('MYD09GA') .filterDate(datetime.datetime(2006, 9, 2), datetime.datetime(2006, 9, 9)).select('sur_refl_b07')) ## the function being iterated over the time-series image collection.. def floodic(image): ## threshold = 0.08 ## gt = "greater than" evaluation method b7gt = image.multiply(0.0001).gt(0.08) ## zone summary statistics
def wrap(band, filt): band = ee.String(band) filt = ee.Filter(filt) newfilt = ee.Filter.listContains(leftField='_BANDS_', rightValue=band) return ee.Filter.Or(filt, newfilt)
#!/usr/bin/env python # Lint as: python3 """Composite an image collection and clip it to a boundary from a fusion table. See also: Filtered Seasonal Composite, which filters the collection by bounds instead. """ import datetime import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-120, 37, 6) # Create a Landsat 7, median-pixel composite for Spring of 2000. collection = (ee.ImageCollection('LANDSAT/LE07/C01/T1').filterDate( datetime.datetime(2000, 4, 1), datetime.datetime(2000, 7, 1))) image1 = collection.median() # Clip to the output image to the California state boundary. fc = (ee.FeatureCollection('TIGER/2018/States').filter(ee.Filter().eq( 'NAME', 'California'))) image2 = image1.clipToCollection(fc) # Select the red, green and blue bands. image = image2.select('B3', 'B2', 'B1') ee.mapclient.addToMap(image, {'gain': [1.4, 1.4, 1.1]})
#!/usr/bin/env python """Reverse mask a region. Create an image that masks everything except for the specified polygon. """ import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-100, 40, 4) fc = ( ee.FeatureCollection('ft:1Ec8IWsP8asxN-ywSqgXWMuBaxI6pPaeh6hC64lA').filter( ee.Filter().eq('ECO_NAME', 'Great Basin shrub steppe'))) # Start with a black image. empty = ee.Image(0).toByte() # Fill and outline the polygons in two colors filled = empty.paint(fc, 2) both = filled.paint(fc, 1, 5) # Mask off everything that matches the fill color. result = both.mask(filled.neq(2)) ee.mapclient.addToMap(result, { 'palette': '000000,FF0000', 'max': 1, 'opacity': 0.5 })
#!/usr/bin/env python """Count features example. Count Panoramio photos near SF that mention bridges. """ import ee import ee.mapclient ee.Initialize() ee.mapclient.centerMap(-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'))) ee.mapclient.addToMap(photos_near_sf, {'color': '0040b0'}) ee.mapclient.addToMap(bridge_photos, {'color': 'e02070'}) print('There are {} bridge photos around SF.'.format( bridge_photos.size().getInfo()))