1 将numpy数组存储为带坐标的tif文件
将numpy数组存储为带坐标的tif文件
def write_img(read_path, img_array):
"""
read_path:原始文件路径
img_array:numpy数组, 数组形状必须是(4, 36786, 37239) ,波段,行,列
"""
read_pre_dataset = gdal.Open(read_path)
img_transf = read_pre_dataset.GetGeoTransform()
img_proj = read_pre_dataset.GetProjection()
print("1读取数组形状", img_array.shape,img_array.dtype.name)
if 'uint8' in img_array.dtype.name:
datatype = gdal.GDT_Byte
elif 'int16' in img_array.dtype.name:
datatype = gdal.GDT_UInt16
else:
datatype = gdal.GDT_Float32
if len(img_array.shape) == 3:
img_bands, im_height, im_width = img_array.shape
else:
img_bands, (im_height, im_width) = 1, img_array.shape
filename = read_path[:-4] + '_unit8' + ".tif"
driver = gdal.GetDriverByName("GTiff")
dataset = driver.Create(filename, im_width, im_height, img_bands, datatype)
dataset.SetGeoTransform(img_transf)
dataset.SetProjection(img_proj)
if img_bands == 1:
dataset.GetRasterBand(1).WriteArray(img_array)
else:
for i in range(img_bands):
dataset.GetRasterBand(i + 1).WriteArray(img_array[i])