Issue
I am thinking this is an easy fix and likely due to me being meh at python.
What I am trying to do is take this 4 banded NAIP and create a 432 false color image. Ultimately to create a script that will run through hundreds of these images to do so, but that is clearly far off.
I keep receiving an error AttributeError: 'function' object has no attribute 'DataType'
If I enter a DataType ex: gdal.GDT_Byte
(which i don't fully understand) then later I get an error AttributeError: 'function' object has no attribute 'shape'
Which leads me to believe either there is something different between this raster and the one I used in a similar function for class OR I am fundamentally reading in the raster wrong.
Here is my full code:
import os
from osgeo import gdal
#change directory to data location
data_folder = r'my directory'
os.chdir(data_folder)
#open the .tif file and its bands, make sure they opened properly
ds = gdal.Open('example.tif')
if ds is None:
raise IOError('Cound not open raster ya n00b')
band1 = ds.GetRasterBand(1).ReadAsArray
if band1 is None:
raise IOError('bandz 1 didnt make her dance')
band2 = ds.GetRasterBand(2).ReadAsArray
if band2 is None:
raise IOError('bandz 2 didnt make her dance')
band3 = ds.GetRasterBand(3).ReadAsArray
if band3 is None:
raise IOError('bandz 3 didnt make her dance')
band4 = ds.GetRasterBand(4).ReadAsArray
if band4 is None:
raise IOError('bandz 4 didnt make her dance')
#Get the GeoTiff driver to create an output raster
gtiff_driver = gdal.GetDriverByName('GTiff')
#Get the data type name
data_type = band1.DataType
data_type = gdal.GetDataTypeName(data_type)
test_1 = gtiff_driver.Create('test_v1.tif', ds.RasterXSize, ds.RasterYSize, 3, gdal.GDT_Byte)
if test_1 is None:
raise IOError('Could not create raster test_1')
test_1.SetProjection(ds.GetProjection())
test_1.SetGeoTransform(ds.GetGeoTransform())
t1_band1 = test_1.GetRasterBand(1)
t1_band1.WriteArray(band4)
t1_band2 = test_1.GetRasterBand(2)
t1_band2.WriteArray(band3)
t1_band3 = test_1.GetRasterBand(3)
t1_band3.WriteArray(band2)
del t1_band1, t1_band2, t1_band3, test_1, ds
I feel like I am just being dumb here but would really appreciate some help. Oh and I am still using Python 2, I know i need to switch soon. Thank you!
Solution
I think try
band1 = ds.GetRasterBand(1).ReadAsArray()
with parentheses at the end.
The parentheses is python syntax to call the function and get the result.
Without the parentheses, you have made band1
a synonym for the ReadAsArray
function.
This can be helpful in other circumstances, you could do
band1 = ds.GetRasterBand(1).ReadAsArray
x = band1()
which calls ReadAsArray
but it is not what you wanted to do
Answered By - Tim Richardson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.