Python ee.List() Examples

The following are 30 code examples of ee.List(). 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: landsat_functions.py    From CrisisMappingToolkit with Apache License 2.0 6 votes vote down vote up
def rename_landsat_bands(collection, collectionName):
    '''Selects and renames the landsat bands we are interested in.  
       Works with any Landsat satellite.'''

    # The list of bands we are interested in
    # - temp = temperature.  Landsat8 splits this into two bands, we use the first of these.
    # - The panchromatic band might be nice but it is only on Landsat7/8
    LANDSAT_BANDS_OF_INTEREST = ee.List(['blue', 'green', 'red', 'nir', 'swir1', 'temp', 'swir2'])

    # The indices where these bands are found in the Landsat satellites
    LANDSAT_BAND_INDICES = {'L8': ee.List([1, 2, 3, 4, 5, 9, 6]),
                            'L7': ee.List([0, 1, 2, 3, 4, 5, 7]),
                            'L5': ee.List([0, 1, 2, 3, 4, 5, 6])}

    landsat_index = 'L8';
    if '5' in collectionName:
        landsat_index = 'L5'
    if '7' in collectionName:
        landsat_index = 'L7'

    return collection.select(LANDSAT_BAND_INDICES[landsat_index], LANDSAT_BANDS_OF_INTEREST) 
Example #2
Source File: eeWishart.py    From earthengine with MIT License 6 votes vote down vote up
def omnibus(imList,significance=0.0001,median=False):
    '''return change maps for sequential omnibus change algorithm'''    
    imList = ee.List(imList).map(multbyenl)    
    p = ee.Image(imList.get(0)).bandNames().length()
    k = imList.length() 
#  pre-calculate p-value array    
    ells = ee.List.sequence(1,k.subtract(1))
    first = ee.Dictionary({'k':k,'p':p,'median':median,'imList':imList,'pv_arr':ee.List([])})
    pv_arr = ee.List(ee.Dictionary(ells.iterate(ells_iter,first)).get('pv_arr'))      
#  filter p-values to generate cmap, smap, fmap and bmap
    cmap = ee.Image(imList.get(0)).select(0).multiply(0.0)
    smap = ee.Image(imList.get(0)).select(0).multiply(0.0)
    fmap = ee.Image(imList.get(0)).select(0).multiply(0.0)   
    bmap = ee.Image.constant(ee.List.repeat(0,k.subtract(1)))    
    threshold = ee.Image.constant(1-significance)
    first = ee.Dictionary({'ell':1,'threshold':threshold,'cmap':cmap,'smap':smap,'fmap':fmap,'bmap':bmap})
    return ee.Dictionary(pv_arr.iterate(filter_ell,first)) 
