简体   繁体   中英

How to stack images as raster bands in a single GeoTiff with GDAL VRT?

I have a bunch of.tif images but i want to stack all of them as 1.Tif image. How do i stack all the.Tif files using gdalVrt??

from osgeo import gdal
from PIL import Image
import numpy as np
from numpy import asarray
import matplotlib.pyplot as plt
import os

os.listdir('../LC08_L1TP_137042_20210301_20210301_01_RT/')


band1=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B1.TIF')
band2=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B2.TIF')
band3=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B3.TIF')
band4=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B4.TIF') # near infra red
band5=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B5.TIF') # near infra red
band6=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B6.TIF')
band7=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B7.TIF')
band8=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B8.TIF')
band9=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B9.TIF')
band10=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B10.TIF')
band11=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_B11.TIF')
band12=gdal.Open('LC08_L1TP_137042_20210301_20210301_01_RT_BQA.TIF')

band1_array = band4.ReadAsArray()
band2_array = band4.ReadAsArray()
band3_array = band4.ReadAsArray()
band4_array = band4.ReadAsArray()
band5_array = band4.ReadAsArray()
band6_array = band4.ReadAsArray()
band7_array = band4.ReadAsArray()
band8_array = band5.ReadAsArray()
band9_array = band4.ReadAsArray()
band10_array = band4.ReadAsArray()
band11_array = band4.ReadAsArray()
band12_array = band4.ReadAsArray()

stack= (band1_array+band2_array+band3_array+band4_array+band5_array+band6_array+band7_array+band8_array+band9_array+band10_array+band11_array+band12_array)
print("The stacked images is \n \n", plt.imshow(stack))

I am sure this isnt the right way..

Step 1.) Create a virtual raster (VRT) with option "separate=True" to stack the images as separate bands:

from osgeo import gdal
ImageList = ['Band1.tif', 'Band2.tif', 'Band3.tif']  # or use sorted(glob.glob('*.tif')) if input images are sortable
VRT = 'OutputImage.vrt'
gdal.BuildVRT(VRT, ImageList, separate=True, callback=gdal.TermProgress_nocb)

Step 2.) Translate virtual raster (VRT) into GeoTiff:

InputImage = gdal.Open(VRT, 0)  # open the VRT in read-only mode
gdal.Translate('OutputImageName.tif', InputImage, format='GTiff',
               creationOptions=['COMPRESS:DEFLATE', 'TILED:YES'],
               callback=gdal.TermProgress_nocb)
del InputImage  # close the VRT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM