计算多边形中不同条带的百分比

2024-05-28 19:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用GEE(USGS/GFSAD1000_V0)的数据集,目的是将其转换为一组多边形,我在所有这些之前已经确定了这些多边形。我现在试图计算某个多边形内不同值(0-9)的像素百分比,并打印出来

import ee
import numpy as np

ee.Initialize()

polygon_version = '(SOURCE)'
land_polygons = ee.FeatureCollection(f'users/(SOURCE)/{polygon_version}_poly_land')

def Landcover_Crops_nr(polygons):
    dataset = ee.Image("USGS/GFSAD1000_V0").clip(polygons)
    type_crop = dataset.select("landcover")
    arr = np.array(type_crop)

    rawres = type_crop.getInfo()["features"]
    res = {
        x["properties"]["id"]: {
            "id": x["properties"]["id"],
            "area": float(x["properties"]["area"]),
            "center_lat": x["properties"]["center_lat"],
            "crop_area": x["properties"]["sum"],
        }
        for x in rawres
    }

    return res
values, frequencies= np.unique(arr, return_counts=True)
sum = np.sum(frequencies)
percentages = [x/sum*100 for x in frequencies]
dfgen = Landcover_Crops_nr(land_polygons)
dfgen.to_csv(f'{polygon_version}_Crops.csv', index=False)
print (dfgen)

我以前尝试过这个方法,但正如您所看到的,它只关注9值,而手动操作,就像这不是全球数据集的选项一样


Tags: cropscropidversiontypenpareaproperties
1条回答
网友
1楼 · 发布于 2024-05-28 19:04:01

尝试使用numpy库。 比如说

import numpy as np

# generate an array of size 10x10 with values (0-9)
arr = np.random.randint(10, size=(10, 10))

# get unique values with frequencies
values, frequencies= np.unique(arr, return_counts=True) 

# calculate sum of frequencies
sum = np.sum(frequencies)

# calculate percentages
percentages = [x/sum*100 for x in frequencies]

# Example

# print(values)
# [0, 1, ...,9 ]

# print(percentages)
# [25.0, 15.0, ..., 2.5]

要使此方法适应您的方法,请尝试使用

arr = np.array(type_crop)

反而

arr = np.random.randint(10, size=(10, 10))

假设type_crop是2d数组

相关问题 更多 >

    热门问题