Python ee.Image() Examples

The following are 30 code examples of ee.Image(). 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: eeMad_old.py    From earthengine with MIT License 6 votes vote down vote up
def covw(centeredImage, weights=None, maxPixels=1e9):
    '''Return the (weighted) covariance matrix of a centered image''' 
    if weights==None:
        weights = centeredImage.multiply(0).add(ee.Image.constant(1))           
    B1 = centeredImage.bandNames().get(0)       
    b1 = weights.bandNames().get(0)     
    sumWeights = ee.Number(weights.reduceRegion(ee.Reducer.sum(), maxPixels=maxPixels).get(b1))  
    nPixels = ee.Number(centeredImage.reduceRegion(ee.Reducer.count(), maxPixels=maxPixels).get(B1))   
#    arr = dataArray(centeredImage.multiply(weights.sqrt()))
#    return arr.matrixTranspose().matrixMultiply(arr).divide(sumWeights)
    covW = centeredImage \
        .multiply(weights.sqrt()) \
        .toArray() \
        .reduceRegion(ee.Reducer.centeredCovariance(), maxPixels=1e9) \
        .get('array')
    return ee.Array(covW).multiply(nPixels.divide(sumWeights)) 
Example #2
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 #3
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 #4
Source File: image_test.py    From earthengine with MIT License 6 votes vote down vote up
def testExpression(self):
    """Verifies the behavior of ee.Image.expression()."""
    image = ee.Image([1, 2]).expression('a', {'b': 'c'})
    expression_func = image.func

    # The call is buried in a one-time override of .encode so we have to call
    # it rather than comparing the object structure.
    def dummy_encoder(x):
      if isinstance(x, ee.encodable.Encodable):
        return x.encode(dummy_encoder)
      else:
        return x

    self.assertEquals(
        {
            'type': 'Invocation',
            'functionName': 'Image.parseExpression',
            'arguments': {
                'expression': 'a',
                'argName': 'DEFAULT_EXPRESSION_IMAGE',
                'vars': ['DEFAULT_EXPRESSION_IMAGE', 'b']
            }
        },
        dummy_encoder(expression_func)) 
Example #5
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 #6
Source File: batch_test.py    From earthengine with MIT License 6 votes vote down vote up
def testExportImageToCloudStorage(self):
    """Verifies the Cloud Storge export task created by Export.image()."""
    region = ee.Geometry.Rectangle(1, 2, 3, 4)
    config = dict(region=region['coordinates'], maxPixels=10**10,
                  outputBucket='test-bucket')
    task = ee.batch.Export.image.toCloudStorage(
        ee.Image(1), 'TestDescription',
        config['outputBucket'], None, None,
        config['region'], None, None, None, config['maxPixels'])
    self.assertEquals('TESTTASKID', task.id)
    self.assertEquals(
        {
            'type': 'EXPORT_IMAGE',
            'state': 'UNSUBMITTED',
            'json': ee.Image(1).serialize(),
            'description': 'TestDescription',
            'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
            'outputBucket': 'test-bucket',
            'maxPixels': 10**10,
        },
        task.config) 
Example #7
Source File: eeWishart.py    From earthengine with MIT License 6 votes vote down vote up
def filter_j(current,prev):
    P = ee.Image(current)
    prev = ee.Dictionary(prev)
    ell = ee.Number(prev.get('ell'))
    cmap = ee.Image(prev.get('cmap'))
    smap = ee.Image(prev.get('smap'))
    fmap = ee.Image(prev.get('fmap'))
    bmap = ee.Image(prev.get('bmap'))
    threshold = ee.Image(prev.get('threshold'))
    j = ee.Number(prev.get('j'))
    cmapj = cmap.multiply(0).add(ell.add(j).subtract(1))
    cmap1 = cmap.multiply(0).add(1)
    tst = P.gt(threshold).And(cmap.eq(ell.subtract(1)))
    cmap = cmap.where(tst,cmapj)
    fmap = fmap.where(tst,fmap.add(1))
    smap = ee.Algorithms.If(ell.eq(1),smap.where(tst,cmapj),smap)
    idx = ell.add(j).subtract(2)
    tmp = bmap.select(idx)
    bname = bmap.bandNames().get(idx)
    tmp = tmp.where(tst,cmap1)
    tmp = tmp.rename([bname])    
    bmap = bmap.addBands(tmp,[bname],True)    
    return ee.Dictionary({'ell':ell,'j':j.add(1),'threshold':threshold,'cmap':cmap,'smap':smap,'fmap':fmap,'bmap':bmap}) 
