Python ee.ImageCollection() Examples

The following are 30 code examples of ee.ImageCollection(). 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: set_image_properties.py    From qgis-earthengine-examples with MIT License 7 votes vote down vote up
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) 
Example #2
Source File: collection_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testMapping(self):
    """Verifies the behavior of the map() method."""
    collection = ee.ImageCollection('foo')
    algorithm = lambda img: img.select('bar')
    mapped = collection.map(algorithm)

    self.assertTrue(isinstance(mapped, ee.ImageCollection))
    self.assertEquals(ee.ApiFunction.lookup('Collection.map'), mapped.func)
    self.assertEquals(collection, mapped.args['collection'])

    # Need to do a serialized comparison for the function body because
    # variables returned from CustomFunction.variable() do not implement
    # __eq__.
    sig = {
        'returns': 'Image',
        'args': [{'name': '_MAPPING_VAR_0_0', 'type': 'Image'}]
    }
    expected_function = ee.CustomFunction(sig, algorithm)
    self.assertEquals(expected_function.serialize(),
                      mapped.args['baseAlgorithm'].serialize()) 
Example #3
Source File: cdd_simple.py    From coded with MIT License 6 votes vote down vote up
def add_cloudscore7(image):
   """ Add cloud score for Landsat 7 """
   thedate = image.date()
   date_bef = thedate.advance(-1, 'day')
   date_aft = thedate.advance(1,'day')
   toa = ee.ImageCollection('LANDSAT/LE07/C01/T1_TOA'
           ).filterDate(date_bef, date_aft
           ).filter(ee.Filter.eq('WRS_PATH', path)
           ).filter(ee.Filter.eq('WRS_ROW', row)
           ).first()
   cs = ee.Algorithms.If(
          ee.Image(toa),
          ee.Image(ee.Algorithms.Landsat.simpleCloudScore(
          ee.Image(toa))).select('cloud'),
          ee.Image(0).rename(['cloud']))
   mask = ee.Image(cs).lt(ee.Image(cloud_score))
   if aoi:
     return image.updateMask(mask).select(['B1','B2', 'B3','B4','B5','B7']).clip(aoi)
   else:
     return image.updateMask(mask).select(['B1','B2', 'B3','B4','B5','B7']) 
Example #4
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 #5
Source File: cdd_simple.py    From coded with MIT License 6 votes vote down vote up
def add_cloudscore8(image):
   """ Add cloud score for Landsat 8 """
   thedate = image.date()
   date_bef = thedate.advance(-1, 'day')
   date_aft = thedate.advance(1,'day')
   toa = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA'
           ).filterDate(date_bef, date_aft
           ).filter(ee.Filter.eq('WRS_PATH', path)
           ).filter(ee.Filter.eq('WRS_ROW', row)
           ).first()
   cs = ee.Algorithms.If(
          ee.Image(toa),
          ee.Image(ee.Algorithms.Landsat.simpleCloudScore(
          ee.Image(toa))).select('cloud'), 
          ee.Image(0).rename(['cloud']))
   mask = ee.Image(cs).lt(ee.Image(cloud_score))
   if aoi:
     return image.updateMask(mask).select(['B1','B2', 'B3','B4','B5','B7']).clip(aoi)
   else:
     return image.updateMask(mask).select(['B1','B2', 'B3','B4','B5','B7'])


#  MAIN WORK 

# JAVASCRIPT GLOBALS 
Example #6
Source File: imageRetrievalFunctions.py    From CrisisMappingToolkit with Apache License 2.0 6 votes vote down vote up
def get_image_collection_landsat(bounds, start_date, end_date, collectionName='LT5_L1T'):
    '''Retrieve Landsat imagery for the selected location and dates.'''

    ee_bounds  = bounds
    ee_points  = ee.List(bounds.bounds().coordinates().get(0))
    points     = ee_points.getInfo()
    points     = map(functools.partial(apply, ee.Geometry.Point), points)
#    collection = ee.ImageCollection(collectionName).filterDate(start_date, end_date) \
#                                    .filterBounds(points[0]).filterBounds(points[1]) \
#                                    .filterBounds(points[2]).filterBounds(points[3])
    collection = ee.ImageCollection(collectionName).filterDate(start_date, end_date) \
                                    .filterBounds(bounds.centroid())
                                    
    # Select and rename the bands we want
    temp = cmt.util.landsat_functions.rename_landsat_bands(collection, collectionName)
    return temp.sort('system:time_start') 
