Raster sang đa giác Python gdal

def rasterize[in_shp_file_name, out_raster_file_name, pixel_size=10, no_data_value=-9999, rdtype=gdal. GDT_Float32, **kwargs]. """ Chuyển đổi bất kỳ shapefile nào thành raster. tham số in_shp_file_name. STR của tên shapefile [với thư mục e. g. , "C. /temp/poly. shp"]. tham số out_raster_file_name. STR của tên tệp đích, bao gồm cả thư mục; . tif". tham số pixel_size. INT của kích thước pixel [mặc định. 10]. tham số no_data_value. Số [INT/FLOAT] cho các pixel không có dữ liệu [mặc định. -9999]. tham số loại. gdal. Kiểu dữ liệu raster GDALDataType - default=gdal. GDT_Float32 [dấu phẩy động 32 bit]. trường kwarg_name. tên của trường shapefile với các giá trị để ghi vào raster. trở lại. tạo shapefile được xác định bằng in_shp_file_name """ # thử nguồn dữ liệu mở. nguồn_ds = ogr. Mở [in_shp_file_name] ngoại trừ RuntimeError là e. in["Lỗi. Không thể mở %s. " % str[in_shp_file_name]] return Không source_lyr = source_ds. GetLayer[] # đọc phạm vi x_min, x_max, y_min, y_max = source_lyr. GetExtent[] # lấy độ phân giải x và y x_res = int[[x_max - x_min] / pixel_size] y_res = int[[y_max - y_min] / pixel_size] # tạo nguồn dữ liệu đích [GeoTiff raster] target_ds = gdal. GetDriverByName['GTiff']. Tạo[out_raster_file_name, x_res, y_res, 1, eType=rdtype] target_ds. SetGeoTransform[[x_min, pixel_size, 0, y_max, 0, -pixel_size]] dải = target_ds. Dải GetRasterBand[1]. Dải điền[no_data_value]. SetNoDataValue[no_data_value] # lấy hệ thống tham chiếu không gian và gán cho raster srs = get_srs[source_ds] try. srs. ImportFromEPSG[int[srs. GetAuthorityCode[None]]] ngoại trừ RuntimeError là e. in[e] trả lại Không target_ds. SetProjection[srs. ExportToWkt[]] # RasterizeLayer[Dataset dataset, int bands, Layer layer, pfnTransformer=None, pTransformArg=None, # int burn_values=0, options=None, GDALProgressFunc callback=0, callback_data=None] gdal. RasterizeLayer[target_ds, [1], source_lyr, Không, Không, burn_values=[0], options=["ALL_TOUCHED=TRUE", "ATTRIBUTE=" + str[kwargs. get["field_name"]]]] # giải phóng dải băng raster. FlushCache[]

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 ] 

Chủ Đề