用pyshp调整多边形的大小

时间:2018-03-21 08:26:20

标签: python shapefile

嗨,我想写一个脚本,它将调整现有shapefile中的多边形大小并使用PyShp库保存它。

enter code here
import shapefile

fileName = "" ##file name
r = shapefile.Reader(fileName)
records = r.records()
w = shapefile.Writer(r.shapeType)
w.fields = r.fields[1:]

size = len(list(r.iterShapes()))
for i in range(1, size):
    t = r.shapeRecords()[i]
    info = t.shape.__geo_interface__
    allPoints = info['coordinates']
    w.fields = list(r.fields)
    w.records.extend(r.records())
    w._shapes.extend(r.shapes())

    points = allPoints[0]
    point1 = points[0]
    point2 = points[1]
    point3 = points[2]
    point4 = points[3]

    avgX = (point1[0] + point2[0] + point3[0] + point4[0])/4
    avgY = (point1[1] + point2[1] + point3[1] + point4[1])/4

    newX1 = 1.7*(point1[0] - avgX) + avgX
    newX2 = 1.7*(point2[0] - avgX) + avgX
    newX3 = 1.7*(point3[0] - avgX) + avgX
    newX4 = 1.7*(point4[0] - avgX) + avgX

    newY1 = 1.7*(point1[1] - avgY) + avgY
    newY2 = 1.7*(point2[1] - avgY) + avgY
    newY3 = 1.7*(point3[1] - avgY) + avgY
    newY4 = 1.7*(point4[1] - avgY) + avgY

    newPoint1 = [newX1, newY1]
    newPoint2 = [newX2, newY2]
    newPoint3 = [newX3, newY3]
    newPoint4 = [newX4, newY4]

    newPoints = [newPoint1, newPoint2, newPoint3, newPoint4, newPoint1, 
    newPoint1]

 w.save('')

这是我有多远。现在我的问题是如何正确编写新的shapefile?

1 个答案:

答案 0 :(得分:0)

一段时间前,我注意到这个悬而未决的问题,所以我用它来提高我的pyshp技能:)。您错过了w.poly()来将新点保存到多边形中。

import shapefile

fileName = r"shapefile.shp"
r = shapefile.Reader(fileName)

w = shapefile.Writer(r.shapeType)
w.fields = r.fields[1:]

for shprec in r.iterShapeRecords():
    points = shprec.shape.points

    point1 = points[0]
    point2 = points[1]
    point3 = points[2]
    point4 = points[3]

    avgX = (point1[0] + point2[0] + point3[0] + point4[0])/4
    avgY = (point1[1] + point2[1] + point3[1] + point4[1])/4

    newX1 = 1.7*(point1[0] - avgX) + avgX
    newX2 = 1.7*(point2[0] - avgX) + avgX
    newX3 = 1.7*(point3[0] - avgX) + avgX
    newX4 = 1.7*(point4[0] - avgX) + avgX

    newY1 = 1.7*(point1[1] - avgY) + avgY
    newY2 = 1.7*(point2[1] - avgY) + avgY
    newY3 = 1.7*(point3[1] - avgY) + avgY
    newY4 = 1.7*(point4[1] - avgY) + avgY

    newPoint1 = [newX1, newY1]
    newPoint2 = [newX2, newY2]
    newPoint3 = [newX3, newY3]
    newPoint4 = [newX4, newY4]

    newPoints = [newPoint1, newPoint2, newPoint3, newPoint4, newPoint1, 
    newPoint1]

    w.poly(parts = [newPoints])
    w.record(shprec.record[0])

w.save(r"shapefile_resized.shp")

我假设多边形只有4个顶点。

相关问题