Friday, November 13, 2015

Arcpy: Convert Shapefile to Raster

Introduction

          Converts features to a raster dataset.
Any feature class (geodatabase, shapefile or coverage) containing point, line, or polygon features can be converted to a raster dataset.
The input field type determines the type of output raster. If the field is integer, the output raster will be integer, if it is floating point, the output will be floating point

Example

       文件夹input包含输入文件,output包含输出文件。
       代码:
 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
# Created by LI Xu
# Version 1.0
# November 14, 2015

# Description:
# Conversion features to a raster

# If you have any question about this code,
# please do not hesitate to contact me via E-mail: 
# jeremy456@163.com

# Blog:
# http://blog.sciencenet.cn/u/lixujeremy

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

def GetFileListExt(SouDir, FlagStr):
    import glob, os
    FileList=[]
    os.chdir(SouDir)
    filter_str='*'+FlagStr
    #print filter_str
    for filepath in glob.glob(filter_str):
        FileList.append(os.path.join(SouDir, filepath))
    return FileList

# Main program
# Source Directory
SouDir=r'E:\Tools\ConFeatures2Rasyers\input'
# Destination Directory
DesDir=r'E:\Tools\ConFeatures2Rasyers\output'
# Cell Size
CellSize=1000
# All Input Files
FlagStr='.shp'
files=GetFileListExt(SouDir, FlagStr)
for filepath in files:
    fieldlist=arcpy.ListFields(filepath)
    otname=filepath.split('\\')
    otname=otname[len(otname)-1]
    otname=otname.split('.')
    otname=otname[0]
    for field in fieldlist[4:]:
        otpath=DesDir+'\\'+otname+'_'+field.name+'.tif'
        arcpy.FeatureToRaster_conversion(filepath,
                                         field.name,
                                         otpath,
                                         CellSize)
        print otpath
        
        
    


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'
       附件文件

References

[1] Feature to Raster (Conversion) - ArcGIS Help.

No comments:

Post a Comment