1

I'm using the Python API of GEE in a Jupyter notebook.

I'd like to perform a surface evaluation of classified pixels.

I have a ee_map with one band called gfc that have values in [1,2 ... 19, 30, 40, 50, 51] characterising the gain or loss of treecover.

I try to evaluate the surface of each class in hectares:

#define the pixel resolution
    res = 30

    hist = ee_map.reduceRegion(**{
      'reducer': ee.Reducer.autoHistogram(),
      'geometry': ee.FeatureCollection(assetId).geometry(),
      'scale': res,
      'maxPixels': 1e12
    })

    hist = pd.DataFrame(hist.getInfo()['gfc'])

    #add column name
    hist.columns= ['code', 'pixels'] 

    #won't work 
    #hist['area'] = hist['pixels']*res*res/10000

Problem : due to projection issues I don't know the surface of each pixel. The documentation suggest to use ee_map.multiply(ee.Image.pixelArea()) but it will only work if the map have binaries values.

Is there a way to combine it with ee.Reducer.autoHistogram() or am I force each of them in a loop?

1 Answer 1

0

There are two steps to this problem :

Select the values to mask in the band

perform a hist on your band of interest and you'll obtain a dic of all the unique values and there surface Keep only the keys in an array

hist = ee_image.select('band').reduceRegion(**{
      'reducer': ee.Reducer.autoHistogram(),
      'geometry': your_geom, #need to be a geometry
      'maxPixels': 1e12
})
dic = hist.getInfo()['band']
codes = [ dic[i][0] for i in range(len(dic))] 

fill the codes variable directly if you already know your possible values.

create the surface histogram

for each value in codes create a binary mask for the value. multiply this mask by the pixel surface and then perform a sum. I finally concatenate them in a panda dataframe.

import pandas as pd 

columns=['code', 'area_m']
row_list = []
for code in codes:
    code = int(code)
    mask = ee_image.select('band').eq(code)
    mask_surface = mask.multiply(ee.Image.pixelArea())
    stats = mask_surface.reduceRegion(**{
        'reducer': ee.Reducer.sum(),
        'geometry': your_geom,
        'maxPixels': 1e13
    })

    row_list.append({
        columns[0]: code, 
        columns[1]: stats.getInfo()['band']
    })

    
hist = pd.DataFrame(row_list)

If anyone knows a more efficient way please feel free to add comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.