python - 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 数组并尝试重新格式化代码已被证明是徒劳的,因为同样的错误仍然存在。
如果有人可以提出解决方案,将不胜感激!
谢谢。
解决方案
好吧,该函数lc_classes = np.unique(lc)
返回一个数组。当您尝试将 for 循环编写为
for classID in range(1, lc_classes)
在这里, lc_classes 是一个数组,并试图将其作为range
导致错误的界限。如果要遍历数组的长度,可以将代码修改为:
for classID in range(1, len(lc_classes))
推荐阅读
- python - 检查输入时出错:预期 lstm_1_input 有 3 个维度,但得到了形状为 (5, 3) 的数组
- c - Linux Networking:RTP 序列号不递增
- reactjs - 如何以编程方式更新 antd 中的表单字段值
- sql - 获取/使用新记录的自动增量主键作为另一个表中记录的外键
- ruby - Ruby 2.6 / 2.7 中“public_send”的不同行为
- python - 将来自无人机摄像机的 h264 视频输入保存为计算机上的视频文件
- .net-core - .Net Core 3.x 中的全局 json 序列化选项
- c# - 在 .NET Core 控制台应用程序中获取对 System.Printing 命名空间的访问权限
- google-chrome-devtools - 在哪里可以找到有关页面生命周期事件的文档?
- nlp - 用于机器翻译的 Transformers 架构