1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| def write_tif_image(img, path, geotrans=None, proj=None, nodata=0): if img is None: return else: if type(img) == list: if len(img) == 1: img = img[0][..., np.newaxis] else: base = img[0][..., np.newaxis] for i in range(1, len(img)): out = np.concatenate((base, img[i][..., np.newaxis]), axis=2) img = out
band1 = img[:,:,0] img_width = band1.shape[1] img_height = band1.shape[0] num_bands = img.shape[2]
if 'int8' in band1.dtype.name: datatype = gdal.GDT_Byte elif 'int16' in band1.dtype.name: datatype = gdal.GDT_UInt16 elif 'float64' in band1.dtype.name: datatype = gdal.GDT_Float64 else: datatype = gdal.GDT_Float32
driver = gdal.GetDriverByName("GTiff") dataset = driver.Create(path, img_width, img_height, num_bands, datatype, options = ['BigTIFF=YES'])
if dataset is not None: if geotrans is not None: dataset.SetGeoTransform(geotrans) if proj is not None: dataset.SetProjection(proj) for i in range(num_bands): dataset.GetRasterBand(i + 1).WriteArray(img[:,:,i]) dataset.BuildOverviews('average',[2,4,8,16,32,64,128]) dataset.FlushCache() del dataset print("save image success.")
|