首页 > 解决方案 > AttributeError:“数据集”对象没有属性“astype”

问题描述

我正在运行此代码:

from osgeo import gdal
import numpy as np

g = gdal.Open ("UAV_image.tif")
if g is None:
    raise IOError("Couldn't open baikal_subset.tif")

b3 = g.GetRasterBand(3).ReadAsArray().astype(np.float32)
b4 = g.GetRasterBand(4).ReadAsArray().astype(np.float32)

ndvi = (b4 - b3)/(b4 + b3)

drv = gdal.GetDriverByName ( "GTiff" )
dst_ds = drv.Create ( "output_file.tif", g.RasterXSize, g.RasterYSize, 1, 
       gdal.GDT_Float32, options=["COMPRESS=LZW"] )
print("1")
dst_ds.GetRasterBand(1).WriteArray ( dst_ds.astype (np.float32) )
print("2")
dst_ds = None
print("3")

从此链接收集:https ://gist.github.com/jgomezdans/6c11fef62eced9e131eb

我收到了这个错误:

1
Traceback (most recent call last):
  File "calc_ndvi_gdal.py", line 17, in <module>
    dst_ds.GetRasterBand(1).WriteArray ( dst_ds.astype (np.float32) )
AttributeError: 'Dataset' object has no attribute 'astype'

并遵循此解决方案:如何解决 AttributeError:'list' object has no attribute 'astype'?

我改变了:

dst_ds.GetRasterBand(1).WriteArray ( dst_ds.astype (np.float32))

对此:

dst_ds.GetRasterBand(1).WriteArray ( np.array(dst_ds).astype ('float32') )

我得到了这个错误:

1
Traceback (most recent call last):
  File "calc_ndvi_gdal.py", line 18, in <module>
    dst_ds.GetRasterBand(1).WriteArray ( np.array(dst_ds).astype ('float32') )
TypeError: float() argument must be a string or a number, not 'Dataset'

从上面提到的链接中,我尝试了另一个建议,并将该行更改为这一行:

dst_ds.GetRasterBand(1).WriteArray ( np.array(dst_ds), dtype = np.float32)

我得到了这个错误:

1
Traceback (most recent call last):
  File "calc_ndvi_gdal.py", line 19, in <module>
    dst_ds.GetRasterBand(1).WriteArray ( np.array(dst_ds), dtype = np.float32)
TypeError: WriteArray() got an unexpected keyword argument 'dtype'

知道如何解决这个问题吗?

标签: pythonubuntutiff

解决方案


推荐阅读