遥感图像合并

从文件夹中读取小范围的遥感影像并合并成一大图

遥感图像合并

读取tiff影像

采用opencv库也能读取,但是不能读取其中保存的坐标等信息;一般采用gdal库进行读取:

1
2
3
4
5
6
7
8
9
10
11
12
13
from osgeo import gdal
from gdalconst import *

image_dataset = gdal.Open(image_path, GA_ReadOnly)
if image_dataset is None:
print("文件读写错误!!!")
return
image_geotransform = image_dataset.GetGeoTransform()
image_width, image_height = image_dataset.RasterXSize, image_dataset.RasterYSize
image_data = image_dataset.ReadAsArray(0, 0, image_width, image_height)
print(image_geotransform)
print(image_width, image_height)
print(image_data.shape)

保存tiff影像

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]
#ipdb.set_trace()

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:
#dataset.GetRasterBand(1).SetNoDataValue(nodata)
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.")

具体代码可参考https://github.com/lover-520/lover-notes