Python ee.FeatureCollection() Examples

The following are 30 code examples of ee.FeatureCollection(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ee , or try the search function .
Example #1
Source File: map.py    From ipygee with MIT License 7 votes vote down vote up
def addMarker(self, marker, visParams=None, name=None, show=True,
                  opacity=None, replace=True,
                  inspect={'data':None, 'reducer':None, 'scale':None}):
        """ General method to add Geometries, Features or FeatureCollections
        as Markers """

        if isinstance(marker, ee.Geometry):
            self.addGeometry(marker, visParams, name, show, opacity, replace,
                             inspect)

        elif isinstance(marker, ee.Feature):
            self.addFeature(marker, visParams, name, show, opacity, replace,
                            inspect)

        elif isinstance(marker, ee.FeatureCollection):
            geometry = marker.geometry()
            self.addGeometry(marker, visParams, name, show, opacity, replace,
                             inspect) 
Example #2
Source File: featurecollection.py    From gee_tools with MIT License 6 votes vote down vote up
def enumerateProperty(col, name='enumeration'):
    """ Create a list of lists in which each element of the list is:
    [index, element]. For example, if you parse a FeatureCollection with 3
    Features you'll get: [[0, feat0], [1, feat1], [2, feat2]]

    :param collection: the collection
    :return: ee.FeatureCollection
    """
    enumerated = eecollection.enumerate(col)

    def over_list(l):
        l = ee.List(l)
        index = ee.Number(l.get(0))
        element = l.get(1)
        return ee.Feature(element).set(name, index)

    featlist = enumerated.map(over_list)
    return ee.FeatureCollection(featlist) 
Example #3
Source File: ee_report.py    From gee_asset_manager_addon with Apache License 2.0 6 votes vote down vote up
def assetsize(asset):
    ee.Initialize()
    header = ee.data.getAsset(asset)["type"]
    if header == "IMAGE_COLLECTION":
        collc = ee.ImageCollection(asset)
        size = collc.aggregate_array("system:asset_size")
        return [str(humansize(sum(size.getInfo()))), collc.size().getInfo()]
    elif header == "IMAGE":
        collc = ee.Image(asset)
        return [str(humansize(collc.get("system:asset_size").getInfo())), 1]
    elif header == "TABLE":
        collc = ee.FeatureCollection(asset)
        return [str(humansize(collc.get("system:asset_size").getInfo())), 1]
    elif header == "FOLDER":
        num = subprocess.check_output(
            "earthengine --no-use_cloud_api ls " + asset, shell=True
        ).decode("ascii")
        return ["NA", len(num.split("\n")) - 1]


# folder parse 
Example #4
Source File: collection_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testNestedMapping(self):
    """Verifies that nested map() calls produce distinct variables."""
    collection = ee.FeatureCollection('foo')
    result = collection.map(lambda x: collection.map(lambda y: [x, y]))

    # Verify the signatures.
    self.assertEquals(
        '_MAPPING_VAR_1_0',
        result.args['baseAlgorithm']._signature['args'][0]['name'])
    inner_result = result.args['baseAlgorithm']._body
    self.assertEquals(
        '_MAPPING_VAR_0_0',
        inner_result.args['baseAlgorithm']._signature['args'][0]['name'])

    # Verify the references.
    self.assertEquals(
        '_MAPPING_VAR_1_0',
        inner_result.args['baseAlgorithm']._body[0].varName)
    self.assertEquals(
        '_MAPPING_VAR_0_0',
        inner_result.args['baseAlgorithm']._body[1].varName) 
Example #5
Source File: production_gui.py    From CrisisMappingToolkit with Apache License 2.0 6 votes vote down vote up
def _updateMap(self):
        '''Updates the map with the current class'''

        self._clearDrawings() # Remove all existing drawings
        
        if not self.selectedClass:
            return

        # Convert from current class to an EE feature
        coordList = self.classDict[self.selectedClass]
        if len(coordList) == 0:
            return # Don't try to draw an empty list
        if len(coordList) < 3:
            eeRing = ee.Geometry.LineString(coordList)
        else:
            eeRing = ee.Geometry.LinearRing(coordList)

        # Add the feature to the map
        fc = ee.FeatureCollection(ee.Feature(eeRing))
        polyImage = ee.Image().byte().paint(fc, 0, 4)
        self.polygonOnMap = polyImage
        self.mapWidgetHandle.addToMap(polyImage, {}, self.selectedClass, True) 
Example #6
Source File: filter_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testBounds(self):
    """Verifies that geometry intersection filters work."""
    polygon = ee.Geometry.Polygon(1, 2, 3, 4, 5, 6)
    self.assertEquals(
        ee.ApiFunction.call_(
            'Filter.intersects', '.all',
            ee.ApiFunction.call_('Feature', polygon)),
        ee.Filter.geometry(polygon))

    # Collection-to-geometry promotion.
    collection = ee.FeatureCollection('foo')
    feature = ee.ApiFunction.call_(
        'Feature', ee.ApiFunction.call_('Collection.geometry', collection))
    self.assertEquals(
        ee.ApiFunction.call_('Filter.intersects', '.all', feature),
        ee.Filter.geometry(collection)) 
Example #7
Source File: filter_test.py    From earthengine with MIT License 6 votes vote down vote up
def testBounds(self):
    """Verifies that geometry intersection filters work."""
    polygon = ee.Geometry.Polygon(1, 2, 3, 4, 5, 6)
    self.assertEquals(
        ee.ApiFunction.call_(
            'Filter.intersects', '.all',
            ee.ApiFunction.call_('Feature', polygon)),
        ee.Filter.geometry(polygon))

    # Collection-to-geometry promotion.
    collection = ee.FeatureCollection('foo')
    feature = ee.ApiFunction.call_(
        'Feature', ee.ApiFunction.call_('Collection.geometry', collection))
    self.assertEquals(
        ee.ApiFunction.call_('Filter.intersects', '.all', feature),
        ee.Filter.geometry(collection)) 
Example #8
Source File: server.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def GetImageInfoTimeSeries(aoi):
    def GetImageInfo(img):
        return ee.Feature(None, {
            'id': img.get('system:id'),
            'time': img.get('system:time_start'),
            'cloud_cover': img.get('CLOUD_COVER')
        })

    def ToFeatureCollection(imageCollectionName):
        return ee.FeatureCollection(ee.ImageCollection(imageCollectionName).filterBounds(aoi).map(GetImageInfo))

    collectionNames = [
        'LANDSAT/LT4_L1T_TOA',
        'LANDSAT/LT5_L1T_TOA',
        'LANDSAT/LE7_L1T_TOA',
        'LANDSAT/LC8_L1T_TOA'
    ]

    fc = ee.FeatureCollection([])
    for n in collectionNames:
        fc = fc.merge(ToFeatureCollection(n))

    info = fc.sort('time').getInfo()

    return [i['properties'] for i in info['features']] 
Example #9
Source File: collection_test.py    From earthengine with MIT License 6 votes vote down vote up
def testNestedMapping(self):
    """Verifies that nested map() calls produce distinct variables."""
    collection = ee.FeatureCollection('foo')
    result = collection.map(lambda x: collection.map(lambda y: [x, y]))

    # Verify the signatures.
    self.assertEquals(
        '_MAPPING_VAR_1_0',
        result.args['baseAlgorithm']._signature['args'][0]['name'])
    inner_result = result.args['baseAlgorithm']._body
    self.assertEquals(
        '_MAPPING_VAR_0_0',
        inner_result.args['baseAlgorithm']._signature['args'][0]['name'])

    # Verify the references.
    self.assertEquals(
        '_MAPPING_VAR_1_0',
        inner_result.args['baseAlgorithm']._body[0].varName)
    self.assertEquals(
        '_MAPPING_VAR_0_0',
        inner_result.args['baseAlgorithm']._body[1].varName) 
Example #10
Source File: active_contour.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def to_ee_feature_collections(self):
        # currently only supports single unfilled region inside filled region
        exterior = []
        interior = []
        for l in self.loops:
            coords = map(lambda x: self.local_image.image_to_global(x[0], x[1]), l.nodes)
            f      = ee.Feature.Polygon(coords)
            if not l.clockwise:
                interior.append(f)
            else:
                exterior.append(f)
        return (ee.FeatureCollection(exterior), ee.FeatureCollection(interior)) 
Example #11
Source File: pull_MODIS_world.py    From crop_yield_prediction with MIT License 5 votes vote down vote up
def appendBand(current, previous):
    # Rename the band
    previous=ee.Image(previous)
    current = current.select([0,1,2,3,4,5,6])
    # Append it to the result (Note: only return current item on first element/iteration)
    accum = ee.Algorithms.If(ee.Algorithms.IsEqual(previous,None), current, previous.addBands(ee.Image(current)))
    # Return the accumulation
    return accum

# county_region = ee.FeatureCollection('ft:18Ayj5e7JxxtTPm1BdMnnzWbZMrxMB49eqGDTsaSp') 
Example #12
Source File: miscUtilities.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def regionIsInUnitedStates(region):
        '''Returns true if the current region is inside the US.'''
        
        # Extract the geographic boundary of the US.
        nationList = ee.FeatureCollection('ft:1tdSwUL7MVpOauSgRzqVTOwdfy17KDbw-1d9omPw')
        nation     = ee.Feature(nationList.filter(ee.Filter.eq('Country', 'United States')).first())
        nationGeo  = ee.Geometry(nation.geometry())
        result     = nationGeo.contains(region, 10)

        return (str(result.getInfo()) == 'True') 
Example #13
Source File: domain.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def _load_training_json(self, sensor_domain_folder, json_file_name):
        '''Load in a JSON file containing training features for an EE classifier'''
        
        # Load the input file
        json_file_path = os.path.join(sensor_domain_folder, json_file_name.text + '.json')
        print('Loading JSON training data: ' + json_file_path)
        with open(json_file_path, 'r') as f:
            feature_dict = json.load(f)
        if not feature_dict:
            raise Exception('Failed to read JSON file ' + json_file_path)

        # Convert the data into the desired training format
        # - The input data is N entries, each containing a polygon of points.
        # - The output data is ee formatted and classified as either 0 (land) or 1 (water)
        feature_list = []
        for key in feature_dict:
            # Assign as land unless water is in the key name!
            terrain_code = 0
            if 'water' in key.lower():
                terrain_code = 1
            #this_geometry = ee.Geometry.LinearRing(feature_dict[key])
            this_geometry = ee.Geometry.Polygon(feature_dict[key])
            this_feature  = ee.Feature(this_geometry, {'classification': terrain_code})
            feature_list.append(this_feature)
        
        self.training_features = ee.FeatureCollection(feature_list) 
Example #14
Source File: assetsizes.py    From Planet-GEE-Pipeline-CLI with Apache License 2.0 5 votes vote down vote up
def assetsize(asset):
    header = ee.data.getInfo(asset)["type"]
    if header == "ImageCollection":
        collc = ee.ImageCollection(asset)
        size = collc.aggregate_array("system:asset_size")
        print("")
        print(str(asset) + " ===> " + str(humansize(sum(size.getInfo()))))
        print("Total number of items in collection: " + str(collc.size().getInfo()))
    elif header == "Image":
        collc = ee.Image(asset)
        print("")
        print(
            str(asset)
            + " ===> "
            + str(humansize(collc.get("system:asset_size").getInfo()))
        )
    elif header == "Table":
        collc = ee.FeatureCollection(asset)
        print("")
        print(
            str(asset)
            + " ===> "
            + str(humansize(collc.get("system:asset_size").getInfo()))
        )
    elif header == "Folder":
        b = subprocess.check_output(
            "earthengine --no-use_cloud_api du " + asset + " -s", shell=True
        )
        num = subprocess.check_output(
            "earthengine --no-use_cloud_api ls " + asset, shell=True
        )
        size = humansize(float(b.strip().split(" ")[0]))
        print("")
        print(str(asset) + " ===> " + str(size))
        print("Total number of items in folder: " + str(len(num.split("\n")) - 1)) 
Example #15
Source File: featurecollection_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testDownload(self):
    """Verifies that Download ID and URL generation."""
    csv_url = ee.FeatureCollection(7).getDownloadURL('csv')

    self.assertEquals('/table', self.last_table_call['url'])
    self.assertEquals(
        {
            'table': ee.FeatureCollection(7).serialize(),
            'json_format': 'v2',
            'format': 'CSV'
        },
        self.last_table_call['data'])
    self.assertEquals('/api/table?docid=5&token=6', csv_url)

    everything_url = ee.FeatureCollection(8).getDownloadURL(
        'json', 'bar, baz', 'qux')
    self.assertEquals(
        {
            'table': ee.FeatureCollection(8).serialize(),
            'json_format': 'v2',
            'format': 'JSON',
            'selectors': 'bar, baz',
            'filename': 'qux'
        },
        self.last_table_call['data'])
    self.assertEquals('/api/table?docid=5&token=6', everything_url)

    self.assertEquals(ee.FeatureCollection(7).getDownloadUrl('csv'),
                      ee.FeatureCollection(7).getDownloadURL('csv')) 
Example #16
Source File: featurecollection_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testGetMapId(self):
    """Verifies that getMap() uses Collection.draw to draw."""
    collection = ee.FeatureCollection(5)
    mapid = collection.getMapId({'color': 'ABCDEF'})
    manual = ee.ApiFunction.call_('Collection.draw', collection, 'ABCDEF')

    self.assertEquals('fakeMapId', mapid['mapid'])
    self.assertEquals(manual, mapid['image']) 
Example #17
Source File: batch_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExportTableToGoogleDrive(self):
    """Verifies the Drive destined task created by Export.table.toDrive()."""
    test_collection = ee.FeatureCollection('foo')
    test_description = 'TestDescription'
    test_file_name_prefix = 'fooDriveFileNamePrefix'
    test_format = 'KML'
    expected_config = {
        'type': 'EXPORT_FEATURES',
        'state': 'UNSUBMITTED',
        'json': test_collection.serialize(),
        'description': test_description,
        'driveFileNamePrefix': test_file_name_prefix,
        'fileFormat': test_format,
    }

    # Ordered parameters
    task_ordered = ee.batch.Export.table.toDrive(
        test_collection, test_description,
        None, test_file_name_prefix, test_format)
    self.assertEquals('TESTTASKID', task_ordered.id)
    self.assertEquals(expected_config, task_ordered.config)

    # Updating expectations to test keyed parameters
    expected_config.update({
        'fileFormat': 'CSV',
        'description': 'myExportTableTask',
        'driveFolder': 'fooFolder'
    })

    # Test that deprecated parameters (driveFolder and driveFileNamePrefix)
    # still work.
    task_old_keys = ee.batch.Export.table.toDrive(
        collection=test_collection, driveFolder='fooFolder',
        driveFileNamePrefix='fooDriveFileNamePrefix')
    self.assertEquals(expected_config, task_old_keys.config)

    # Test that new parameters work
    task_new_keys = ee.batch.Export.table.toDrive(
        collection=test_collection, folder='fooFolder',
        fileNamePrefix='fooDriveFileNamePrefix')
    self.assertEquals(expected_config, task_new_keys.config) 
Example #18
Source File: geeadd.py    From gee_asset_manager_addon with Apache License 2.0 5 votes vote down vote up
def assetsize(asset):
    ee.Initialize()
    header = ee.data.getAsset(asset)["type"]
    if header == "IMAGE_COLLECTION":
        collc = ee.ImageCollection(asset)
        size = collc.aggregate_array("system:asset_size")
        print("")
        print(str(asset) + " ===> " + str(humansize(sum(size.getInfo()))))
        print("Total number of items in collection: {}".format(collc.size().getInfo()))
    elif header == "IMAGE":
        collc = ee.Image(asset)
        print("")
        print(
            str(asset)
            + " ===> "
            + str(humansize(collc.get("system:asset_size").getInfo()))
        )
    elif header == "TABLE":
        collc = ee.FeatureCollection(asset)
        print("")
        print(
            str(asset)
            + " ===> "
            + str(humansize(collc.get("system:asset_size").getInfo()))
        )
    elif header == "FOLDER":
        b = subprocess.check_output(
            "earthengine --no-use_cloud_api du " + asset + " -s", shell=True
        ).decode("ascii")
        num = subprocess.check_output(
            "earthengine --no-use_cloud_api ls " + asset, shell=True
        ).decode("ascii")
        size = humansize(float(b.strip().split(" ")[0]))
        print("")
        print(str(asset) + " ===> " + str(size))
        print("Total number of items in folder: {}".format(len(num.split("\n")) - 1)) 
Example #19
Source File: batch_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testStringRepresentation(self):
    """Verifies the string representation of tasks."""
    tasks = ee.batch.Task.list()
    self.assertEquals(
        '<Task EXPORT_IMAGE: FirstTestTask (RUNNING)>', str(tasks[0]))
    self.assertEquals(
        '<Task EXPORT_FEATURES: SecondTestTask (FAILED)>', str(tasks[1]))
    new_task = ee.batch.Export.table(ee.FeatureCollection('foo'), 'bar')
    self.assertEquals(
        '<Task EXPORT_FEATURES: bar (UNSUBMITTED)>', str(new_task))
    self.assertEquals(
        '<Task "foo">', str(ee.batch.Task('foo'))) 
Example #20
Source File: pull_MODIS_world_hist.py    From crop_yield_prediction with MIT License 5 votes vote down vote up
def appendBand(current, previous):
    # Rename the band
    previous=ee.Image(previous)
    current = current.select([0,1,2,3,4,5,6])
    # Append it to the result (Note: only return current item on first element/iteration)
    accum = ee.Algorithms.If(ee.Algorithms.IsEqual(previous,None), current, previous.addBands(ee.Image(current)))
    # Return the accumulation
    return accum

# county_region = ee.FeatureCollection('ft:18Ayj5e7JxxtTPm1BdMnnzWbZMrxMB49eqGDTsaSp') 
Example #21
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def fromKML(filename=None, data=None, crs=None, encoding=None):
    """ Create a list of Features from a KML file. Return a python tuple
    with ee.Feature inside. This is due to failing when attempting to create a
    FeatureCollection (Broken Pipe ERROR) out of the list. You can try creating
    it yourself casting the result of this function to a ee.List or using it
    directly as a FeatureCollection argument.

    :param filename: the name of the file to load
    :type filename: str
    :param crs: a coordinate reference system in EPSG format. If not specified
        it will try to get it from the geoJSON, and if not there it will rise
        an error
    :type: crs: str
    :return: a tuple of features.
    """
    geojsondict = utils.kmlToGeoJsonDict(filename, data, encoding)
    features = geojsondict['features']

    for feat in features:
        # remove styleUrl
        prop = feat['properties']
        if 'styleUrl' in prop:
            prop.pop('styleUrl')

        # remove Z value if needed
        geom = feat['geometry']
        ty = geom['type']
        if ty == 'GeometryCollection':
            geometries = geom['geometries']
            for g in geometries:
                c = g['coordinates']
                utils.removeZ(c)
        else:
            coords = geom['coordinates']
            utils.removeZ(coords)

    return fromGeoJSON(data=geojsondict, crs=crs) 
Example #22
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def toDict(collection, split_at=4000):
    """ Get the FeatureCollection as a dict object """
    size = collection.size()
    condition = size.gte(4999)

    def greater():
        size = collection.size()
        seq = tools.ee_list.sequence(0, size, split_at)
        limits = ee.List.zip(seq.slice(1), seq)

        def over_limits(n):
            n = ee.List(n)
            ini = ee.Number(n.get(0))
            end = ee.Number(n.get(1))
            return ee.FeatureCollection(collection.toList(ini, end))

        return limits.map(over_limits)

    collections = ee.List(
        ee.Algorithms.If(condition,
                         greater(),
                         ee.List([collection])))

    collections_size = collections.size().getInfo()

    col = ee.FeatureCollection(collections.get(0))
    content = col.getInfo()
    feats = content['features']

    for i in range(0, collections_size):
        c = ee.FeatureCollection(collections.get(i))
        content_c = c.getInfo()
        feats_c = content_c['features']
        feats = feats + feats_c

    content['features'] = feats

    return content 
Example #23
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def toGeoJSON(collection, name, path=None, split_at=4000):
    """ Export a FeatureCollection to a GeoJSON file

    :param collection: The collection to export
    :type collection: ee.FeatureCollection
    :param name: name of the resulting file
    :type name: str
    :param path: The path where to save the file. If None, will be saved
        in the current folder
    :type path: str
    :param split_at: limit to avoid an EE Exception
    :type split_at: int
    :return: A GeoJSON (.geojson) file.
    :rtype: file
    """
    import json
    import os

    if not path:
        path = os.getcwd()

    # name
    if name[-8:-1] != '.geojson':
        fname = name+'.geojson'

    content = toDict(collection, split_at)

    with open(os.path.join(path, fname), 'w') as thefile:
        thefile.write(json.dumps(content))

    return thefile 
Example #24
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def toCSV(collection, filename, split_at=4000):
    """ Alternative to download a FeatureCollection as a CSV """
    d = toDict(collection, split_at)

    fields = list(d['columns'].keys())
    fields.append('geometry')

    features = d['features']

    ext = filename[-4:]
    if ext != '.csv':
        filename += '.csv'

    with open(filename, 'w') as thecsv:
        writer = csv.DictWriter(thecsv, fields)

        writer.writeheader()
        # write rows
        for feature in features:
            properties = feature['properties']
            fid = feature['id']
            geom = feature['geometry']['type']

            # match fields
            properties['system:index'] = fid
            properties['geometry'] = geom

            # write row
            writer.writerow(properties)

        return thecsv 
Example #25
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def toAsset(table, assetPath, name=None, create=True, verbose=False, **kwargs):
    """ This function can create folders and ImageCollections on the fly.
    The rest is the same to Export.image.toAsset. You can pass the same
    params as the original function

    :param table: the feature collection to upload
    :type table: ee.FeatureCollection
    :param assetPath: path to upload the image (only PATH, without
        filename)
    :type assetPath: str
    :param name: filename for the image (AssetID will be assetPath + name)
    :type name: str
    :return: the tasks
    :rtype: ee.batch.Task
    """

    # Check if the user is specified in the asset path
    is_user = (assetPath.split('/')[0] == 'users')
    if not is_user:
        user = ee.batch.data.getAssetRoots()[0]['id']
        assetPath = "{}/{}".format(user, assetPath)

    if create:
        # Recrusive create path
        path2create = assetPath #  '/'.join(assetPath.split('/')[:-1])
        utils.createAssets([path2create], 'Folder', True)

    # Asset ID (Path + name)
    assetId = '/'.join([assetPath, name])
    # Description
    description = utils.matchDescription(name)
    # Init task
    task = ee.batch.Export.table.toAsset(table, assetId=assetId,
                                         description=description, **kwargs)
    task.start()
    if verbose:
        print('Exporting {} to {}'.format(name, assetPath))

    return task 
Example #26
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def paint(image, featurecollection, vis_params=None, color='black', width=1,
          fillColor=None, **kwargs):
    """ Paint a FeatureCollection onto an Image. Returns an Image with three
    bands: vis-blue, vis-geen, vis-red (uint8)

    It admits the same parameters as ee.FeatureCollection.style
    """
    if not fillColor:
        fillColor = "#00000000"
    if not vis_params:
        firstband = ee.String(image.bandNames().get(0))
        vis_params = dict(bands=[firstband, firstband, firstband], min=0,
                          max=1)
    region = image.geometry()
    filtered = ee.FeatureCollection(
        ee.Algorithms.If(
            region.isUnbounded(),
            featurecollection,
            featurecollection.filterBounds(region)
        ))
    fcraster = filtered.style(color=color, width=width, fillColor=fillColor,
                              **kwargs)
    mask = fcraster.reduce('sum').gte(0).rename('mask')
    topaint = image.visualize(**vis_params)
    final = topaint.where(mask, fcraster)
    final = final.copyProperties(source=image)
    properties = image.propertyNames()
    final = ee.Image(ee.Algorithms.If(
        properties.contains('system:time_start'),
        final.set('system:time_start', image.date().millis()),
        final))
    final = ee.Image(ee.Algorithms.If(
        properties.contains('system:time_end'),
        final.set('system:time_end', ee.Number(image.get('system:time_end'))),
        final))

    return final 
Example #27
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def addId(collection, name='id', start=1):
    """ Add a unique numeric identifier, from parameter 'start' to
    collection.size() stored in a property called with parameter 'name'

    :param collection: the collection
    :type collection: ee.FeatureCollection
    :param name: the name of the resulting property
    :type name: str
    :param start: the number to start from
    :type start: int
    :return: the parsed collection with a new property
    :rtype: ee.FeatureCollection
    """
    start = ee.Number(start)
    collist = collection.toList(collection.size())
    first = ee.Feature(collist.get(0))
    rest = collist.slice(1)

    # Set first id
    first = ee.List([first.set(name, start)])

    # Set rest
    def over_col(feat, last):
        last = ee.List(last)
        last_feat = ee.Feature(last.get(-1))
        feat = ee.Feature(feat)
        last_id = ee.Number(last_feat.get('id'))
        return last.add(feat.set('id', last_id.add(1)))

    return ee.FeatureCollection(ee.List(rest.iterate(over_col, first))) 
Example #28
Source File: featurecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def enumerateSimple(collection, name='ENUM'):
    """ Simple enumeration of features inside a collection. Each feature stores
     its enumeration, so if the order of features changes over time, the
     numbers will not be in order """

    size = collection.size()
    collist = collection.toList(size)
    seq = ee.List.sequence(0, size.subtract(1))
    def wrap(n):
        n = ee.Number(n).toInt()
        feat = collist.get(n)
        return ee.Feature(feat).set(name, n)
    fc = ee.FeatureCollection(seq.map(wrap))

    return ee.FeatureCollection(fc.copyProperties(source=collection)) 
Example #29
Source File: batch_test.py    From earthengine with MIT License 5 votes vote down vote up
def testTaskStart(self):
    """Verifies that Task.start() calls the server appropriately."""
    task = ee.batch.Export.table(ee.FeatureCollection('foo'), 'bar')
    task.start()
    self.assertEquals('TESTTASKID', self.start_call_params['id'])
    self.assertEquals('bar', self.start_call_params['description']) 
Example #30
Source File: maptools.py    From ipygee with MIT License 5 votes vote down vote up
def paint(geometry, outline_color='black', fill_color=None, outline=2):
    """ Paint a Geometry, Feature or FeatureCollection """

    def overlap(image_back, image_front):
        mask_back = image_back.mask()
        mask_front = image_front.mask()
        entire_mask = mask_back.add(mask_front)
        mask = mask_back.Not()
        masked = image_front.updateMask(mask).unmask()

        return masked.add(image_back.unmask()).updateMask(entire_mask)

    if isinstance(geometry, ee.Feature) or isinstance(geometry, ee.FeatureCollection):
        geometry = geometry.geometry()

    if fill_color:
        fill = ee.Image().paint(geometry, 1).visualize(palette=[fill_color])

    if outline_color:
        out = ee.Image().paint(geometry, 1, outline).visualize(palette=[outline_color])

    if fill_color and outline_color:
        rgbVector = overlap(out, fill)
    elif fill_color:
        rgbVector = fill
    else:
        rgbVector = out

    return rgbVector