Saturday, 23 June 2018

Randomly rotating polygons in shapefile using ArcPy?



I have a shapefile with polygons and want to rotate each of them randomly. Centroid of the polygon should be the anchor point of rotation.


Rotation example:



enter image description here



Answer



This script will make a copy of your shapefile and randomly rotate every polygon:


# -*- coding: utf-8 -*-
import math
import arcpy
import numpy

def Transform_coords(x, y, angle, polygon_centroid):
radians = math.radians(angle)

(X,Y) = polygon_centroid

x_trans = x - X
y_trans = y - Y

x_transprime = math.cos(radians) * x_trans - math.sin(radians) * y_trans
y_transprime = math.sin(radians) * x_trans + math.cos(radians) * y_trans

x_prime = x_transprime + X
y_prime = y_transprime + Y


return x_prime, y_prime

def main(shp_file, new_shp_file):
arcpy.env.overwriteOutput = True

arcpy.MakeFeatureLayer_management (shp_file, "polygon")
sr = arcpy.Describe("polygon").spatialReference
features = []


with arcpy.da.SearchCursor("polygon", ["SHAPE@", "SHAPE@XY"]) as cursor:
for row in cursor:

array = numpy.random.uniform(0, 360, size = 1)
angle = array.tolist()[0]

for feature_parts in row[0]:
feature = []

polygon_centroid = row[1]


for coord in feature_parts:
x = coord.X
y = coord.Y

new_x, new_y = Transform_coords(x, y, angle, polygon_centroid)
feature.append([new_x, new_y])

points = arcpy.Array([arcpy.Point(*coords) for coords in feature])
polygon_feature = arcpy.Polygon(points,sr)

features.append(polygon_feature)

arcpy.CopyFeatures_management(features, new_shp_file)

if __name__ == "__main__":
main(
shp_file = r"G:\Scripts\py_test\Misc\Arcpy_rotate_polygon_DEL\New_Shapefile.shp",
new_shp_file = r"G:\Scripts\py_test\Misc\Arcpy_rotate_polygon_DEL\TEST.shp"
)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...