Example #8
Source File: ee_test.py    From earthengine with MIT License 6 votes vote down vote up
def testPromotion(self):
    """Verifies object promotion rules."""
    self.InitializeApi()

    # Features and Images are both already Elements.
    self.assertTrue(isinstance(ee._Promote(ee.Feature(None), 'Element'),
                               ee.Feature))
    self.assertTrue(isinstance(ee._Promote(ee.Image(0), 'Element'), ee.Image))

    # Promote an untyped object to an Element.
    untyped = ee.ComputedObject('foo', {})
    self.assertTrue(isinstance(ee._Promote(untyped, 'Element'), ee.Element))

    # Promote an untyped variable to an Element.
    untyped = ee.ComputedObject(None, None, 'foo')
    self.assertTrue(isinstance(ee._Promote(untyped, 'Element'), ee.Element))
    self.assertEquals('foo', ee._Promote(untyped, 'Element').varName) 
Example #9
Source File: eeWishart.py    From earthengine with MIT License 6 votes vote down vote up
def pv(imList,p,median,j):
    ''' calculate -2log(R_ell,j) and return P-value '''
    imList = ee.List(imList)
    p = ee.Number(p)
    j = ee.Number(j)
    f = p
    one = ee.Number(1.0)
# 1 - (1. + 1./(j*(j-1)))/(6.*p*n)    
    rhoj = one.subtract(one.add(one.divide(j.multiply(j.subtract(one)))).divide(6*ENL))
# -(f/4.)*(1.-1./rhoj)**2'    
    omega2j = one.subtract(one.divide(rhoj)).pow(2.0).multiply(f.divide(-4.0))
    Z = ee.Image(ee.Image(log_det_sum(imList,j.subtract(1)))).multiply(j.subtract(1)) \
                 .add(log_det(imList,j))  \
                 .add(p.multiply(j).multiply(ee.Number(j).log())) \
                 .subtract(p.multiply(j.subtract(1)).multiply(j.subtract(1).log())) \
                 .subtract(ee.Image(log_det_sum(imList,j)).multiply(j)) \
                 .multiply(rhoj) \
                 .multiply(-2*ENL)
# (1.-omega2j)*stats.chi2.cdf(Z,[f])+omega2j*stats.chi2.cdf(Z,[f+4])                 
    P = ee.Image( chi2cdf(Z,f).multiply(one.subtract(omega2j)).add(chi2cdf(Z,f.add(4)).multiply(omega2j))  )
# 3x3 median filter    
    return ee.Algorithms.If(median, P.focal_median(), P) 
Example #10
Source File: eeMad.py    From earthengine with MIT License 6 votes vote down vote up
def covarw(image, weights, maxPixels=1e9):
    '''Return the weighted centered image and its weighted covariance matrix'''  
    geometry = image.geometry()
    bandNames = image.bandNames()
    N = bandNames.length()
    scale = image.select(0).projection().nominalScale()
    weightsImage = image.multiply(ee.Image.constant(0)).add(weights)
    means = image.addBands(weightsImage) \
                 .reduceRegion(ee.Reducer.mean().repeat(N).splitWeights(), scale=scale,maxPixels=maxPixels) \
                 .toArray() \
                 .project([1])
    centered = image.toArray().subtract(means) 
    B1 = centered.bandNames().get(0)       
    b1 = weights.bandNames().get(0)     
    nPixels = ee.Number(centered.reduceRegion(ee.Reducer.count(), scale=scale, maxPixels=maxPixels).get(B1)) 
    sumWeights = ee.Number(weights.reduceRegion(ee.Reducer.sum(),geometry=geometry, scale=scale, maxPixels=maxPixels).get(b1))
    covw = centered.multiply(weights.sqrt()) \
                   .toArray() \
                   .reduceRegion(ee.Reducer.centeredCovariance(), geometry=geometry, scale=scale, maxPixels=maxPixels) \
                   .get('array')
    covw = ee.Array(covw).multiply(nPixels).divide(sumWeights)
    return (centered.arrayFlatten([bandNames]), covw) 
Example #11
Source File: eeWishart.py    From earthengine with MIT License 5 votes vote down vote up
def multbyenl(image):
    return ee.Image(image).multiply(ENL) 
