Thursday, November 19, 2015

Python+GDAL: 文件格式的转换

空间数据的格式千变万化,常见的有ENVI Standard、GEOTIFF、Erads Image等等(栅格文件列表矢量文件列表),以下应用GDAL工具转换文件的格式,省时高效。
举个栗子,ENVI Standard转换为GEOTIFF,参考How to call gdal_translate from Python code? Answered by Max

Note

os.system (command): Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(). On Windows, the return value is that returned by the system shell after running command. 实际上,示例是Python调用C+GDAL的代码。
 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
##Created by LI Xu
##Version 1.0
##7 October, 2014


##Convert ENVI Standard to GEOTIFF

##http://gis.stackexchange.com/questions/42584/how-to-call-gdal-translate-from-python-codearray-returns-just-nan-values-when-trying-to-read-envi-file


import gdal
import ogr
import os
import datetime
import time





def IsSubString(SubStrList,Str):  
 
    flag=True  
    for substr in SubStrList:  
        if not(substr in Str):  
            flag=False  
  
    return flag  
#~ #----------------------------------------------------------------------


def GetFileList(FindPath,FlagStr=[]):  

    import os  
    FileList=[]  
    FileNames=os.listdir(FindPath)  
    if (len(FileNames)>0):  
       for fn in FileNames:  
           if (len(FlagStr)>0):  
               
               if (IsSubString(FlagStr,fn)):  
                   fullfilename=os.path.join(FindPath,fn)  
                   FileList.append(fullfilename)  
           else:  
               
               fullfilename=os.path.join(FindPath,fn)  
               FileList.append(fullfilename)  
  
    
    if (len(FileList)>0):  
        FileList.sort()  
  
    return FileList  

def convert_format(infile, otfile, oFormat):
    os.system("gdal_translate -of" +" " +oFormat+" "+ infile + " " +  otfile)

##Main
begintime=time.strftime("%Y-%m-%d %H:%M:%S")
print 'Time Begin:'+begintime
starttime = datetime.datetime.now()

#Source Directory
SouDir=r'E:\Tools\rad\NEW'
#Destination Directory
DesDir=r'E:\Tools\rad\Rad'


#Retrieve files
FlagStr='.hdr'
files=GetFileList(SouDir,FlagStr)
for file in files:
    #print file
    str_file=file.split('.')
    infile=str_file[0]+'.tif'
    #print infile
    oformat="GTiff"
    ##Output Image
    filename=infile.split('\\')
    filename=filename[len(filename)-1]
    filename=filename.split('.')
    otimg=DesDir+'\\'+filename[0]+'.tif'
    print otimg
    convert_format(infile, otimg, oformat)
    



print "END"
endtime=time.strftime("%Y-%m-%d %H:%M:%S")
print 'Time End:'+endtime
finishtime=datetime.datetime.now()
timespan=(finishtime-starttime).seconds
timespan='%f' %timespan
print 'Time Span:'+timespan+' s'

No comments:

Post a Comment