def getFairPartitioning(poly, n_partitions, display=False): polyg_coords = [tuple(e) for e in poly.vertices] if n_partitions < 1: raise ValueError elif n_partitions == 1: return [poly] else: polyg = Polygon(*polyg_coords) target_area = abs(polyg.area) / n_partitions chosen_vertex = polyg_coords[0] final_polygons = [] original_polyg_coords = polyg_coords polyg_coords = orderCoords(polyg_coords) original_n_parition = n_partitions for i in range(original_n_parition - 1): sub_polygon, other = fin_sub_poly(not (i % 2 == 0), polyg_coords, chosen_vertex, target_area) final_polygons.append(sub_polygon) if i == original_n_parition - 2: other = Polygon( *orderCoords([tuple(v) for v in other.vertices])) final_polygons.append(other) polyg_coords = [tuple(e) for e in other.vertices] polyg_coords = orderCoords(polyg_coords) plotPoly(original_polyg_coords, 'black') plotPoly([tuple(e) for e in sub_polygon.vertices], 'black') n_partitions -= 1 polyg = Polygon(*polyg_coords) target_area = abs(polyg.area) / n_partitions chosen_vertex = tuple(other.vertices[-1]) if display: plt.show() return final_polygons
def splitCPPpolygon(cell, cutline): i = 0 uppoints = [] downpoints = [] for side in cell.sides: if (side.contains(cutline[0])): leftupindex = i leftdownindex = (i + 1) % len(cell.sides) if (side.contains(cutline[-1])): rightdownindex = i rightupindex = (i + 1) % len(cell.sides) i = i + 1 if (leftupindex >= rightupindex): uppoints.extend(cell.vertices[rightupindex:leftupindex + 1]) else: uppoints.extend(cell.vertices[rightupindex:len(cell.vertices)]) uppoints.extend(cell.vertices[0:leftupindex + 1]) uppoints.extend(cutline) if (leftdownindex <= rightdownindex): downpoints.extend(cell.vertices[leftdownindex:rightdownindex + 1]) else: downpoints.extend(cell.vertices[leftdownindex:len(cell.vertices)]) downpoints.extend(cell.vertices[0:rightdownindex + 1]) cutline.reverse() downpoints.extend(cutline) downpolygon = Polygon(*downpoints) uppolygon = Polygon(*uppoints) return downpolygon, uppolygon
def get_plot_data(self, x, y, subplot=0): 'get the plot data at x, y, or None if not found' rv = None mode_to_obj = self.mode_to_obj_list[subplot] clicked = Point(x, y) for mode, obj_list in mode_to_obj.items(): for obj in obj_list: verts = obj[0] if len( verts ) < 4: # need at least 3 points (4 with wrap) to be clicked inside continue verts_2dp = [Point2D(x, y) for x, y in verts[1:]] poly = Polygon(*verts_2dp) if poly.encloses_point(clicked): rv = obj break if rv is not None: break return rv
def parse_county(lat, lng): poi = Point(lng, lat) for city_geo_data in city_geo_datas: polygons = city_geo_data['geometry']['coordinates'] polygons = [polygons] if city_geo_data['geometry']['type'] == 'Polygon' else polygons for polygon_coordinates in polygons: polygon = Polygon(*polygon_coordinates[0]) if polygon.encloses_point(poi): return city_geo_data['properties']['name'] raise 'not in taiwan'
def isInRoom(roomBlob, lat, lon, alt): roomJson = json.loads(roomBlob) if (alt - roomJson['alt'] > 10 or alt < roomJson['alt']): return False p1 = Point(roomJson['corner1'][1], roomJson['corner1'][0]) p2 = Point(roomJson['corner2'][1], roomJson['corner2'][0]) p3 = Point(roomJson['corner3'][1], roomJson['corner3'][0]) p4 = Point(roomJson['corner4'][1], roomJson['corner4'][0]) pn = Point(lon, lat) poly = Polygon(p1, p2, p3, p4) return poly.encloses_point(pn)
def create_polygon(position_sensor): s = str(position_sensor) x = float(s.split("{'x': ")[1].split(", 'y':")[0]) y = float(s.split("'y': ")[1].split(", '")[0]) theta = math.atan2(y, x) if sensor_type(s) == "fence": length = float(s.split("'length': ")[1].split("}")[0]) width = 0.5 center = np.array([x, y]) center_norm = norm(center) # print("normed center: " + str(center_norm)) # print("perpendicular = " + str(perpendicular_vector(center))) # print("center = " + str(center)) a = center + (center / center_norm ) * width / 2 + perpendicular_vector(center) * length / 2 # print("a = " + str(a)) b = center + (center / center_norm ) * width / 2 - perpendicular_vector(center) * length / 2 # print("b = " + str(b)) c = center - (center / center_norm ) * width / 2 - perpendicular_vector(center) * length / 2 # print("c = " + str(c)) d = center - (center / center_norm ) * width / 2 + perpendicular_vector(center) * length / 2 # print("d = " + str(d)) poly = Polygon([a, b, c, d]) return poly if sensor_type(s) == "mat": width = float(s.split("'width': ")[1].split(", 'length':")[0]) length = float(s.split("'length': ")[1].split("}")[0]) center = np.array([x, y]) center_norm = norm(center) a = center + (center / center_norm ) * width / 2 + perpendicular_vector(center) * length / 2 b = center - (center / center_norm ) * width / 2 + perpendicular_vector(center) * length / 2 c = center - (center / center_norm ) * width / 2 - perpendicular_vector(center) * length / 2 d = center + (center / center_norm ) * width / 2 - perpendicular_vector(center) * length / 2 poly = Polygon([a, b, c, d]) return poly if sensor_type(s) == "lidar": r = float(s.split("'lidar_range': ")[1].split(", 'angle_res':")[0]) angle = float(s.split("'max_angle': ")[1].split(", 'rate':")[0]) center = np.array([x, y]) theta1 = theta - angle / 2 theta2 = theta + angle / 2 wedge_patch = Wedge(center, r, theta1, theta2) wedge_path = wedge_patch.get_path() wedge_polygon = asPolygon(wedge_path.vertices).buffer(0) return wedge_polygon
def parse_county(lat, lng): poi = Point(lng, lat) for city_geo_data in city_geo_datas: polygons = city_geo_data['geometry']['coordinates'] polygons = [ polygons ] if city_geo_data['geometry']['type'] == 'Polygon' else polygons for polygon_coordinates in polygons: polygon = Polygon(*polygon_coordinates[0]) if polygon.encloses_point(poi): return city_geo_data['properties']['name'] raise 'not in taiwan'
def check_selected_polygon(self): valid_polygon = False if(len(self.points)> 2): if Polygon(*self.points).is_convex(): valid_polygon = True elif Polygon(*(self.points[::-1])).is_convex(): # check anticlockwise valid_polygon = True self.points = self.points[::-1] else: valid_polygon = False else: valid_polygon = False return valid_polygon
def check_overlap(gmap_a, gmap_b): gmap_a = [(x, y) for x, y in gmap_a.reshape(-1, 2)] gmap_b = [(x, y) for x, y in gmap_b.reshape(-1, 2)] poly_a = Polygon(*gmap_a) poly_b = Polygon(*gmap_b) for point in poly_a.vertices: if poly_b.encloses(point): return 1 return -1
def __init__(self, d, t): sqrt3 = sympy.sqrt(3) lp = (-d, -sqrt3 * d / 2) self.outter = Polygon( *map(Point, ((-d, 0), (-d / 2, -sqrt3 * d / 2), (d / 2, -sqrt3 * d / 2), (d / 2, sqrt3 * d / 2), (d, 0), (-d / 2, sqrt3 * d / 2)))).translate(x=-lp[0], y=-lp[1]) d -= t * 2 / sqrt3 self.inner = Polygon(*map(Point, ((-d, 0), (-d / 2, -sqrt3 * d / 2), (d / 2, -sqrt3 * d / 2), (d / 2, sqrt3 * d / 2), (d, 0), (-d / 2, sqrt3 * d / 2)))).translate( x=-lp[0], y=-lp[1])
def within_state(latidute, longitude, border_array): print("debug:\n lat:: %s\n lon:: %s\n borders:: %s" % (latidute, longitude, border_array)) test_point = Point(latidute, longitude) print("Point used successfully") Point_arr = [Point(x[0], x[1]) for x in border_array] Pennsylvania_Polygon = Polygon(*Point_arr) print("Pennsylvania area: %s" % Pennsylvania_Polygon) return Pennsylvania_Polygon.encloses_point(test_point)
def roundpolygon(polygon): newvertices = [] for vertice in polygon.vertices: newvertice = Point(round(vertice.x, 6), round(vertice.y, 6)) newvertices.append(newvertice) newpolygon = Polygon(*newvertices) return newpolygon
def metric_intragroup_distance(self, subjects: dict): subjects_distance = dict() neck_keypoint = None for subject_id, subject in subjects.items(): subject_pose = subject.current_pose for camera, keypoints in subject_pose.items(): if camera not in subjects_distance: subjects_distance[camera] = dict() neck_keypoint = tuple( keypoints[str(DENSEPOSE_KEYPOINT_MAP['neck'])]) subjects_distance[camera][subject_id] = neck_keypoint[:2] intragroup_distance = dict() for camera, subjects in subjects_distance.items(): points = list(subjects.values()) points.append(points[0]) polygon = Polygon(*points) polygon_area = None try: polygon_area = float(abs(polygon.area)) except AttributeError: print(self.current_frame, camera, polygon, polygon_area) centroid = (sum([point[0] for point in points]) / len(points), sum([point[1] for point in points]) / len(points)) polygon_center = [float(centroid[0]), float(centroid[1])] intragroup_distance[camera] = {'polygon': points, 'area': polygon_area, 'center': polygon_center} return intragroup_distance
def test_2(self): print("test_2") graph = utils.Graph() # Make two overlapping polygons p0 = Polygon((0, 0), (0, 2), (2, 2), (2, 0)) graph.add_polygon(p0) p1 = Polygon((1, 1), (1, 3), (3, 3), (3, 1)) graph.add_polygon(p1) # Show nodes print("Node points:", [n.point for n in graph.nodes]) ext_nodes = graph.get_exterior_nodes() print("Exterior points:", [n.point for n in ext_nodes]) self.assertEqual(8, len(ext_nodes)) print("Exterior segments:", graph.get_exterior_segments())
def poligon(sez): points=[] sez1 = sez[::-1] for tocka in naredi_points(sez1): points.append(tocka) t = tuple(points) p = Polygon(*t) return p
def p102(): with open("../data/p102-triangles.txt") as f: num = 0 for line in f: it = map(int, line.split(",")) if Polygon(*zip(it, it)).encloses_point((0, 0)): num += 1 return num
def compareValueinStruct(cell0, lpos0, cell1, lpos1, centroids, x0, x1, z0, z1, n0, n1): vertices = findPointsofRect(x0, x1, z0, z1) rect = Polygon(vertices[0], vertices[1], vertices[3], vertices[2]) points = [] for point in centroids: if (rect.encloses_point(point)): points.append(point) cell0V = findValueofcell(cell0, points, lpos0) cell1V = findValueofcell(cell1, points, lpos1) if ((n1 / n0) > 0.65 and cell1V > cell0V): return cell1[0], lpos1 else: return cell0[0], lpos0
def __init__(self, l, h, b1, b2, t1, t2, t3): self.outter = Polygon( *map(Point, ((0, 0), (b1, 0), (b1, t1), (b1 / 2 + t3 / 2, t1), (b1 / 2 + t3 / 2, h - t2), (b1 / 2 + b2 / 2, h - t2), (b1 / 2 + b2 / 2, h), (b1 / 2 - b2 / 2, h), (b1 / 2 - b2 / 2, h - t2), (b1 / 2 - t3 / 2, h - t2), (b1 / 2 - t3 / 2, t1), (0, t1)))) self.inner = None
def find_pixels_in_structure( array): #passed 1d array of coordinates on the form (x,y,z) points = array3D_to_points( array) # sorts array into a list of 2d points [(x0,y0), (x1,y1), ...] #creating polygon polyList = [] for i in range(len(points)): polyList.append(i) t = tuple(polyList) poly = Polygon(*t) #unpacking list elements to make a sequence of points DVH_points = [] #iterating through passed array and checking if points are insie polygon for i in range(len(array)): if (poly.encloses_point(array[i])): DVH_points.append(array[i]) return DVH_points #returning list of points that are inside the polygon
def pass_coordinates(list_coordinates): """ Returns a dictionary of polygons with the coordinates """ polygons = {} for key, value in list_coordinates.items(): polygons[key] = Polygon(*value) time_poly = time() print("Time of create the polygon: ", key, " : ", time_poly - start) return polygons
def compute_iou_using_sympy(gmap_a, gmap_b): gmap_a = [(x, y) for x, y in gmap_a.reshape(-1, 2)] gmap_b = [(x, y) for x, y in gmap_b.reshape(-1, 2)] poly_a = Polygon(*gmap_a) poly_b = Polygon(*gmap_b) #print([map(sympy.Float, p) for p in poly_a.vertices]) #print([map(sumpy.Float, p) for p in poly_b.vertices]) intersection_ = intersection(poly_a, poly_b) #print(intersection_) #print([tuple(p) for p in intersection_.vertices]) area_int = np.abs(np.float(intersection(poly_a, poly_b))) area_un = np.abs(np.float(poly_a.area)) + np.abs(np.float( poly_b.area)) + area_int + 10e-6 iou = area_int / area_un return iou
def coordinate_iwf(self, H, B, tw, tf): # Generate coordinate of points of IWF profile # But its still to slow using SymPy P = [(0, 0), (B, 0), (B, tf), (B / 2. + tw, tf), (B / 2. + tw, H - tf), (B, H - tf), (B, H), (0, H), (0, H - tf), (B / 2. - tw, H - tf), (B / 2. - tw, tf), (0, tf)] poly = Polygon(*P) x, y = poly.centroid.x, poly.centroid.y for i, e in enumerate(P): P[i] = (e[0] - x, e[1] - y) return P
def randomCheck(polygonJSONfn, pubFacilityJSONfn): from sympy import Polygon from sympy.geometry import Point import random totalMatch = 0 #read json file json_data = open(polygonJSONfn) data = json.load(json_data) json_data.close() CACoords = {} # for each features numOfFeatures = len(data['features']) #get a random number idx = random.randint(0, numOfFeatures-1) ca = data['features'][idx]['properties']['CACODE'] #print ca coords = data['features'][idx]['geometry']['coordinates'][0] #form polygon polygon = Polygon(*coords) pub_facility_json_data = open(pubFacilityJSONfn) pub_facility_data = json.load(pub_facility_json_data) pub_facility_json_data.close() numOfPubFacility = len(pub_facility_data['features']) print "Please wait for a while... It takes some time..." #for each public facility for i in range(numOfPubFacility): location = pub_facility_data['features'][i]['geometry']['coordinates'] point = Point(location) #check if it is in or out if polygon.encloses_point(point): print pub_facility_data['features'][i]['properties']['ENGLISH CATEGORY'], print pub_facility_data['features'][i]['properties']['ENGLISH NAME'] totalMatch = totalMatch + 1 print "Total number of public facility in ", ca, ":", totalMatch
def load(self, file_name): f = open(file_name, "r") polygons = [] for l in f: point_pairs = l.split(";") points = [] for p in point_pairs: p = p.split(",") points.append(Point(int(p[0]), int(p[1]))) polygons.append(Polygon(*points)) f.close() self.polygons = polygons
def get_polygon(left, right, top, bottom): # convert rays to lines left = Line(left.p1, left.p2) right = Line(right.p1, right.p2) top = Line(top.p1, top.p2) bottom = Line(bottom.p1, bottom.p2) top_left = left.intersection(top)[0] top_right = right.intersection(top)[0] bottom_left = left.intersection(bottom)[0] bottom_right = right.intersection(bottom)[0] return Polygon(top_left, top_right, bottom_right, bottom_left)
def poligon(sez): points = [] sez1 = sez[::-1] for tocka in naredi_points(sez1): #print ("Tocka: ", tocka) points.append(tocka) print(points) t = tuple(points) #print ("Points: ", points) p = Polygon(*t) #print ("Polygon: ", p) return p
def mergecell(cell0, cell1, index0, index1): vertice0 = cell0.vertices vertice1 = cell1.vertices if (index0 == 0): vertice = vertice0[0:len(vertice0) - 1] else: vertice = vertice0[index0:len(cell0.vertices)] + vertice0[0:index0 - 1] if (index1 == 0): vertice += vertice1[0:len(vertice1) - 1] else: vertice += vertice1[index1:len(cell1.vertices)] + vertice1[0:index1 - 1] return Polygon(*vertice)
def update_bound(current, other): if current.bound is None: return other.bound else: current_xmin, current_ymin, current_xmax, current_ymax = current.bound.bounds other_xmin, other_ymin, other_xmax, other_ymax = other.bound.bounds current_xmin = other_xmin if other_xmin < current_xmin else current_xmin current_ymin = other_ymin if other_ymin < current_ymin else current_ymin current_xmax = other_xmax if other_xmax > current_xmax else current_xmax current_ymax = other_ymax if other_ymax > current_ymax else current_ymax return Polygon((current_xmin, current_ymin), (current_xmax, current_ymin), (current_xmax, current_ymax), (current_xmin, current_ymax))
def is_i(g1, g2): """Judges if the two components could consist a character i""" if not (is_circle(g1) or is_circle(g2)): return False if is_circle(g1): poly = Polygon(*get_points_from_segment(g1)) lines = g2 else: poly = Polygon(*get_points_from_segment(g2)) lines = g1 centriod_of_poly = poly.centroid points = get_points_from_segment(lines) lines_with_centriod = [centriod_of_poly, points[0] ] + get_points_from_segment(lines) __is_straight = points_consist_straight_line(lines_with_centriod) if __is_straight: return True else: return False
def partitionCC(stats, aw): centroids = [] mapP = [] for pos in range(len(stats)): stat = stats[pos] l = stat[cv.CC_STAT_LEFT] t = stat[cv.CC_STAT_TOP] h = stat[cv.CC_STAT_HEIGHT] for i in range(1, int(math.ceil(stat[cv.CC_STAT_WIDTH] / aw)) + 1): end = i * aw if i * aw < stat[cv.CC_STAT_WIDTH] else stat[ cv.CC_STAT_WIDTH] polyCen = Polygon((l, t), (l + end, t), (l + end, t + h), (l, t + h)).centroid centroids.append((polyCen.x, polyCen.y)) mapP.append(pos) return centroids, mapP
def build_graph(self, obstacles: List[Obstacle]): graph = nx.Graph() polygons = [] visited_lines = [] for obst_coords in obstacles: poly = Polygon(*obst_coords) polygons.append(poly) coors_len = len(obst_coords) i = 0 while i < coors_len: c1 = obst_coords[i] try: c2 = obst_coords[i + 1] except IndexError: c2 = obst_coords[-1] if c1 != c2: visited_lines.append(Line(c1, c2)) graph.add_edge(c1, c2) i += 1 coordinates = [] # brute force the rest for obst_coords in obstacles: coordinates.extend(obst_coords) for coord1 in coordinates: for coord2 in coordinates: if coord1 == coord2: continue l = Line(coord1, coord2) if l in visited_lines: continue for poly in polygons: intersect = l.intersection(poly) if len(intersect) > 1: graph.add_edge()
def minuspolygon(polygon, obs, pt): verticesp = polygon.vertices sides = polygon.sides for side in sides: if (side.contains(Point(pt))): break indexp1 = findpoint(verticesp, side.p1) indexp2 = findpoint(verticesp, side.p2) if (indexp1 > indexp2): indexp = indexp1 else: indexp = indexp2 verticeso = obs.vertices verticeso.reverse() indexo = findpoint(verticeso, Point(pt)) verticesp[indexp:indexp] = iter(verticeso[0:indexo + 1]) verticesp[indexp:indexp] = iter(verticeso[indexo:len(verticeso)]) polygon = Polygon(*verticesp) return polygon