Example #12
Source File: cdd_simple.py    From coded with MIT License 5 votes vote down vote up
def makeVariables_soil(image):
  """ Make variables for soil regression model """
  year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) 
  season = year.multiply(2 * np.pi)
  return image.select().addBands(ee.Image(1)).addBands(
    season.sin().rename(['sin'])).addBands(
    season.cos().rename(['cos'])).addBands(
    image.select(['band_3'])).toFloat() 
Example #13
Source File: cdd_simple.py    From coded with MIT License 5 votes vote down vote up
def makeVariables(image):
  """ Computes the predictors and the response from the input. """
  # Compute time of the image in fractional years relative to the Epoch.
  year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) 
  # Compute the season in radians, one cycle per year.
  season = year.multiply(2 * np.pi)
  # Return an image of the predictors followed by the response.
  return image.select().addBands(ee.Image(1)).addBands(
    season.sin().rename(['sin'])).addBands(
    season.cos().rename(['cos'])).addBands(
    image.select(['NDFI'])).toFloat() 
Example #14
Source File: eeMad.py    From earthengine with MIT License 5 votes vote down vote up
def radcal(current,prev):
    ''' iterator function for orthogonal regression and interactive radiometric normalization '''
    k = ee.Number(current)
    prev = ee.Dictionary(prev)    
#  image is concatenation of reference and target    
    image = ee.Image(prev.get('image'))
    ncmask = ee.Image(prev.get('ncmask'))
    nbands = ee.Number(prev.get('nbands'))
    rect = ee.Geometry(prev.get('rect'))
    coeffs = ee.List(prev.get('coeffs'))
    normalized = ee.Image(prev.get('normalized'))
    scale = image.select(0).projection().nominalScale()
#  orthoregress reference onto target  
    image1 = image.clip(rect).select(k.add(nbands),k).updateMask(ncmask).rename(['x','y'])
    means = image1.reduceRegion(ee.Reducer.mean(), scale=scale, maxPixels=1e9) \
                  .toArray()\
                  .project([0])              
    Xm = means.get([0])    
    Ym = means.get([1])    
    S = ee.Array(image1.toArray() \
                       .reduceRegion(ee.Reducer.covariance(), geometry=rect, scale=scale, maxPixels=1e9) \
                       .get('array'))     
#  Pearson correlation     
    R = S.get([0,1]).divide(S.get([0,0]).multiply(S.get([1,1])).sqrt())
    eivs = S.eigen()
    e1 = eivs.get([0,1])
    e2 = eivs.get([0,2])
#  slope and intercept    
    b = e2.divide(e1)
    a = Ym.subtract(b.multiply(Xm))
    coeffs = coeffs.add(ee.List([b,a,R]))
#  normalize kth band in target    
    normalized = normalized.addBands(image.select(k.add(nbands)).multiply(b).add(a))
    return ee.Dictionary({'image':image,'ncmask':ncmask,'nbands':nbands,'rect':rect,'coeffs':coeffs,'normalized':normalized}) 
Example #15
Source File: cdd_simple.py    From coded with MIT License 5 votes vote down vote up
def unmix(image):
  """ Do spectral unmixing on a single image """
  unmixi = ee.Image(image).unmix([gv, shade, npv, soil, cloud], True, 
				 True)
  newimage = ee.Image(image).addBands(unmixi)
  mask = ee.Image(newimage).select('band_4').lt(cf_thresh)
  return newimage.updateMask(mask)


# NDFI functions 
Example #16
Source File: cdd_simple.py    From coded with MIT License 5 votes vote down vote up
def get_ndfi(image):
  """ Get Normalized Degradation Fraction Index (NDFI) for an image """
  newimage = ee.Image(image).expression(
      '((GV / (1 - SHADE)) - (NPV + SOIL)) / ((GV / (1 - SHADE)) + NPV + SOIL)', {
        'GV': ee.Image(image).select('band_0'),
        'SHADE': ee.Image(image).select('band_1'),
        'NPV': ee.Image(image).select('band_2'),
        'SOIL': ee.Image(image).select('band_3')
      })
  return ee.Image(image).addBands(ee.Image(newimage).rename(['NDFI'])
    ).select(['band_0','band_1','band_2','band_3','NDFI']) 