Example #3
Source File: imagecollection.py    From gee_tools with MIT License 6 votes vote down vote up
def containsAllBands(collection, bands):
    """ Filter a collection with images cotaining all 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.And(filt, newfilt)

    filt = ee.Filter(rest.iterate(wrap, filt0))
    return collection.filter(filt) 
Example #4
Source File: imagecollection.py    From gee_tools with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: imagecollection.py    From gee_tools with MIT License 6 votes vote down vote up
def enumerateProperty(collection, name='enumeration'):
    """

    :param collection:
    :param name:
    :return:
    """
    enumerated = eecollection.enumerate(collection)

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

    imlist = enumerated.map(over_list)
    return ee.ImageCollection(imlist) 
Example #6
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 #7
Source File: image.py    From gee_tools with MIT License 6 votes vote down vote up
def _add_suffix_prefix(image, value, option, bands=None):
    """ Internal function to handle addPrefix and addSuffix """
    if bands:
        bands = ee.List(bands)

    addon = ee.String(value)

    allbands = image.bandNames()
    bands_ = ee.List(ee.Algorithms.If(bands, bands, allbands))

    def over_bands(band, first):
        all = ee.List(first)
        options = ee.Dictionary({
            'suffix': ee.String(band).cat(addon),
            'prefix': addon.cat(ee.String(band))
        })
        return all.replace(band, ee.String(options.get(option)))

    newbands = bands_.iterate(over_bands, allbands)
    newbands = ee.List(newbands)
    return image.select(allbands, newbands) 
Example #8
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 #9
Source File: image.py    From gee_tools with MIT License 6 votes vote down vote up
def addMultiBands(imagesList):
    """ Image.addBands for many images. All bands from all images will be
    put together, so if there is one band with the same name in different
    images, the first occurrence will keep the name and the rest will have a
    number suffix ({band}_1, {band}_2, etc)

    :param imagesList: a list of images
    :type imagesList: list or ee.List
    :rtype: ee.Image
    """
    imagesList = ee.List(imagesList)
    first = ee.Image(imagesList.get(0))
    rest = imagesList.slice(1)

    def iteration(img, ini):
        ini = ee.Image(ini)
        img = ee.Image(img)
        return ini.addBands(img)

    return ee.Image(rest.iterate(iteration, first)) 
Example #10
Source File: list_test.py    From earthengine with MIT License 6 votes vote down vote up
def testMapping(self):
    lst = ee.List(['foo', 'bar'])
    body = lambda s: ee.String(s).cat('bar')
    mapped = lst.map(body)

    self.assertTrue(isinstance(mapped, ee.List))
    self.assertEquals(ee.ApiFunction.lookup('List.map'), mapped.func)
    self.assertEquals(lst, mapped.args['list'])

    # 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': 'Object'}]
    }
    expected_function = ee.CustomFunction(sig, body)
    self.assertEquals(expected_function.serialize(),
                      mapped.args['baseAlgorithm'].serialize()) 
Example #11
Source File: image.py    From gee_tools with MIT License 6 votes vote down vote up
def doyToDate(image, dateFormat='yyyyMMdd', year=None):
    """ Make a date band from a day of year band """
    if not year:
        year = image.date().get('year')

    doyband = image.select([0])
    leap = date.isLeap(year)
    limit = ee.Number(ee.Algorithms.If(leap, 365, 364))
    alldoys = ee.List.sequence(1, limit)

    def wrap(doy, i):
        i = ee.Image(i)
        doy = ee.Number(doy)
        d = date.fromDOY(doy, year)
        date_band = ee.Image.constant(ee.Number.parse(d.format(dateFormat)))
        condition = i.eq(doy)
        return i.where(condition, date_band)

    datei = ee.Image(alldoys.iterate(wrap, doyband))

    return datei.rename('date') 
Example #12
Source File: app.py    From earthengine with MIT License 6 votes vote down vote up
def iterate(image1,image2,niter,first):
#   simulated iteration of MAD for debugging          
#   result = iterate(image1,image2,niter,first)   
    for i in range(1,niter+1):
        result = ee.Dictionary(imad(i,first))
        allrhos = ee.List(result.get('allrhos'))
        chi2 = ee.Image(result.get('chi2'))
        MAD = ee.Image(result.get('MAD'))
        first = ee.Dictionary({'image':image1.addBands(image2),
                               'allrhos':allrhos,
                               'chi2':chi2,
                               'MAD':MAD})
    return result


#------------------
# helper functions
#------------------ 
Example #13
Source File: algorithms.py    From gee_tools with MIT License 5 votes vote down vote up
def _rescale(image, bands=None, thermal_bands=None, original='TOA',
                 to='SR', number='all'):
        """ Rescaling logic """
        if not bands:
            bands = ['B1','B2','B3','B4','B5','B6','B7']
        bands = ee.List(bands)

        if not thermal_bands:
            thermal_bands = ['B10', 'B11']
        thermal_bands = ee.List(thermal_bands)

        allbands = bands.cat(thermal_bands)

        if number == '8':
            max_raw = 65535
        else:
            max_raw = 255

        if original == 'TOA' and to == 'SR':
            scaled = image.select(bands).multiply(10000).toInt16()
            scaled_thermal = image.select(thermal_bands).multiply(10).toInt16()
        elif original == 'SR' and to == 'TOA':
            scaled = image.select(bands).toFloat().divide(10000)
            scaled_thermal = image.select(thermal_bands).toFloat().divide(10)
        elif original == 'TOA' and to == 'RAW':
            scaled = tools.image.parametrize(image.select(bands), (0, 1),
                                             (0, max_raw))
            scaled_thermal = tools.image.parametrize(image.select(bands), (0, 1),
                                                     (0, max_raw)).multiply(1000)

        original_bands = image.bandNames()

        rest_bands = tools.ee_list.difference(original_bands, allbands)

        rest_image = image.select(rest_bands)

        return rest_image.addBands(scaled).addBands(scaled_thermal) 
Example #14
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def repeatBand(image, times=None, names=None, properties=None):
    """ Repeat one band. If the image parsed has more than one band, the first
    will be used """
    band = ee.Image(image.select([0]))
    if times is not None:
        times = ee.Number(times)
        proxylist = ee.List.repeat(0, times.subtract(1))
        def add(band, i):
            band = ee.Image(band)
            i = ee.Image(i)
            return i.addBands(band)
        proxyImg = proxylist.map(lambda n: band)
        repeated = ee.Image(proxyImg.iterate(add, band))
    else:
        newNames = ee.List(names)
        firstName = ee.String(newNames.get(0))
        rest = ee.List(newNames.slice(1))
        def add(name, i):
            name = ee.String(name)
            i = ee.Image(i)
            return i.addBands(band.rename(name))
        first = band.rename(firstName)
        repeated = ee.Image(rest.iterate(add, first))

    if properties:
        repeated = repeated.setMulti(properties)

    return ee.Image(repeated) 
Example #15
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def sumBands(image, name="sum", bands=None):
    """ Adds all *bands* values and puts the result on *name*.

    There are 2 ways to use it:

    .. code:: python

        img = ee.Image("LANDSAT/LC8_L1T_TOA_FMASK/LC82310902013344LGN00")
        newimg = Image.sumBands(img, "added_bands", ("B1", "B2", "B3"))

    :param name: name for the band that contains the added values of bands
    :type name: str
    :param bands: names of the bands to be added. If None (default) it sums
        all bands
    :type bands: tuple
    :return: the parsed image with one additional band with the sum of `bands`
    :rtype: ee.Image
    """
    band_names = image.bandNames()
    if bands is None:
        bn = band_names
    else:
        bn = ee.List(list(bands))

    nim = ee.Image(0).select([0], [name])

    # TODO: check if passed band names are in band names # DONE
    def sum_bands(n, ini):
        condition = ee.List(band_names).contains(n)
        return ee.Algorithms.If(condition,
                                ee.Image(ini).add(image.select([n])),
                                ee.Image(ini))

    newimg = ee.Image(bn.iterate(sum_bands, nim))

    return image.addBands(newimg) 
Example #16
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def computeBits(image, start, end, newName):
    """ Compute the bits of an image

    :param start: start bit
    :type start: int
    :param end: end bit
    :type end: int
    :param newName: new name for the band
    :type newName: str
    :return: A function which single argument is the image and returns a single
        band image of the extracted bits, giving the band a new name
    :rtype: function
    """
    pattern = ee.Number(0)
    start = ee.Number(start).toInt()
    end = ee.Number(end).toInt()
    newName = ee.String(newName)

    seq = ee.List.sequence(start, end)

    def toiterate(element, ini):
        ini = ee.Number(ini)
        bit = ee.Number(2).pow(ee.Number(element))
        return ini.add(bit)

    patt = seq.iterate(toiterate, pattern)

    patt = ee.Number(patt).toInt()

    good_pix = image.select([0], [newName]).toInt() \
        .bitwiseAnd(patt).rightShift(start)
    return good_pix.toInt() 
Example #17
Source File: cloud_mask.py    From gee_tools with MIT License 5 votes vote down vote up
def decodeBitsEE(bit_reader, qa_band):
    """
    :param bit_reader: the bit reader
    :type bit_reader: BitReader
    :param qa_band: name of the band that holds the bit information
    :type qa_band: str
    :return: a function to map over a collection. The function adds all
        categories masks as new bands
    """
    options = ee.Dictionary(bit_reader.info)
    categories = ee.List(bit_reader.all_categories)

    def wrap(image):
        def eachcat(cat, ini):
            ini = ee.Image(ini)
            qa = ini.select(qa_band)
            # get data for category
            data = ee.Dictionary(options.get(cat))
            lshift = ee.Number(data.get('lshift'))
            length = ee.Number(data.get('bit_length'))
            decoded = ee.Number(data.get('shifted'))
            # move = places to move bits right and left back
            move = lshift.add(length)
            # move bits right and left
            rest = qa.rightShift(move).leftShift(move)
            # subtract the rest
            norest = qa.subtract(rest)
            # right shift to compare with decoded data
            to_compare = norest.rightShift(lshift) ## Image
            # compare if is equal, return 0 if not equal, 1 if equal
            mask = to_compare.eq(decoded)
            # rename to the name of the category
            qa_mask = mask.select([0], [cat])

            return ini.addBands(qa_mask)
        return ee.Image(categories.iterate(eachcat, image))
    return wrap 
Example #18
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def goodPix(image, retain=None, drop=None, name='good_pix'):
    """ Get a 'good pixels' bands from the image's bands that retain the good
    pixels and drop the bad pixels. It will first retain the retainable bands
    and then drop the droppable ones

    :param image: the image
    :type image: ee.Image
    :param retain: names of the bands that hold good (want to retain) pixels,
        for example, a good quality band
    :type retain: tuple
    :param drop: names of the bands that hold bad (want to drop) pixels, for
        example a cloud mask band
    :type drop: tuple
    :param name: name for the resulting band
    :type name: str
    :rtype: ee.Image
    """
    to_retain = ee.List(retain)
    to_drop = ee.List(drop)

    def make_or(bandname, ini):
        ini = ee.Image(ini)
        band = image.select(bandname)
        return ini.Or(band)

    final_retain = ee.Image(to_retain.iterate(make_or, empty(0)))
    final_drop = ee.Image(to_drop.iterate(make_or, empty(0)))

    # not bad but not good (retain)
    not_bad_not_good = final_drop.And(final_retain)

    final = not_bad_not_good.bitwiseXor(final_drop)

    return final.select([0], [name]) 
Example #19
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def removeBands(image, bands):
    """ Remove the specified bands from an image """
    bnames = image.bandNames()
    bands = ee.List(bands)
    inter = ee_list.intersection(bnames, bands)
    diff = bnames.removeAll(inter)
    return image.select(diff) 
Example #20
Source File: utils.py    From gee_tools with MIT License 5 votes vote down vote up
def reduceRegionsPandas(data, index='system:index', add_coordinates=False,
                        duplicate_index=False):
    """ Transform data coming from Image.reduceRegions to a pandas dataframe

    :param data: data coming from Image.reduceRegions
    :type data: ee.Dictionary or dict
    :param index: the index of the dataframe
    :param add_coordinates: if True adds the coordinates to the dataframe
    :param duplicate_index: if True adds the index data to the dataframe too
    :return: a pandas dataframe
    :rtype: pd.DataFrame
    """
    if not isinstance(data, dict):
        if add_coordinates:
            def addCentroid(feat):
                feat = ee.Feature(feat)
                centroid = feat.centroid().geometry()
                coords = ee.List(centroid.coordinates())
                return feat.set('longitude', ee.Number(coords.get(0)),
                                'latitude', ee.Number(coords.get(1)))
            data = data.map(addCentroid)

        data = data.getInfo()

    features = data['features']

    d, indexes = [], []
    for feature in features:
        nf = deepcopy(feature)
        props = nf['properties']

        if not duplicate_index:
            props.pop(index) if index in props else props

        d.append(props)
        if index == 'system:index':
            indexes.append(feature['id'])
        else:
            indexes.append(feature['properties'][index])

    return pd.DataFrame(d, indexes) 
Example #21
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def applyMask(image, mask, bands=None, negative=True):
    """ Apply a passed positive mask """
    bands = bands or mask.bandNames()
    bands = ee.List(bands)
    def wrap(band, img):
        img = ee.Image(img)
        band = ee.String(band)
        m = mask.select(band)
        toapply = m.Not() if negative else m
        return img.updateMask(toapply)

    return ee.Image(bands.iterate(wrap, image)) 
Example #22
Source File: algorithms.py    From gee_tools with MIT License 5 votes vote down vote up
def harmonization(image, blue='B2', green='B3', red='B4', nir='B5',
                      swir='B6', swir2='B7', max_value=None):
        """ Harmonization of Landsat 8 images to be consistant with
        Landsat 7 images

        Roy, D.P., Kovalskyy, V., Zhang, H.K., Vermote, E.F., Yan, L.,
        Kumar, S.S, Egorov, A., 2016, Characterization of Landsat-7 to
        Landsat-8 reflective wavelength and normalized difference vegetation
        index continuity, Remote Sensing of Environment, 185, 57-70.
        (http://dx.doi.org/10.1016/j.rse.2015.12.024) Table 2 -
        reduced major axis (RMA) regression coefficients

        :param image: A Landsat 8 Image
        :param max_value: the maximum value for the optical bands. For float
            bands it is 1 (TOA), for int16 it is 10000 (SR) and for int8 it is
            255 (RAW). It default to 1 (TOA)
        :return:
        """
        bands = ee.List([blue, green, red, nir, swir, swir2])
        band_types = image.bandTypes().select(bands)

        if max_value is None:
            max_value = 1

        slopes = ee.Image.constant([0.9785, 0.9542, 0.9825,
                                    1.0073, 1.0171, 0.9949])
        itcp = ee.Image.constant([-0.0095, -0.0016, -0.0022,
                                  -0.0021, -0.0030, 0.0029])

        only_bands = image.select(bands)
        resampled = only_bands.resample('bicubic')

        harmonized = resampled.subtract(itcp.multiply(max_value)).divide(slopes)

        harmonized = harmonized.cast(band_types)

        # append rest of the bands
        return image.addBands(harmonized, overwrite=True) 
Example #23
Source File: list_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInternals(self):
    """Test eq(), ne() and hash()."""
    a = ee.List([1, 2])
    b = ee.List([2, 1])
    c = ee.List([1, 2])

    self.assertTrue(a.__eq__(a))
    self.assertFalse(a.__eq__(b))
    self.assertTrue(a.__eq__(c))
    self.assertTrue(b.__ne__(c))
    self.assertNotEquals(a.__hash__(), b.__hash__())
    self.assertEquals(a.__hash__(), c.__hash__()) 
Example #24
Source File: collection.py    From openet-ssebop-beta with Apache License 2.0 5 votes vote down vote up
def overpass(self, variables=None):
        """Return a collection of computed values for the overpass images

        Parameters
        ----------
        variables : list, optional
            List of variables that will be returned in the Image Collection.
            If variables is not set here it must be specified in the class
            instantiation call.

        Returns
        -------
        ee.ImageCollection

        Raises
        ------
        ValueError

        """
        # Does it make sense to use the class variable list if not set?
        if not variables:
            if self.variables:
                variables = self.variables
            else:
                raise ValueError('variables parameter must be set')

        return self._build(variables=variables) 
Example #25
Source File: lake_measure.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def detect_water(image):
    global collection_dict, sensor_band_dict#, spacecraft_dict
    shadowSumBands = ee.List(['nir','swir1','swir2'])# Bands for shadow masking
    # Compute several indicators of water and take the minimum of them.
    score = ee.Image(1.0)

    # Set up some params
    darkBands = ['green','red','nir','swir2','swir1']# ,'nir','swir1','swir2']
    brightBand = 'blue'

    # Water tends to be dark
    sum = image.select(shadowSumBands).reduce(ee.Reducer.sum())
    sum = rescale(sum,'img',[0.35,0.2]).clamp(0,1)
    score = score.min(sum)

    # It also tends to be relatively bright in the blue band
    mean = image.select(darkBands).reduce(ee.Reducer.mean())
    std = image.select(darkBands).reduce(ee.Reducer.stdDev())
    z = (image.select([brightBand]).subtract(std)).divide(mean)
    z = rescale(z,'img',[0,1]).clamp(0,1)
    score = score.min(z)

    # Water is at or above freezing

    score = score.min(rescale(image, 'img.temp', [273, 275]))

    # Water is nigh in ndsi (aka mndwi)
    ndsi = image.normalizedDifference(['green', 'swir1'])
    ndsi = rescale(ndsi, 'img', [0.3, 0.8])

    score = score.min(ndsi)
    return score.clamp(0,1) 
Example #26
Source File: imagecollection_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testImageCollectionConstructors(self):
    """Verifies that constructors understand valid parameters."""
    from_id = ee.ImageCollection('abcd')
    self.assertEquals(ee.ApiFunction.lookup('ImageCollection.load'),
                      from_id.func)
    self.assertEquals({'id': 'abcd'}, from_id.args)

    from_images = ee.ImageCollection([ee.Image(1), ee.Image(2)])
    self.assertEquals(ee.ApiFunction.lookup('ImageCollection.fromImages'),
                      from_images.func)
    self.assertEquals({'images': [ee.Image(1), ee.Image(2)]}, from_images.args)

    self.assertEquals(ee.ImageCollection([ee.Image(1)]),
                      ee.ImageCollection(ee.Image(1)))

    original = ee.ImageCollection('foo')
    from_other_image_collection = ee.ImageCollection(original)
    self.assertEquals(from_other_image_collection, original)

    l = ee.List([ee.Image(1)]).slice(0)
    from_list = ee.ImageCollection(l)
    self.assertEquals({'images': l}, from_list.args)

    from_computed_object = ee.ImageCollection(
        ee.ComputedObject(None, {'x': 'y'}))
    self.assertEquals({'x': 'y'}, from_computed_object.args) 
Example #27
Source File: image_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testRename(self):
    """Verifies image.rename varargs handling."""
    image = ee.Image([1, 2]).rename('a', 'b')
    self.assertEquals(ee.ApiFunction.lookup('Image.rename'), image.func)
    self.assertEquals(ee.List(['a', 'b']), image.args['names'])

    image = ee.Image([1, 2]).rename(['a', 'b'])
    self.assertEquals(ee.ApiFunction.lookup('Image.rename'), image.func)
    self.assertEquals(ee.List(['a', 'b']), image.args['names']) 
Example #28
Source File: 3_water_class_transition.py    From qgis-earthengine-examples with MIT License 5 votes vote down vote up
def createPieChartSliceDictionary(fc):
  return ee.List(fc.aggregate_array("transition_class_palette")) \
    .map(lambda p: {'color': p}).getInfo()


###############################
# Calculations
###############################

# Create a dictionary for looking up names of transition classes. 
Example #29
Source File: image_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testCombine(self):
    """Verifies the behavior of ee.Image.combine_()."""
    image1 = ee.Image([1, 2])
    image2 = ee.Image([3, 4])
    combined = ee.Image.combine_([image1, image2], ['a', 'b', 'c', 'd'])

    self.assertEquals(ee.ApiFunction.lookup('Image.select'), combined.func)
    self.assertEquals(ee.List(['.*']), combined.args['bandSelectors'])
    self.assertEquals(ee.List(['a', 'b', 'c', 'd']), combined.args['newNames'])
    self.assertEquals(ee.ApiFunction.lookup('Image.addBands'),
                      combined.args['input'].func)
    self.assertEquals({'dstImg': image1, 'srcImg': image2},
                      combined.args['input'].args) 
Example #30
Source File: image_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSelect(self):
    """Verifies regression in the behavior of empty ee.Image.select()."""
    image = ee.Image([1, 2]).select()
    self.assertEquals(ee.ApiFunction.lookup('Image.select'), image.func)
    self.assertEquals(ee.List([]), image.args['bandSelectors'])