# -*- coding:utf-8 -*-
import os
import arcpy
from arcpy import env
sourceDir=u'E:' #中文路径 输入
targetDir=u'E:' #英文路径 输出
arcpy.CheckOutExtension("Spatial")
env.workspace = sourceDir
arcpy.env.scratchWorkspace = sourceDir
hdfList = arcpy.ListRasters('*','hdf')
for hdf in hdfList:
print hdf
eviName=os.path.basename(hdf).replace('hdf','tif')
outname=targetDir+'\\'+eviName
print outname
data1=arcpy.ExtractSubDataset_management(hdf,outname, "Eight_Day_Snow_Cover") #Eight_Day_Snow_Cover是子数据集名称
##
print 'all done'
接下来是获取每个HDF/TIF 年内天数数据,生成列表或文件,以方便后期判断合成日期是否一致
import os
import glob
import pandas as pd
path=r'E:\data'
outws=r'E:\天数列表'
rasters = glob.glob(os.path.join(path, "*.tif"))
for year in range(2000,2020):#这里数据是2000-2019年
days_list=[]
for ras in rasters:
info=os.path.basename(ras).split('.')[1]
info=info.replace('A','')
if str(info[:4])==str(year):
days=info[4:7] #截取天数
days_list.append(days)
outname=outws+'\\'+str(year)+'.csv'#输入文件名
days_list_f=list(set(days_list))
days_list_f.sort(reverse=False)
days_list_df=pd.DataFrame(days_list_f)
days_list_df.columns=['days']# df设置列名
days_list_df.to_csv(outname,header=True,encoding='gbk') #写入文件CSV
然后继续拼接tif
# -*- coding:gbk-*-
import arcpy
import glob
import os
from arcpy import env
import pandas as pd
arcpy.CheckOutExtension("Spatial")
#指定影像所在目录
env.workspace =r'E:'#输入路径
inws =r'E:' #输入路径
##inws=inws.encode('utf-8')
outws = r'E:' #输出路径
mask = r"E:\WGS84Project.prj" #投影文件
days_inws=r'E:\天数列表'
#判断日期函数,由于MODIS数据文件是以年内天数命名,为了将其转为日期,并给镶嵌后的文件重新命名,如2001001变为2001_01_01
def out_date(year,day):
fir_day = datetime.datetime(year,1,1)
zone = datetime.timedelta(days=day-1)
return datetime.datetime.strftime(fir_day + zone, "%Y_%m_%d")
#利用glob包,将inws下的所有tif文件读存放到rasters中
##rasters = glob.glob(os.path.join(inws, "*.tif"))
csv_file = glob.glob(os.path.join(days_inws, "*.csv"))
for year in csv_file:
year_csv=os.path.basename(year).split('.')[0]
data=pd.read_csv(year,encoding='gbk')
days=list(data['days'])
for d in days:
raster_list=[]
day=int(str(d))
print day,year_csv
for ras in arcpy.ListFiles("*.tif"):
#循环rasters中的所有影像,进行按掩模提取操作
info=os.path.basename(ras).split('.')[1]
info=info.replace('A','')
day_info=int(info[4:7])
if str(info[:4])==str(year_csv) and day==day_info:
raster_list.append(ras)
print info
year_info_shift=info[:4]
days_info_shift=info[4:7]
#生成文件名日期
finame_1=out_date(int(year_info_shift),int(days_info_shift))
print finame_1
## #完整文件名
outname=finame_1+'_MOD10A2.tif'
print outname
try:
##Mosaic several TIFF images to a new TIFF image
arcpy.MosaicToNewRaster_management(raster_list,outws, outname, mask,\
"32_BIT_UNSIGNED", "", "1", "LAST","FIRST")
except:
print "Mosaic To New Raster example failed."
print arcpy.GetMessages()
print 'mosaic finish'
拼接结果: