Debian Codegraph @

examples/orient-ccw.py

raw
1 # An example of flipping feature polygons right side up.
2
3 import datetime
4 import logging
5 import sys
6
7 import fiona
8
9
10 logging.basicConfig(stream=sys.stderr, level=logging.INFO)
11
12 def signed_area(coords):
13 """Return the signed area enclosed by a ring using the linear time
14 algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0
15 indicates a counter-clockwise oriented ring.
16 """
17 xs, ys = map(list, zip(*coords))
18 xs.append(xs[1])
19 ys.append(ys[1])
20 return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0
21
22
23 with fiona.open('docs/data/test_uk.shp', 'r') as source:
24
25 # Copy the source schema and add two new properties.
26 schema = source.schema.copy()
27 schema['properties']['s_area'] = 'float'
28 schema['properties']['timestamp'] = 'str'
29
30 # Create a sink for processed features with the same format and
31 # coordinate reference system as the source.
32 with fiona.open(
33 'oriented-ccw.shp', 'w',
34 driver=source.driver,
35 schema=schema,
36 crs=source.crs
37 ) as sink:
38
39 for f in source:
40
41 try:
42
43 # If any feature's polygon is facing "down" (has rings
44 # wound clockwise), its rings will be reordered to flip
45 # it "up".
46 g = f['geometry']
47 assert g['type'] == 'Polygon'
48 rings = g['coordinates']
49 sa = sum(signed_area(r) for r in rings)
50 if sa < 0.0:
51 rings = [r[::-1] for r in rings]
52 g['coordinates'] = rings
53 f['geometry'] = g
54
55 # Add the signed area of the polygon and a timestamp
56 # to the feature properties map.
57 f['properties'].update(
58 s_area=sa,
59 timestamp=datetime.datetime.now().isoformat() )
60
61 sink.write(f)
62
63 except Exception as e:
64 logging.exception("Error processing feature %s:", f['id'])
65