Example #17
Source File: cdd_simple.py    From coded with MIT License 5 votes vote down vote up
def makeVariables_noharm(image):
  """ Computes the predictors and the response from the input. """
  # Compute time of the image in fractional years relative to the Epoch.
  year = ee.Image(image.date().difference(ee.Date('1970-01-01'), 'year')) 
  # Compute the season in radians, one cycle per year.
  season = year.multiply(2 * np.pi)
  # Return an image of the predictors followed by the response.
  return image.select().addBands(ee.Image(1)).addBands(
    ee.Image(0).rename(['sin'])).addBands(
    ee.Image(0).rename(['cos'])).addBands(
    image.select(['NDFI'])).toFloat() 
Example #18
Source File: imagecollection_test.py    From earthengine with MIT License 5 votes vote down vote up
def testFilter(self):
    """Verifies that filtering an ImageCollection wraps the result."""
    collection = ee.ImageCollection(ee.Image(1))
    noop_filter = ee.Filter()
    filtered = collection.filter(noop_filter)
    self.assertTrue(isinstance(filtered, ee.ImageCollection))
    self.assertEquals(ee.ApiFunction.lookup('Collection.filter'),
                      filtered.func)
    self.assertEquals({'collection': collection, 'filter': noop_filter},
                      filtered.args) 
Example #19
Source File: deserializer_test.py    From earthengine with MIT License 5 votes vote down vote up
def testReuse(self):
    """Verifies that decoding results can be used and re-encoded."""
    input_image = ee.Image(13)
    output = deserializer.fromJSON(serializer.toJSON(input_image))
    self.assertEquals(output.addBands(42).serialize(),
                      input_image.addBands(42).serialize()) 
Example #20
Source File: deserializer_test.py    From earthengine with MIT License 5 votes vote down vote up
def testCast(self):
    """Verifies that decoding casts the result to the right class."""
    input_image = ee.Image(13).addBands(42)
    output = deserializer.fromJSON(serializer.toJSON(input_image))
    self.assertTrue(isinstance(output, ee.Image)) 
Example #21
Source File: serializer_test.py    From earthengine with MIT License 5 votes vote down vote up
def testRepeats(self):
    """Verifies serialization finds and removes repeated values."""
    test1 = ee.Image(5).mask(ee.Image(5))     # pylint: disable-msg=no-member
    expected1 = {
        'type': 'CompoundValue',
        'scope': [
            ['0', {
                'type': 'Invocation',
                'arguments': {
                    'value': 5
                },
                'functionName': 'Image.constant'
            }],
            ['1', {
                'type': 'Invocation',
                'arguments': {
                    'image': {
                        'type': 'ValueRef',
                        'value': '0'
                    },
                    'mask': {
                        'type': 'ValueRef',
                        'value': '0'
                    }
                },
                'functionName': 'Image.mask'
            }]
        ],
        'value': {
            'type': 'ValueRef',
            'value': '1'
        }
    }
    self.assertEquals(expected1, json.loads(serializer.toJSON(test1))) 
Example #22
Source File: batch_test.py    From earthengine with MIT License 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 #23
Source File: batch_test.py    From earthengine with MIT License 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 #24
Source File: batch_test.py    From earthengine with MIT License 5 votes vote down vote up
def testExportMapToCloudStorage(self):
    """Verifies the task created by Export.map.toCloudStorage()."""
    config = dict(
        image=ee.Image(1), bucket='test-bucket', maxZoom=7, path='foo/gcs/path')

    # Test keyed parameters.
    task_keyed = ee.batch.Export.map.toCloudStorage(
        image=config['image'], bucket=config['bucket'],
        maxZoom=config['maxZoom'], path=config['path'])
    self.assertEquals('TESTTASKID', task_keyed.id)
    self.assertEquals(
        {
            'type': 'EXPORT_TILES',
            'state': 'UNSUBMITTED',
            'json': config['image'].serialize(),
            'description': 'myExportMapTask',
            'outputBucket': config['bucket'],
            'maxZoom': config['maxZoom'],
            'outputPrefix': config['path'],
            'writePublicTiles': True,
            'fileFormat': 'auto'
        }, task_keyed.config)

    # Test ordered parameters.
    task_ordered = ee.batch.Export.map.toCloudStorage(
        config['image'], 'TestDescription', config['bucket'], 'jpeg', None,
        False, None, 30)
    self.assertEquals(
        {
            'type': 'EXPORT_TILES',
            'state': 'UNSUBMITTED',
            'json': config['image'].serialize(),
            'description': 'TestDescription',
            'outputBucket': config['bucket'],
            'outputPrefix': 'TestDescription',
            'scale': 30,
            'writePublicTiles': False,
            'fileFormat': 'jpeg'
        }, task_ordered.config) 