Example #7
Source File: app_sav.py    From earthengine with MIT License 6 votes vote down vote up
def simonf(path):
    
    def sel(image):
        return ee.Image(image).select(['VV','VH'])
        
    images = ee.List(  
       [ee.Image(path+'S1A_IW_GRDH_1SDV_20160305T171543_20160305T171608_010237_00F1FA_49DC'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160329T171543_20160329T171608_010587_00FBF9_B4DE'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160410T171538_20160410T171603_010762_010122_CEF6'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160422T171539_20160422T171604_010937_010677_03F6'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160504T171539_20160504T171604_011112_010BED_80AF'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160516T171540_20160516T171605_011287_011198_FC21'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160528T171603_20160528T171628_011462_011752_F570'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160609T171604_20160609T171629_011637_011CD1_C2F5'), 
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160715T171605_20160715T171630_012162_012DA2_95A1'), 
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160727T171606_20160727T171631_012337_013359_29A6'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160808T171607_20160808T171632_012512_01392E_44C4'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160901T171608_20160901T171633_012862_0144E3_30E5'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20160925T171609_20160925T171634_013212_015050_8FDB'),
        ee.Image(path+'S1B_IW_GRDH_1SDV_20161001T171508_20161001T171533_002316_003E9D_D195'), 
        ee.Image(path+'S1A_IW_GRDH_1SDV_20161007T171609_20161007T171634_013387_0155CD_F513'), 
        ee.Image(path+'S1A_IW_GRDH_1SDV_20161019T171609_20161019T171634_013562_015B60_27FF'),
        ee.Image(path+'S1A_IW_GRDH_1SDV_20161031T171609_20161031T171634_013737_0160BD_4FAE') ] )
    
    return ee.ImageCollection(images.map(sel)) 
Example #8
Source File: app_sav.py    From earthengine with MIT License 6 votes vote down vote up
def simon(path):
    images = ee.List(  
        [ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160305T171543_20160305T171608_010237_00F1FA_49DC')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160329T171543_20160329T171608_010587_00FBF9_B4DE')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160410T171538_20160410T171603_010762_010122_CEF6')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160422T171539_20160422T171604_010937_010677_03F6')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160504T171539_20160504T171604_011112_010BED_80AF')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160516T171540_20160516T171605_011287_011198_FC21')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160528T171603_20160528T171628_011462_011752_F570')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160609T171604_20160609T171629_011637_011CD1_C2F5')), 
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160715T171605_20160715T171630_012162_012DA2_95A1')), 
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160727T171606_20160727T171631_012337_013359_29A6')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160808T171607_20160808T171632_012512_01392E_44C4')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160901T171608_20160901T171633_012862_0144E3_30E5')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20160925T171609_20160925T171634_013212_015050_8FDB')),
         ee.call("S1.dB",ee.Image(path+'S1B_IW_GRDH_1SDV_20161001T171508_20161001T171533_002316_003E9D_D195')), 
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20161007T171609_20161007T171634_013387_0155CD_F513')), 
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20161019T171609_20161019T171634_013562_015B60_27FF')),
         ee.call("S1.dB",ee.Image(path+'S1A_IW_GRDH_1SDV_20161031T171609_20161031T171634_013737_0160BD_4FAE')) ] )
    return ee.ImageCollection(images) 
Example #9
Source File: algorithms.py    From gee_tools with MIT License 6 votes vote down vote up
def sumDistance(image, collection, bands=None, discard_zeros=False,
                name='sumdist'):
    """ Compute de sum of all distances between the given image and the
    collection passed
    
    :param image: 
    :param collection:
    :return: 
    """
    condition = isinstance(collection, ee.ImageCollection)

    if condition:
        collection = collection.toList(collection.size())

    accum = ee.Image(0).rename(name)

    def over_rest(im, ini):
        ini = ee.Image(ini)
        im = ee.Image(im)
        dist = ee.Image(euclideanDistance(image, im, bands, discard_zeros))\
                 .rename(name)
        return ini.add(dist)

    return ee.Image(collection.iterate(over_rest, accum)) 
