当前位置:网站首页>GDAL multiband synthesis tool
GDAL multiband synthesis tool
2022-06-26 14:23:00 【Chaoying.】
A set of The coordinate system is the same 、 The number of ranks is the same Of Single band tif image Merge into Multiband tif image
On the first code
#!D:\ProgramData\Anaconda3\python.exe
# Appoint python Indicator
import argparse
import os
import re
from osgeo import gdal
from osgeo import osr
from osgeo import gdal_array
from tqdm import tqdm
# Set parameters
parser = argparse.ArgumentParser(
' Multi band synthesis tool : Combine multiple single bands tif The files are merged into one multi band tif file , To be merged tif The file must have the same spatial reference and number of rows and columns ')
parser.add_argument('--inputpath', type=str,
required=True, help=' Include to be merged tif File directory ')
parser.add_argument('--filter', type=str, default=None,
help=' Filter conditions , It should be a regular expression , Filter the files in the input directory ')
parser.add_argument('--outpath', type=str, default='./',
help=' Directory of output files , Default to current directory ')
parser.add_argument('--outname', type=str, required=True, help=' Output file name ')
args = parser.parse_args()
# To obtain parameters
inputpath = args.inputpath
filterstr = args.filter
outpath = args.outpath
outname = args.outname
# Filter files
files = os.listdir(inputpath)
# Can only handle tif File format
files = list(filter(lambda file: file.endswith('.tif'), files))
if len(files) == 0:
print(' Can only handle tif file !')
exit()
# Filter eligible files based on the passed in regular expression
files = list(filter(lambda file: re.search(filterstr, file), files))
if len(files) == 0:
print(' There are no pending files that meet the filter criteria !')
exit()
# Filter spatial references and row / column numbers with processed images
gdal.AllRegister()
srs = None
gt=None
row = -9999
col = -9999
dtypes = []
for file in files:
ds = gdal.Open(os.path.join(inputpath, file))
band = gdal.Dataset.GetRasterBand(ds, 1)
dtypes.append(band.DataType)
if row == -9999 and col == -9999:
col = band.XSize
row = band.YSize
srs = gdal.Dataset.GetSpatialRef(ds)
gt=gdal.Dataset.GetGeoTransform(ds)
else:
if row != band.YSize or col != band.XSize:
print(' The images to be merged must have the same row and column number !')
exit()
elif not(osr.SpatialReference.IsSame(srs, gdal.Dataset.GetSpatialRef(ds))):
print(' The images to be merged must have the same spatial reference !')
exit()
else:
pass
driver = gdal.GetDriverByName('GTiff')
N = len(files)
# Set the data type of the output file
dMax = max(dtypes)
# Estimate the size of the output file , Based on this, decide whether to create BIGTIFF
GDT_dict = dict([
(1,8),
(2,16),
(3,16),
(4,32),
(5,32),
(6,32),
(7,64),
(8,16),
(9,32),
(10,32),
(11,64)])
outSize=GDT_dict[dMax]*col*row/8/1024/1024/1024*N
bigTiffFlag='YES' if outSize>=4 else 'NO'
outds = gdal.Driver.Create(driver, os.path.join(
outpath, outname), col, row, N, dMax, ["COMPRESS=LZW", f"BIGTIFF={
bigTiffFlag}"])
gdal.Dataset.SetSpatialRef(outds,srs)
gdal.Dataset.SetGeoTransform(outds,gt)
# Start merging files
print(' The documents to be merged are :\n{}'.format('\n'.join(files)))
pbar = tqdm(files, colour='blue')
for file in pbar:
pbar.set_description(' Dealing with {}'.format(file))
filearr = gdal_array.LoadFile(os.path.join(inputpath, file))
i=files.index(file)
outband=gdal.Dataset.GetRasterBand(outds,i+1)
gdal.Band.WriteArray(outband,filearr)
print('finished!')
Example 
bands_composite.py --inputpath=../months_lzw --filter=odiac2020b_1km_excl_intl_00[0-9]{
2}.tif --outpath=./ --outname=2000.tif
Results output 
View the multi band output tif image 
边栏推荐
- Bug memory management
- transformers DataCollatorWithPadding类
- Never use redis expired monitoring to implement scheduled tasks!
- From Celsius to the three arrows: encrypting the domino of the ten billion giants, and drying up the epic liquidity
- Matlab programming related knowledge
- D check type is pointer
- [cqoi2015] task query system
- d的is表达式
- C language ---getchar() and putchar()
- Sword finger offer 45.61 Sort (simple)
猜你喜欢

Intellij IDEA--格式化SQL文件的方法

9 articles, 6 interdits! Le Ministère de l'éducation et le Ministère de la gestion des urgences publient et publient conjointement neuf règlements sur la gestion de la sécurité incendie dans les établ

Setup instance of layout manager login interface

Eigen(3):error: ‘Eigen’ has not been declared

Sword finger offer 06.24.35 Linked list

ICML 2022 | limo: a new method for rapid generation of targeted molecules

Related knowledge of libsvm support vector machine

Stream常用操作以及原理探索

RISC-V 芯片架构新规范

永远不要使用Redis过期监听实现定时任务!
随机推荐
Stream常用操作以及原理探索
CF676C Vasya and String
Installation and uninstallation of MySQL software for windows
C language ---getchar() and putchar()
How to check if a text field is empty or not in swift
1075 pat judge (25 points)
d的is表达式
8. Ribbon load balancing service call
程序员必备,一款让你提高工作效率N倍的神器uTools
C language | file operation and error prone points
ArcGIS secondary development - arcpy delete layer
Never use redis expired monitoring to implement scheduled tasks!
9 regulations and 6 prohibitions! The Ministry of education and the emergency management department jointly issued the nine provisions on fire safety management of off campus training institutions
Pychar remotely connects to the server to run code
[cqoi2015] task query system
Leaflet loading ArcGIS for server map layers
7.consul service registration and discovery
One article of the quantification framework backtrader read observer
Bug memory management
Common evaluation indexes of classification model -- confusion matrix and ROC curve