首页 > 解决方案 > TypeError:只有大小为 1 的数组可以转换为 Python 标量 - 地球观测

问题描述

我正在尝试创建一个脚本,它将 .GTiff 文件作为参数输入,然后从文件中提取一些信息以创建一个 stats.txt 文件,该文件将为我提供 classID、分数覆盖率和总像素数那个classID。

到目前为止,我相信我拥有我需要的一切,但我一直遇到同样的错误,而且我纠正错误的尝试并没有被证明是非常富有成效的。

#!/usr/bin/env python

import sys
import calendar
import os

import gdal
import numpy as np
from scipy.stats import mode

from IPython import embed

GDAL2NUMPY = {  gdal.GDT_Byte      :   np.uint8,
                gdal.GDT_UInt16    :   np.uint16,
                gdal.GDT_Int16     :   np.int16,
                gdal.GDT_UInt32    :   np.uint32,
                gdal.GDT_Int32     :   np.int32,
                gdal.GDT_Float32   :   np.float32,
                gdal.GDT_Float64   :   np.float64,
                gdal.GDT_CInt16    :   np.complex64,
                gdal.GDT_CInt32    :   np.complex64,
                gdal.GDT_CFloat32  :   np.complex64,
                gdal.GDT_CFloat64  :   np.complex128
              }


#Open the original training data .tif map file.

fname = sys.argv[1]
lc_dataset = gdal.Open(fname)
lc = lc_dataset.ReadAsArray()
lc = np.array(lc)

#Calculating total number of pixels with a valid Land Cover ID.

fill_value = 0
number_of_pixels = np.where(lc != fill_value)[0].shape[0]

#Get the number of classes and corresponding IDs.

lc_classes = np.unique(lc)

#Split each class into its contituante pixel and write result to file.

for classID in range(1, lc_classes):
    lc_class_pixels = np.where(lc == classID)[0].shape[0]
    FractionalCover = lc_class_pixels/number_of_pixels
    f.write(classID, FractionalCoverage, lc_class_pixels)

f.close()

当我运行它时,它会收集以下回溯:

Traceback (most recent call last):
  File "GeneratingLCstats.py", line 45, in <module>
    for classID in range(1, lc_classes):
TypeError: only size-1 arrays can be converted to Python scalars

我尝试了一些更改,因为我确定错误与 numpy 数据和本机 python 数据交互有关,但是将我的所有数组转换为 numpy 数组并尝试重新格式化代码已被证明是徒劳的,因为同样的错误仍然存​​在。

如果有人可以提出解决方案,将不胜感激!

谢谢。

标签: pythonnumpy

解决方案


好吧,该函数lc_classes = np.unique(lc)返回一个数组。当您尝试将 for 循环编写为

for classID in range(1, lc_classes)

在这里, lc_classes 是一个数组,并试图将其作为range导致错误的界限。如果要遍历数组的长度,可以将代码修改为:

for classID in range(1, len(lc_classes))


推荐阅读