Example #10
Source File: composite.py    From gee_tools with MIT License 6 votes vote down vote up
def medoid(collection, bands=None, discard_zeros=False):
    """ Medoid Composite

    :param collection: the collection to composite
    :type collection: ee.ImageCollection
    :param bands: the bands to use for computation. The composite will include
        all bands
    :type bands: list
    :param discard_zeros: Masked and pixels with value zero will not be use
        for computation. Improves dark zones.
    :type discard_zeros: bool
    :return: the Medoid Composite
    :rtype: ee.Image
    """
    medcol = medoidScore(collection, bands, discard_zeros)
    comp = medcol.qualityMosaic('sumdist')
    final = tools.image.removeBands(comp, ['sumdist', 'mask'])
    return final 
Example #11
Source File: bap.py    From geebap with GNU General Public License v3.0 6 votes vote down vote up
def make_proxy(self, image, collection, year):
        """ Make a proxy collection """

        size = collection.size()

        # unmask all bands
        unmasked = image.unmask()

        proxy_date = ee.Date('{}-01-01'.format(year))

        bands = image.bandNames()
        empty = tools.image.empty(0, bands)
        proxy = unmasked.where(unmasked, empty)

        proxy = proxy.set('system:time_start', proxy_date.millis())

        proxy_col = ee.ImageCollection.fromImages([proxy])

        return ee.ImageCollection(ee.Algorithms.If(size.gt(0),
                                                   collection,
                                                   proxy_col)) 
Example #12
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 #13
Source File: imagecollection.py    From gee_tools with MIT License 6 votes vote down vote up
def fillWithLast(collection):
    """ Fill masked values of each image pixel with the last available
    value

    :param collection: the collection that holds the images that will be filled
    :type collection: ee.ImageCollection
    :rtype: ee.ImageCollection
    """
    collector = ee.List([])
    def overcol(i, collect):
        collect = ee.List(collect)
        def true():
            last = ee.Image(collect.get(-1))
            mask = i.mask().Not()
            return collect.add(ee.Image(i.unmask().where(mask, last)))
        def false():
            return collect.add(i)

        return ee.List(ee.Algorithms.If(collect.size(), true(), false()))

    return ee.ImageCollection.fromImages(collection.iterate(overcol, collector)) 
Example #14
Source File: collection_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testIteration(self):
    """Verifies the behavior of the iterate() method."""
    collection = ee.ImageCollection('foo')
    first = ee.Image(0)
    algorithm = lambda img, prev: img.addBands(ee.Image(prev))
    result = collection.iterate(algorithm, first)

    self.assertEquals(ee.ApiFunction.lookup('Collection.iterate'), result.func)
    self.assertEquals(collection, result.args['collection'])
    self.assertEquals(first, result.args['first'])

    # Need to do a serialized comparison for the function body because
    # variables returned from CustomFunction.variable() do not implement
    # __eq__.
    sig = {
        'returns': 'Object',
        'args': [
            {'name': '_MAPPING_VAR_0_0', 'type': 'Image'},
            {'name': '_MAPPING_VAR_0_1', 'type': 'Object'}
        ]
    }
    expected_function = ee.CustomFunction(sig, algorithm)
    self.assertEquals(expected_function.serialize(),
                      result.args['function'].serialize()) 
Example #15
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def add(collection, image):
    """ Add an Image to the Collection

    **SERVER SIDE**

    """
    # TODO: handle a list of images
    collist = collection.toList(collection.size())
    append = collist.add(image)
    return ee.ImageCollection.fromImages(append) 
Example #16
Source File: imagecollection.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.Image(feat).set(name, n)
    fc = ee.ImageCollection.fromImages(seq.map(wrap))

    return ee.ImageCollection(fc.copyProperties(source=collection)) 
Example #17
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def wrapper(f, *arg, **kwargs):
    """ Wrap a function and its arguments into a mapping function for
    ImageCollections. The first parameter of the functions must be an Image,
    and it must return an Image.

    :param f: the function to be wrapped
    :type f: function
    :return: a function to use in ee.ImageCollection.map
    :rtype: function
    """
    def wrap(img):
        return f(img, *arg, **kwargs)
    return wrap 
Example #18
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def getId(collection):
    """ Get the ImageCollection id.

    **CLIENT SIDE**

    :type collection: ee.ImageCollection
    :return: the collection's id
    :rtype: str
    """
    return collection.limit(0).getInfo()['id'] 
