-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubtract.py
87 lines (67 loc) · 2.58 KB
/
subtract.py
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
try:
from osgeo import ogr
except ImportError:
import ogr
import sys, os
def subtract(sourceFile, maskFile):
outputFileName = 'difference'
driver = ogr.GetDriverByName("ESRI Shapefile")
source = driver.Open(sourceFile,0)
sourceLayer = source.GetLayer()
if source is None:
print "Could not open file ", sourceFile
sys.exit(1)
mask = driver.Open(maskFile,0)
maskLayer = mask.GetLayer()
if mask is None:
print "Could not open file ", maskFile
### Create output file ###
if os.path.exists(outputFileName):
os.remove(outputFileName)
try:
output = driver.CreateDataSource(outputFileName)
except:
print 'Could not create output datasource ', outputFileName
sys.exit(1)
# newLayer = output.CreateLayer('difference',geom_type=ogr.wkbPolygon,srs=sourceLayer.GetSpatialRef())
newLayer = output.CreateLayer('difference',geom_type=ogr.wkbMultiLineString,srs=sourceLayer.GetSpatialRef())
prototypeFeature = sourceLayer.GetFeature(0)
for i in range(prototypeFeature.GetFieldCount()):
newLayer.CreateField(prototypeFeature.GetFieldDefnRef(i))
prototypeFeature.Destroy()
if newLayer is None:
print "Could not create output layer"
sys.exit(1)
newLayerDef = newLayer.GetLayerDefn()
##############################
processedCount = 0
featureID = 0
total = sourceLayer.GetFeatureCount()
sourceFeature = sourceLayer.GetNextFeature()
while sourceFeature:
sourceGeom = sourceFeature.GetGeometryRef()
maskLayer.ResetReading()
maskLayer.SetSpatialFilter(sourceGeom)
maskFeature = maskLayer.GetNextFeature()
while maskFeature:
maskGeom = maskFeature.GetGeometryRef()
sourceGeom = sourceGeom.Difference(maskGeom)
maskFeature.Destroy()
maskFeature = maskLayer.GetNextFeature()
if sourceGeom.Length() > 0:
newFeature = ogr.Feature(newLayerDef)
newFeature.SetGeometry(sourceGeom)
newFeature.SetFID(featureID)
for i in range(sourceFeature.GetFieldCount()):
newFeature.SetField(i, sourceFeature.GetField(i))
newLayer.CreateFeature(newFeature)
featureID += 1
newFeature.Destroy()
sourceFeature.Destroy()
sourceFeature = sourceLayer.GetNextFeature()
processedCount += 1
print "%d / %d / %d" % (processedCount, featureID, total)
source.Destroy()
mask.Destroy()
if __name__ == "__main__":
subtract(sys.argv[1], sys.argv[2])