Công thức này cho thấy cách đóng tập dữ liệu raster. Nó rất hữu ích ở giữa tập lệnh, để khôi phục các tài nguyên được giữ bằng cách truy cập tập dữ liệu, xóa khóa tệp, v.v. Không cần thiết ở cuối tập lệnh, vì trình thu gom rác Python sẽ tự động thực hiện điều tương tự khi tập lệnh thoát. Thảo luận thêm về chủ đề này có thể được tìm thấy trong câu hỏi StackExchange của GIS này
import gdal # open dataset ds = gdal.Open['test.tif'] # close dataset ds = None
Nhận siêu dữ liệu raster
Nhận siêu dữ liệu raster để kiểm tra độ phân giải nhanh và bẩn
from osgeo import gdal gtif = gdal.Open[ "INPUT.tif" ] print gtif.GetMetadata[]
Nhận băng tần
Nhận một dải raster. Lưu ý cách chúng tôi xử lý các lỗi thời gian chạy mà chức năng này có thể gây ra
from osgeo import gdal import sys # this allows GDAL to throw Python Exceptions gdal.UseExceptions[] try: src_ds = gdal.Open[ "INPUT.tif" ] except RuntimeError, e: print 'Unable to open INPUT.tif' print e sys.exit[1] try: srcband = src_ds.GetRasterBand[1] except RuntimeError, e: # for example, try GetRasterBand[10] print 'Band [ %i ] not found' % band_num print e sys.exit[1]
Lặp qua tất cả các dải raster
Lặp lại tất cả các dải raster và làm điều gì đó hữu ích như liệt kê số liệu thống kê về dải
from osgeo import gdal import sys src_ds = gdal.Open[ "INPUT.tif" ] if src_ds is None: print 'Unable to open INPUT.tif' sys.exit[1] print "[ RASTER BAND COUNT ]: ", src_ds.RasterCount for band in range[ src_ds.RasterCount ]: band += 1 print "[ GETTING BAND ]: ", band srcband = src_ds.GetRasterBand[band] if srcband is None: continue stats = srcband.GetStatistics[ True, True ] if stats is None: continue print "[ STATS ] = Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f" % [ \ stats[0], stats[1], stats[2], stats[3] ]
Nhận thông tin băng tần Raster
Sử dụng tài liệu về API băng tần, chúng tôi có thể viết một tập lệnh loại bỏ thông tin một băng tần
from osgeo import gdal import sys gdal.UseExceptions[] def Usage[]: print[""" $ getrasterband.py [ band number ] input-raster """] sys.exit[1] def main[ band_num, input_file ]: src_ds = gdal.Open[ input_file ] if src_ds is None: print 'Unable to open %s' % input_file sys.exit[1] try: srcband = src_ds.GetRasterBand[band_num] except RuntimeError, e: print 'No band %i found' % band_num print e sys.exit[1] print "[ NO DATA VALUE ] = ", srcband.GetNoDataValue[] print "[ MIN ] = ", srcband.GetMinimum[] print "[ MAX ] = ", srcband.GetMaximum[] print "[ SCALE ] = ", srcband.GetScale[] print "[ UNIT TYPE ] = ", srcband.GetUnitType[] ctable = srcband.GetColorTable[] if ctable is None: print 'No ColorTable found' sys.exit[1] print "[ COLOR TABLE COUNT ] = ", ctable.GetCount[] for i in range[ 0, ctable.GetCount[] ]: entry = ctable.GetColorEntry[ i ] if not entry: continue print "[ COLOR ENTRY RGB ] = ", ctable.GetColorEntryAsRGB[ i, entry ] if __name__ == '__main__': if len[ sys.argv ]