Example #19
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def makeEqualInterval(collection, interval=1, unit='month'):
    """ Make a list of image collections filtered by the given interval,
    for example, one month. Starts from the end of the parsed collection

    :param collection: the collection
    :type collection: ee.ImageCollection
    :param interval: the interval
    :type interval: int
    :param unit: unit of the interval. Can be 'day', 'month', 'year'
    :rtype: ee.List
    """
    interval = int(interval)  # force to int
    collist = collection.sort('system:time_start').toList(collection.size())
    start_date = ee.Image(collist.get(0)).date()
    end_date = ee.Image(collist.get(-1)).date()

    ranges = date.daterangeList(start_date, end_date, interval, unit)

    def over_ranges(drange, ini):
        ini = ee.List(ini)
        drange = ee.DateRange(drange)
        start = drange.start()
        end = drange.end()
        filtered = collection.filterDate(start, end)
        condition = ee.Number(filtered.size()).gt(0)
        return ee.List(ee.Algorithms.If(condition, ini.add(filtered), ini))

    imlist = ee.List(ranges.iterate(over_ranges, ee.List([])))

    return imlist 
Example #20
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def normalDistributionProperty(collection, property, mean=None, std=None,
                               name='NORMAL_DISTRIBUTION'):
    """ Compute a normal distribution using a specified property, over an
    ImageCollection. For more see:
    https://en.wikipedia.org/wiki/Normal_distribution

    :param property: the name of the property to use
    :type property: str
    :param mean: the mean value. If None it will be computed from the source.
        defaults to None.
    :type mean: float
    :param std: the standard deviation value. If None it will be computed from
        the source. Defaults to None.
    :type std: float
    """
    if mean is None:
        imean = ee.Number(collection.aggregate_mean(property))
    else:
        imean = ee.Number(mean)

    if std is None:
        istd = ee.Number(collection.aggregate_total_sd(property))
    else:
        istd = ee.Number(std)

    imax = ee.Number(1)\
             .divide(istd.multiply(ee.Number(2).multiply(math.pi).sqrt()))

    return gaussFunctionProperty(collection, property, mean=imean,
                                 output_max=imax, std=istd, name=name) 
Example #21
Source File: test_d_interpolate.py    From openet-ssebop-beta with Apache License 2.0 5 votes vote down vote up
def scene_coll(variables, et_fraction=0.4, et=5, ndvi=0.6):
    """Return a generic scene collection to test scene interpolation functions

    Parameters
    ----------
    variables : list
        The variables to return in the collection
    et_fraction : float
    et : float
    ndvi : float

    Returns
    -------
    ee.ImageCollection

    """
    img = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044033_20170716') \
        .select(['B2']).double().multiply(0)
    mask = img.add(1).updateMask(1).uint8()

    time1 = ee.Number(ee.Date.fromYMD(2017, 7, 8).millis())
    time2 = ee.Number(ee.Date.fromYMD(2017, 7, 16).millis())
    time3 = ee.Number(ee.Date.fromYMD(2017, 7, 24).millis())

    # Mask and time bands currently get added on to the scene collection
    #   and images are unscaled just before interpolating in the export tool
    scene_img = ee.Image([img.add(et_fraction), img.add(et), img.add(ndvi), mask])\
        .rename(['et_fraction', 'et', 'ndvi', 'mask'])
    scene_coll = ee.ImageCollection([
        scene_img.addBands([img.add(time1).rename('time')]) \
            .set({'system:index': 'LE07_044033_20170708',
                  'system:time_start': time1}),
        scene_img.addBands([img.add(time2).rename('time')]) \
            .set({'system:index': 'LC08_044033_20170716',
                  'system:time_start': time2}),
        scene_img.addBands([img.add(time3).rename('time')]) \
            .set({'system:index': 'LE07_044033_20170724',
                  'system:time_start': time3}),
    ])
    return scene_coll.select(variables) 