Example #25
Source File: batch_test.py    From earthengine with MIT License 5 votes vote down vote up
def testExportImageFileDimensions(self):
    """Verifies proper handling of the fileDimensions parameter."""
    number_task = ee.batch.Export.image.toDrive(
        image=ee.Image(1), fileDimensions=100)
    self.assertEquals(100, number_task.config['fileDimensions'])

    tuple_task = ee.batch.Export.image.toDrive(
        image=ee.Image(1), fileDimensions=(100, 200))
    self.assertEquals('100,200', tuple_task.config['fileDimensions']) 
Example #26
Source File: batch_test.py    From earthengine with MIT License 5 votes vote down vote up
def testExportImageToGoogleDrive(self):
    """Verifies the Drive destined task created by Export.table.toDrive()."""
    region = ee.Geometry.Rectangle(1, 2, 3, 4)
    drive_task_by_keys = ee.batch.Export.image.toDrive(
        image=ee.Image(1), region=region['coordinates'], folder='foo',
        maxPixels=10**10, crsTransform='bar')
    self.assertEquals('TESTTASKID', drive_task_by_keys.id)
    self.assertEquals(
        {
            'type': 'EXPORT_IMAGE',
            'state': 'UNSUBMITTED',
            'json': ee.Image(1).serialize(),
            'description': 'myExportImageTask',
            'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
            'driveFileNamePrefix': 'myExportImageTask',
            'driveFolder': 'foo',
            'maxPixels': 10**10,
            'crs_transform': 'bar',  # Transformed by _ConvertToServerParams.
        },
        drive_task_by_keys.config)

    drive_task_with_old_keys = ee.batch.Export.image.toDrive(
        image=ee.Image(1), region=region['coordinates'], driveFolder='foo',
        driveFileNamePrefix='fooExport', maxPixels=10**10, crs_transform='bar')
    self.assertEquals(
        {
            'type': 'EXPORT_IMAGE',
            'state': 'UNSUBMITTED',
            'json': ee.Image(1).serialize(),
            'description': 'myExportImageTask',
            'region': '[[[1, 4], [1, 2], [3, 2], [3, 4]]]',
            'driveFileNamePrefix': 'fooExport',
            'driveFolder': 'foo',
            'maxPixels': 10**10,
            'crs_transform': 'bar',  # Transformed by _ConvertToServerParams.
        },
        drive_task_with_old_keys.config) 
Example #27
Source File: batch_test.py    From earthengine with MIT License 5 votes vote down vote up
def testExportImageToAsset(self):
    """Verifies the Asset export task created by Export.image.toAsset()."""
    config = dict(
        image=ee.Image(1), assetId='user/foo/bar',
        pyramidingPolicy={'B1': 'min'})

    # Test keyed parameters.
    task_keyed = ee.batch.Export.image.toAsset(
        image=config['image'], assetId=config['assetId'],
        pyramidingPolicy=config['pyramidingPolicy'])
    self.assertEquals('TESTTASKID', task_keyed.id)
    self.assertEquals(
        {
            'type': 'EXPORT_IMAGE',
            'state': 'UNSUBMITTED',
            'json': config['image'].serialize(),
            'description': 'myExportImageTask',
            'assetId': config['assetId'],
            'pyramidingPolicy': config['pyramidingPolicy']
        }, task_keyed.config)

    task_ordered = ee.batch.Export.image.toAsset(
        config['image'], 'TestDescription', config['assetId'], maxPixels=1000)
    self.assertEquals(
        {
            'type': 'EXPORT_IMAGE',
            'state': 'UNSUBMITTED',
            'json': config['image'].serialize(),
            'description': 'TestDescription',
            'assetId': config['assetId'],
            'maxPixels': 1000
        }, task_ordered.config) 
Example #28
Source File: collection_test.py    From earthengine with MIT License 5 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 #29
Source File: collection_test.py    From earthengine with MIT License 5 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 #30
Source File: imagecollection_test.py    From earthengine with MIT License 5 votes vote down vote up
def testImperativeFunctions(self):
    """Verifies that imperative functions return ready values."""
    image_collection = ee.ImageCollection(ee.Image(1))
    self.assertEquals({'value': 'fakeValue'}, image_collection.getInfo())
    self.assertEquals('fakeMapId', image_collection.getMapId()['mapid'])