最近的课题有用到这两个软件,其中做maxent的时候需要气象因子,而在worldclim下载的未来生物气象因子只有一张包含19个波段的tif文件,需要手动拆分成19个文件。实在是没有找到用arcgis拆分的方法,所以转向了python。

代码如下:

import gdal
import os

input_file = "G:/4.其他/wc2.1_30s_bioc_ACCESS-CM2_ssp126_2041-2060.tif"#下载的tif文件
output_folder = "G:/4.其他/feature_bio/"#输出文件夹

if not os.path.exists(output_folder):
   os.makedirs(output_folder)

dataset = gdal.Open(input_file)
num_bands = dataset.RasterCount

for i in range(num_bands):
   band = dataset.GetRasterBand(i + 1) 
   output_file = os.path.join(output_folder, f"bio_{i + 1}.tif")
   driver = gdal.GetDriverByName("GTiff")
   new_dataset = driver.Create(output_file, dataset.RasterXSize, dataset.RasterYSize, 1, gdal.GDT_Float32)
   new_dataset.SetProjection(dataset.GetProjection())
   new_dataset.SetGeoTransform(dataset.GetGeoTransform())
   new_dataset.GetRasterBand(1).WriteArray(band.ReadAsArray())
   print(f"Creating {output_file}...")
   new_dataset.FlushCache()
   new_dataset = None

dataset = None

但是有个问题,安装gdal的时候大概率会报错,具体原因我也没查到。网上的推荐办法是使用conda:

conda install gdal

实际情况可能会出现无法安装或者安装了没法调用,解决办法:

  1. 如果安装失败:
    Github仓库下载对应的.whl文件,比如python 3.11就下载GDAL-3.7.1-cp311-cp311-win_amd64.whl
    ,然后手动安装pip install GDAL-3.7.1-cp311-cp311-win_amd64.whl
  2. 如果无法调用:
    在python安装各种环境包的文件夹下,如:D:**\python3.9.12\Lib\site-packages\文件夹下,新建gdal.py文件,将以下代码复制进去:
    # import osgeo.gdal as a convenience
    from osgeo.gdal import deprecation_warn
    deprecation_warn('gdal')
    from osgeo.gdal import *