Example #22
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def normalDistributionBand(collection, band, mean=None, std=None,
                           name='normal_distribution'):
    """ Compute a normal distribution using a specified band, over an
    ImageCollection. For more see:
    https://en.wikipedia.org/wiki/Normal_distribution

    :param band: the name of the property to use
    :type band: str
    :param mean: the mean value. If None it will be computed from the source.
        defaults to None.
    :type mean: float
    :param std: the standard deviation value. If None it will be computed from
        the source. Defaults to None.
    :type std: float
    """
    if mean is None:
        imean = ee.Image(collection.mean())
    else:
        imean = ee.Image.constant(mean)

    if std is None:
        istd = ee.Image(collection.reduce(ee.Reducer.stdDev()))
    else:
        istd = ee.Image.constant(std)

    ipi = ee.Image.constant(math.pi)

    imax = ee.Image(1) \
             .divide(istd.multiply(ee.Image.constant(2).multiply(ipi).sqrt()))

    return gaussFunctionBand(collection, band, mean=imean,
                             output_max=imax, std=istd, name=name) 
Example #23
Source File: domain.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def _load_source(self, source_element):
        '''load a data source for a band or mask, represented by the <source> tag.'''
        # A source is stored like this: {'mosaic', 'source', 'eeid'}
        d = dict()
        source_band = source_element.find('source')
        if source_band == None:
            return d # Source not specified, leave the dictionary empty!
            
        # if it's a mosaic, combine the images in an EE ImageCollection
        mosaic = source_band.get('mosaic')
        if mosaic != None:
            if mosaic.lower() == 'true':
                d['mosaic'] = True
            elif mosaic.lower() == 'false':
                d['mosaic'] = False
            else:
                raise Exception('Unexpected value of mosaic, %s.' % (source_band.get('mosaic')))
            
        # The name of the band in the source data, maybe not what we will call it in the output image.
        name = source_band.find('name')
        if name != None:
            # the name of the band in the original image
            d['source'] = name.text

        # Load more information about the band source
        self._loadPieceOfSourceInfo(source_band, 'eeid',       d) # The id of the image to load, if a single image.
        self._loadPieceOfSourceInfo(source_band, 'collection', d) # The ImageCollection name of the data, if any.
        self._loadPieceOfSourceInfo(source_band, 'start_date', d)    # Start and end dates used to filter an ImageCollection.
        self._loadPieceOfSourceInfo(source_band, 'end_date',   d)

        return d 
Example #24
Source File: mapclient_qt.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def getPixel(self, layer, x, y):
        collection = ee.ImageCollection([self.overlays[layer].eeobject])
        # note: scale likely not correct
        (lon, lat) = self.pixelCoordToLonLat(x, y)
        point_extracted = collection.getRegion(ee.Geometry.Point(lon, lat), 1)

        return point_extracted 
Example #25
Source File: lake_measure.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def get_image_collection(bounds, start_date, end_date):
    '''Retrieve Landsat 5 imagery for the selected location and dates'''
    # ee_bounds = apply(ee.Geometry.Rectangle, bounds)
    # ee_points = map(ee.Geometry.Point, [(bounds[0], bounds[1]), (bounds[0], bounds[3]),
    #                 (bounds[2], bounds[1]), (bounds[2], bounds[3])])
    global possibleSensors
    l5s = ee.ImageCollection(ee.Algorithms.If(possibleSensors.contains('L5'),getCollection('L5',bounds,start_date, end_date),getCollection('L5',bounds,ee.Date('1000-01-01'),ee.Date('1001-01-01'))))
    #l7s = ee.ImageCollection(ee.Algorithms.If(possibleSensors.contains('L7'),getCollection('L7',bounds,start_date, end_date),getCollection('L7',bounds,ee.Date('1000-01-01'),ee.Date('1001-01-01'))))
    l8s = ee.ImageCollection(ee.Algorithms.If(possibleSensors.contains('L8'),getCollection('L8',bounds,start_date, end_date),getCollection('L8',bounds,ee.Date('1000-01-01'),ee.Date('1001-01-01'))))
    ls = ee.ImageCollection(l5s.merge(l8s))
    # Clips image to rectangle around buffer. Thought this would free-up memory by reducing image size, but it doesn't
    # seem too :(
    # rect = bounds.bounds().getInfo()
    # ls = ls.map(lambda img: img.clip(rect))
    return ls 
Example #26
Source File: lake_measure.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def getCollection(sensor, bounds, startDate, endDate):
    global collection_dict, sensor_band_dict, bandNames
    ee_bounds = bounds
    collectionName = collection_dict.get(sensor)
    # Start with an un-date-confined collection of images
    WOD = ee.ImageCollection(collectionName).filterBounds(ee_bounds)
    # Filter by the dates
    landsat_set = WOD.filterDate(startDate,endDate)
    # Select and rename the bands
    landsat_set = landsat_set.select(sensor_band_dict.get(sensor),bandNames)
    return landsat_set 
