Python-GDAL将二进制文件转为栅格影像

import argparse
from osgeo import gdal

def convert_ascii_to_tiff(in_asc_path: str, out_tiff_path: str, band_count: int):
    try:
        print("Processing...")
        src_ds = gdal.Open(in_asc_path)
        data = src_ds.ReadAsArray()

        # 创建 GTiff 驱动程序
        driver = gdal.GetDriverByName('GTiff')
        width = src_ds.RasterXSize
        height = src_ds.RasterYSize

        # 创建 TIFF 文件
        dst_ds = driver.Create(out_tiff_path, width, height, bands=band_count, eType=gdal.GDT_Float32)

        # 将数据写入 TIFF 文件的第i+1个波段
        for i in range(band_count):
            dst_ds.GetRasterBand(i+1).WriteArray(data)
        # 设置地理变换
        dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
        # 设置投影信息
        dst_ds.SetProjection(src_ds.GetProjection())

        src_ds = None  # 关闭输入文件
        dst_ds = None  # 关闭输出文件
        print("Conversion completed successfully.")
    except Exception as e:
        print(f"An error occurred during conversion:{str(e)}")

convert_ascii_to_tiff("183.ASC","183.tif",band_count=1)
#下面是命令行调用:python 模块名.py 183.ASC 183.tif --bands 1
# if __name__ == "__main__":
#
#     parser = argparse.ArgumentParser(description='Convert ASCII file to TIFF')
#     parser.add_argument('input', help='Input ASCII file path')
#     parser.add_argument('output', help='Output TIFF file path')
#     parser.add_argument('--bands', type=int, default=1, help='Number of output bands (default: 1)')
#     args = parser.parse_args()
#
#     convert_ascii_to_tiff(args.input, args.output, args.bands)

你可能感兴趣的:(python,开发语言)