from imutils import perspective import numpy as np import json import math file_name = 'TCXcp5VIsfhHZrh0nm2VsgBtcGy2_ZipML/gavl_json_obj.json' def order_points_new(pts): # sort the points based on their x-coordinates xSorted = pts[np.argsort(pts[:, 0]), :] # grab the left-most and right-most points from the sorted # x-roodinate points leftMost = xSorted[:2, :] rightMost = xSorted[2:, :] # now, sort the left-most coordinates according to their # y-coordinates so we can grab the top-left and bottom-left # points, respectively leftMost = leftMost[np.argsort(leftMost[:, 1]), :] (tl, bl) = leftMost # if use Euclidean distance, it will run in error when the object # is trapezoid. So we should use the same simple y-coordinates order method. # now, sort the right-most coordinates according to their # y-coordinates so we can grab the top-right and bottom-right # points, respectively rightMost = rightMost[np.argsort(rightMost[:, 1]), :] (tr, br) = rightMost # return the coordinates in top-left, top-right, # bottom-right, and bottom-left order return np.array([tl, tr, br, bl], dtype="float32") def solve(points): def key(x): atan = math.atan2(x[1], x[0]) return (atan, x[1]**2+x[0]**2) if atan >= 0 else (2*math.pi + atan, x[0]**2+x[1]**2) return sorted(points, key=key) f = open(file_name) data = json.load(f) polygon_num = 0 gavl_polygons = data["features"] for single_polygon in gavl_polygons: points = single_polygon["geometry"]["coordinates"] points = points[0] #new_points = [] # for p in points: # new_points.append([int(float(p[0])*10000000), int(float(p[1])*10000000)]) # #pts = np.array([[10,10],[10,20],[20,20],[30,10]]) # print(new_points) #pts = np.array(points) pts = points print(pts) print(solve(pts)) single_polygon["geometry"]["coordinates"][0] = solve(pts) gavl_polygons[polygon_num] = single_polygon polygon_num = polygon_num + 1 # #ordered_old = perspective.order_points(pts) # ordered_new = order_points_new(pts) # print("raw points") # print(pts.astype("int")) # print("ordered by Euclidean distance") # #print(ordered_old.astype("int")) # print("orderd by y-coordinates") # print(ordered_new.astype("int")) # print("") #break data["features"] = gavl_polygons # Serializing json json_object = json.dumps(data, indent=4) # Writing to sample.json with open("gavl_filtered.json", "w") as outfile: outfile.write(json_object)