Example #27
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 #28
Source File: batch_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExportVideoToDrive(self):
    """Verifies the task created by Export.video.toDrive()."""
    region = ee.Geometry.Rectangle(1, 2, 3, 4)
    collection = ee.ImageCollection([ee.Image(1), ee.Image(2)])
    expected_config = {
        'type': 'EXPORT_VIDEO',
        'state': 'UNSUBMITTED',
        'json': collection.serialize(),
        'description': 'TestVideoName',
        'crs': 'SR-ORG:6627',
        'driveFolder': 'test-folder',
        'driveFileNamePrefix': 'TestVideoName',
        'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
        'dimensions': 16,
        'crs_transform': 'bar'
    }

    # Test keyed parameters.
    task_keyed = ee.batch.Export.video.toDrive(
        collection=collection,
        description='TestVideoName',
        folder='test-folder',
        dimensions=16,
        crsTransform='bar',
        region=region['coordinates'])
    self.assertEquals('TESTTASKID', task_keyed.id)
    self.assertEquals(expected_config, task_keyed.config)

    # Test orderd parameters.
    task_ordered = ee.batch.Export.video.toDrive(
        collection, 'TestVideoName', 'test-folder', None, None, 16,
        region['coordinates'], None, 'SR-ORG:6627', 'bar')
    self.assertEquals(expected_config, task_ordered.config) 
Example #29
Source File: batch_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExportVideoToCloudStorage(self):
    """Verifies the task created by Export.video.toCloudStorage()."""
    region = ee.Geometry.Rectangle(1, 2, 3, 4)
    collection = ee.ImageCollection([ee.Image(1), ee.Image(2)])
    expected_config = {
        'type': 'EXPORT_VIDEO',
        'state': 'UNSUBMITTED',
        'json': collection.serialize(),
        'description': 'TestVideoName',
        'outputBucket': 'test-bucket',
        'outputPrefix': 'TestVideoName',
        'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
        'dimensions': 16,
        'crs_transform': 'bar',  # Transformed by _ConvertToServerParams.
        'crs': 'foo'
    }

    # Test keyed parameters.
    task_keyed = ee.batch.Export.video.toCloudStorage(
        collection=collection,
        description='TestVideoName',
        bucket='test-bucket',
        dimensions=16,
        region=region['coordinates'],
        crsTransform='bar',
        crs='foo')
    self.assertEquals('TESTTASKID', task_keyed.id)
    self.assertEquals(expected_config, task_keyed.config)

    # Test orderd parameters.
    task_ordered = ee.batch.Export.video.toCloudStorage(
        collection, 'TestVideoName', 'test-bucket', None, None, 16,
        region['coordinates'], None, 'foo', 'bar')
    self.assertEquals(expected_config, task_ordered.config) 
Example #30
Source File: batch_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExportVideo(self):
    """Verifies the task created by Export.video()."""
    region = ee.Geometry.Rectangle(1, 2, 3, 4)
    config = dict(region=region['coordinates'], dimensions=16)
    collection = ee.ImageCollection([ee.Image(1), ee.Image(2)])
    task = ee.batch.Export.video(collection, 'TestVideoName', config)
    self.assertEquals('TESTTASKID', task.id)
    # Defaults the destination to Drive.
    self.assertEquals(
        {
            'type': 'EXPORT_VIDEO',
            'state': 'UNSUBMITTED',
            'json': collection.serialize(),
            'description': 'TestVideoName',
            'crs': 'SR-ORG:6627',
            'driveFileNamePrefix': 'TestVideoName',
            'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
            'dimensions': 16
        },
        task.config)

    config['outputBucket'] = 'test-bucket'
    gcs_task = ee.batch.Export.video(collection, 'TestVideoName', config)
    self.assertEquals(
        {
            'type': 'EXPORT_VIDEO',
            'state': 'UNSUBMITTED',
            'json': collection.serialize(),
            'description': 'TestVideoName',
            'crs': 'SR-ORG:6627',
            'outputBucket': 'test-bucket',
            'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
            'dimensions': 16
        },
        gcs_task.config)