class obstacle(object): #Initializes the polygon which represents the obstacle def __init__(self,points_): self.points = Polygon(points_) self.rawpoints=points_ #Checks to see if a given point is within an obstacle including if it is on the boundary #Returns true if the point is in the shape #Returns false if the point is not in the shape def checkInside(self,point): checkpoint=Point(point) flag=self.points.intersects(checkpoint) return flag #Checks to see if a line is within an obstacle, point 1 refers to current position and point 2 is where it wants to go #Returns true if the line passes through the shape #Returns false if the line does not pass through the shape def checkPassThrough(self,point1,point2): line = LineString([point1,point2]) flag=self.points.intersects(line) return flag #Print the max bounds and min bounds for x and y in that order def printBounds(self): print(self.points.bounds) #Returns the area contained within an obstacles def getArea(self): return self.points.area #Returns the points for the obstacle def printPoints(self): print(self.rawpoints) return
def get_trace(self, baseinfo_id, start_time=None, end_time=None, ring_str=None): result_data = {} result_data["line"] = [] result_data["point"] = {} polygon = None user_list = self.hotel_dao.get_hotel_trace_users(baseinfo_id) # 遍历用户名 for user in user_list: # 获取该用户的评论数据(评论对应的酒店名和地点) remarks = self.hotel_dao.get_remarks_by_username(user[0]) # 生成轨迹线 for i in range(0, len(remarks) - 1): if ring_str is not None: if polygon is None: ring = json.loads(ring_str) polygon = Polygon(ring) p1 = Point(remarks[i][14], remarks[i][15]) p2 = Point(remarks[i + 1][14], remarks[i + 1][15]) # 如果轨迹点不在这个区域内,则不存储 if not polygon.intersects(p1) or not polygon.intersects( p2): continue if remarks[i][15] != remarks[i + 1][15]: start_point = { "name": remarks[i][13], "geoCoord": [remarks[i][14], remarks[i][15]] } end_point = { "name": remarks[i + 1][13], "geoCoord": [remarks[i + 1][14], remarks[i + 1][15]] } result_data["line"].append([start_point, end_point]) # 生成轨迹点 for remark in remarks: if ring_str is not None: if polygon is None: ring = json.loads(ring_str) polygon = Polygon(ring) p = Point(remark[14], remark[15]) # 如果该点不在这个区域内,则不存储 if not polygon.intersects(p): continue coord_str = str(remark[15]) + "," + str(remark[14]) if coord_str not in result_data["point"]: result_data["point"][coord_str] = { "name": remark[13], "geoCoord": [remark[14], remark[15]], "value": 1 } else: result_data["point"][coord_str]["value"] += 1 return result_data
def create_statics(self, xbounds, ybounds, start, goal): self.statics = [] # iterate over desired number of obstacles for i in range(self.no_static_obs): # go until a valid obstacle is created while True: # generate random point in the workspace x_rand = random.uniform(xbounds[0], xbounds[1]) y_rand = random.uniform(ybounds[0], ybounds[1]) # choose a static size from the bounds provided x_size = random.uniform(self.static_obstacle_x_bounds[0], self.static_obstacle_x_bounds[1]) y_size = random.uniform(self.static_obstacle_y_bounds[0], self.static_obstacle_y_bounds[1]) # find the vertices (lower left, upper left, upper right, lower right) v1 = [x_rand - x_size / 2, y_rand - y_size / 2] v2 = [x_rand + x_size / 2, y_rand - y_size / 2] v3 = [x_rand + x_size / 2, y_rand + y_size / 2] v4 = [x_rand - x_size / 2, y_rand + y_size / 2] # create the shapely object static_obs = Polygon([v1, v2, v3, v4]) # check if goal in there if not static_obs.intersects( Point(start)) and not static_obs.intersects( Point(goal)): self.statics.append(static_obs) break return self.statics
def create_dynamics(self, xbounds, ybounds, start, goal): # same procedure as creating the static obstacle, just make sure it doesn't intersect an existing static self.dynamics = [] # iterate over desired number of obstacles for i in range(self.no_dynamic_obs): # go until a valid obstacle is created while True: # generate random point in the workspace x_rand = random.uniform(xbounds[0], xbounds[1]) y_rand = random.uniform(ybounds[0], ybounds[1]) # choose a static size from the bounds provided x_size = random.uniform(self.dyn_size_x[0], self.dyn_size_x[1]) y_size = random.uniform(self.dyn_size_y[0], self.dyn_size_y[1]) # find the vertices (lower left, upper left, upper right, lower right) v1 = [x_rand - x_size / 2, y_rand - y_size / 2] v2 = [x_rand + x_size / 2, y_rand - y_size / 2] v3 = [x_rand + x_size / 2, y_rand + y_size / 2] v4 = [x_rand - x_size / 2, y_rand + y_size / 2] # create the shapely object dynamic_obs = Polygon([v1, v2, v3, v4]) # check if the obstacle intersects goal if not dynamic_obs.intersects( Point(start)) and not dynamic_obs.intersects( Point(goal)): # append the dynamic obstacle to the list self.dynamics.append(dynamic_obs) break return self.dynamics
def random_environment(bounds, start, radius, goal, n, size_limits=(0.5, 1.5)): minx, miny, maxx, maxy = bounds # print(bounds) edges = 4 minl, maxl = size_limits env = Environment(None) obs = [] start_pose = Point(start).buffer(radius, resolution=3) obi = 0 while obi < n: r = np.random.uniform(low=0.0, high=1.0, size=2) xy = np.array( [minx + (maxx - minx) * r[0], miny + (maxy - miny) * r[1]]) angles = np.random.rand(edges) angles = angles * 2 * np.pi / np.sum(angles) for i in range(1, len(angles)): angles[i] = angles[i - 1] + angles[i] angles = 2 * np.pi * angles / angles[-1] angles = angles + 2 * np.pi * np.random.rand() lengths = 0.5 * minl + (maxl - minl) * 0.5 * np.random.rand(edges) xx = xy[0] + np.array([l * np.cos(a) for a, l in zip(angles, lengths)]) yy = xy[1] + np.array([l * np.sin(a) for a, l in zip(angles, lengths)]) p = Polygon([(x, y) for x, y in zip(xx, yy)]) if p.intersects(start_pose) or p.intersects(goal): continue else: obi = obi + 1 obs.append(p) # coords = xy + [l*np.cos(a),l*np.sin(a) for a,l in zip(angles,lengths)] env.add_obstacles(obs) return env
class Polygon(Geometry): """ class for convex polygon intersection test """ def __init__(self, vertices): """ constructor for polygon, vertices must be specified in counter-clockwise order """ # shapely should not be used if the students are implementing this self.poly = ShapelyPolygon(vertices) def intersects(self, geometry): if isinstance(geometry, Collection): return geometry.intersects(self) elif isinstance(geometry, Point): return self.point_poly_test(geometry) else: return self.poly_poly_test(geometry) def point_poly_test(self, p): """ This method should be implemented by the students but for demo purposes, shapely is used """ return self.poly.intersects(p.point) def poly_poly_test(self, p): """ This method should be implemented by the students but for demo purposes, shapely is used """ return self.poly.intersects(p.poly) @property def vertices(self): return list(self.poly.exterior.coords)
def module_overlaps_in_eta_phi(ref_mod_boundaries, tar_mod_boundaries, refphi=0, zshift=0, verbose=False): ref_center = np.array(ref_mod_boundaries).sum(0) / 4 tar_center = np.array(tar_mod_boundaries).sum(0) / 4 ref_center_phi = math.atan2(ref_center[2], ref_center[1]) tar_center_phi = math.atan2(tar_center[2], tar_center[1]) if abs(Phi_mpi_pi(ref_center_phi - tar_center_phi)) > math.pi / 2: return False # Turn it into eta phi ref_mod_boundaries = np.array([ get_etaphi([x[1], x[2], x[0] + zshift], refphi) for x in ref_mod_boundaries ]) tar_mod_boundaries = np.array([ get_etaphi([x[1], x[2], x[0] + zshift], refphi) for x in tar_mod_boundaries ]) # quick cut diff = ref_mod_boundaries[0] - tar_mod_boundaries[0] if abs(diff[0]) > 0.5: return False if abs(Phi_mpi_pi(diff[1])) > 1: return False p1 = Polygon(ref_mod_boundaries) p2 = Polygon(tar_mod_boundaries) if verbose: print(p1.intersects(p2)) return p1.intersects(p2)
def circGrid(spacing, length, center, boundary): # circle radius radius = spacing # end of radius radiusEnd = int(math.ceil(length / radius)) # width of sector in degrees sectorWidth = 4.0 polys = [] # array for storing features to plot for x in xrange(0, int(360.0 / sectorWidth)): for r in xrange(1, radiusEnd + 1): if r == 1: segmentVertices = [] # first point is center centerPoint = polarPoint(center, 0, 0) segmentVertices.append(centerPoint) # second point firstVertex = polarPoint(center, x * sectorWidth, r * radius) segmentVertices.append(firstVertex) # third point secondVertex = polarPoint(center, x * sectorWidth + sectorWidth, r * radius) segmentVertices.append(secondVertex) # center point ends polygon segmentVertices.append(centerPoint) oldVertices = segmentVertices # add to polys if in field boundary poly = Polygon(segmentVertices) if poly.intersects(boundary): polys.append(poly) else: newVertices = [] firstVertex = oldVertices[1] newVertices.append(firstVertex) secondVertex = polarPoint(center, x * sectorWidth, r * radius) newVertices.append(secondVertex) thirdVertex = polarPoint(center, x * sectorWidth + sectorWidth, r * radius) newVertices.append(thirdVertex) fourthVertex = oldVertices[2] newVertices.append(fourthVertex) # add to polys if in field boundary poly = Polygon(newVertices) if poly.intersects(boundary): polys.append(poly) oldVertices = newVertices return polys
def intersection(args): ''' Reads ply, applies boundingbox and writes matching polygon/cuboid ''' # ./ply-tool.py intersection test_data/house1.ply "POLYGON ((30 10, 80 80, 20 40, 0 10, 30 10))" bla2 print "Plyfile=", args.plyfile print "Boundingbox=", args.boundingbox print "Outfile=", args.outfile # Open outfile for appending outf = open(args.outfile, 'a') # Load WKT into shapely polygon bbox = Polygon(loads(args.boundingbox)) #print bbox #print bbox.area #print bbox.length # Reading the PLY file ply = PlyData.read(args.plyfile) # Loop through polygons poly_count = ply['polygon'].count for poly_i in range(0,poly_count): # List of vertice tuples vtcs = ply['vertex'][ply['polygon'][poly_i].tolist()].tolist() #print vtcs # into shapely Polygon poly = Polygon(vtcs) #print poly # Shapely intersects() does the job nicely print "Polygon", poly_i, "intersects=", bbox.intersects(poly) if bbox.intersects(poly): # to WKT polywkt = dumps(poly) + '\n' print "Adding to file", polywkt outf.write(polywkt) # Loop through cuboids cube_count = ply['cuboid'].count for cub_i in range(0,cube_count): # List of vertice tuples vtcs = ply['vertex'][ply['cuboid'][cub_i].tolist()].tolist() #print vtcs # into multipoint for now. should be polyhedron(?) I think but shapely doesn't have that mp = MultiPoint(vtcs) #print mp # Shapely intersects() does the job nicely print "Cuboid", cub_i, "intersects=", bbox.intersects(mp) if bbox.intersects(mp): # to WKT mpwkt = dumps(mp) + '\n' print "Adding to file", mpwkt outf.write(mpwkt) #write intermediary file outf.close()
def main(): assert args.dataname in ['Haywrd', 'ykdelB'] traindata = configs.dataconfig[args.dataname]['traindata'] testdata = configs.dataconfig[args.dataname]['testdata'] trainloader = loader.setup_testloader(traindata, args) testloader = loader.setup_testloader(testdata, args) ntrain = len(trainloader.dataset) ntest = len(testloader.dataset) traindata = trainloader.dataset testdata = testloader.dataset gtmat = np.zeros((ntest, ntrain), dtype=np.int_) for itest in range(200, ntest): # geo_itest = testloader.dataset.get_data(itest)['georeference'] geo_itest = testdata.get_georeference(itest) # Polygon([]) poly_itest = Polygon([(geo_itest['lowerleft'][0], geo_itest['lowerleft'][1]),\ (geo_itest['lowerright'][0], geo_itest['lowerright'][1]),\ (geo_itest['upperright'][0], geo_itest['upperright'][1]),\ (geo_itest['upperleft'][0], geo_itest['upperleft'][1])]) poly_itest_ = gpd.GeoSeries(poly_itest) for itrain in range(200, ntrain): # geo_itrain = trainloader.dataset.get_data(itrain)['georeference'] geo_itrain = traindata.get_georeference(itrain) poly_itrain = Polygon([(geo_itrain['lowerleft'][0], geo_itrain['lowerleft'][1]),\ (geo_itrain['lowerright'][0], geo_itrain['lowerright'][1]),\ (geo_itrain['upperright'][0], geo_itrain['upperright'][1]),\ (geo_itrain['upperleft'][0], geo_itrain['upperleft'][1])]) poly_itrain_ = gpd.GeoSeries(poly_itrain) if poly_itrain.intersects(poly_itest): # check another case print(poly_itest.intersects(poly_itrain), itest, itrain) print(utils.is_correct(geo_itest, geo_itrain)) if not utils.is_correct(geo_itest, geo_itrain): ax = poly_itest_.plot() poly_itrain_.plot(ax=ax, color='red') plt.show() img_itest = np.load( os.path.join(testdata.img_path, "%04d.npy" % (itest))) img_itest = Image.fromarray(img_itest) # img_itest.show() img_itrain = np.load( os.path.join(traindata.img_path, "%04d.npy" % (itrain))) img_itrain = Image.fromarray(img_itrain) aa = 1 a = utils.is_correct(geo_itest, geo_itrain) # img_itrain.show() gtmat[itest, itrain] = 1
def circGrid(spacing,length,center, boundary): # circle radius radius = spacing # end of radius radiusEnd = int(math.ceil(length/radius)) #width of sector in degrees sectorWidth = 4.0 polys = [] #array for storing features to plot for x in xrange(0,int(360.0/sectorWidth)): for r in xrange(1,radiusEnd + 1): if r==1: segmentVertices = [] #first point is center centerPoint = polarPoint(center, 0,0) segmentVertices.append(centerPoint) #second point firstVertex = polarPoint(center, x*sectorWidth,r * radius) segmentVertices.append(firstVertex) #third point secondVertex = polarPoint(center, x * sectorWidth+sectorWidth, r * radius) segmentVertices.append(secondVertex) #center point ends polygon segmentVertices.append(centerPoint) oldVertices = segmentVertices #add to polys if in field boundary poly = Polygon(segmentVertices) if poly.intersects(boundary): polys.append(poly) else: newVertices = [] firstVertex = oldVertices[1] newVertices.append(firstVertex) secondVertex = polarPoint(center, x*sectorWidth,r * radius) newVertices.append(secondVertex) thirdVertex = polarPoint(center, x * sectorWidth+sectorWidth, r * radius) newVertices.append(thirdVertex) fourthVertex = oldVertices[2] newVertices.append(fourthVertex) #add to polys if in field boundary poly = Polygon(newVertices) if poly.intersects(boundary): polys.append(poly) oldVertices = newVertices return polys
def polygon_to_multi_length_geohashes(self, polygon: Polygon, precision: int) -> tuple: """ 将目标几何图形切割成geohash,并输出包含与相交两个geohash字符串列表 Parameters ---------- polygon : shapely.geometry.Polygon 目标几何图形 precision : int, optional 所求geohash经度 Returns ---------- tuple 被目标几何图形包括的geohash字符串列表,与目标几何图形相交的geohash字符串列表 Examples ---------- >>> g = GeohashOperator() >>> p = Polygon([[116.40233516693117, 39.95442126877703], [116.40233516693117, 39.95744689749303], >>> [116.4070386902313, 39.95744689749303], [116.4070386902313, 39.95442126877703]]) >>> g.polygon_to_multi_length_geohashes(p, 7) ( {'wx4g2cd', 'wx4g2ce', 'wx4g2cf', 'wx4g2cg', 'wx4g2cs', 'wx4g2cu'}, {'wx4g2c3', 'wx4g2c6', 'wx4g2c7', 'wx4g2c9', 'wx4g2cc', 'wx4g2ck', 'wx4g2cm', 'wx4g2ct', 'wx4g2cv', 'wx4g2f1', 'wx4g2f4', 'wx4g2f5', 'wx4g2fh','wx4g2fj'} ) See Also ---------- geohash_to_polygon : 将Geohash字符串转成矩形 """ inner_geohashes = set() outer_geohashes = set() intersect_geohashes = set() testing_geohashes = queue.Queue() testing_geohashes.put(geohash.encode(polygon.exterior.xy[1][0], polygon.exterior.xy[0][0], precision)) while not testing_geohashes.empty(): current_geohash = testing_geohashes.get() if current_geohash not in inner_geohashes and current_geohash not in outer_geohashes: current_polygon = self.geohash_to_polygon(current_geohash) condition = polygon.intersects(current_polygon) if condition: if polygon.contains(current_polygon): inner_geohashes.add(current_geohash) elif polygon.intersects(current_polygon): intersect_geohashes.add(current_geohash) outer_geohashes.add(current_geohash) else: outer_geohashes.add(current_geohash) for neighbor in geohash.neighbors(current_geohash): if neighbor not in inner_geohashes and neighbor not in outer_geohashes: testing_geohashes.put(neighbor) return inner_geohashes, intersect_geohashes
def test_PolygonIntersectsPolygon(self): poly2 = Polygon(((0, 0), (0, 1), (1, 1), (0.5,0.5), (1, 0))) envelope=poly2.envelope bounds=envelope.bounds print bounds poly1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0))) isIntersects=poly1.intersects(poly2) print isIntersects poly1 = Polygon(((2, 2), (2,3), (3, 3), (3, 2))) isIntersects=poly1.intersects(poly2) print isIntersects
def get_trace(self, baseinfo_id, start_time=None, end_time=None, ring_str=None): result_data = {} result_data["line"] = [] result_data["point"] = {} polygon = None user_list = self.hotel_dao.get_hotel_trace_users(baseinfo_id) # 遍历用户名 for user in user_list: # 获取该用户的评论数据(评论对应的酒店名和地点) remarks = self.hotel_dao.get_remarks_by_username(user[0]) # 生成轨迹线 for i in range(0,len(remarks)-1): if ring_str is not None: if polygon is None: ring = json.loads(ring_str) polygon = Polygon(ring) p1 = Point(remarks[i][14],remarks[i][15]) p2 = Point(remarks[i+1][14],remarks[i+1][15]) # 如果轨迹点不在这个区域内,则不存储 if not polygon.intersects(p1) or not polygon.intersects(p2): continue if remarks[i][15] != remarks[i+1][15]: start_point = {"name":remarks[i][13],"geoCoord":[remarks[i][14],remarks[i][15]]} end_point = {"name":remarks[i+1][13],"geoCoord":[remarks[i+1][14],remarks[i+1][15]]} result_data["line"].append([start_point,end_point]) # 生成轨迹点 for remark in remarks: if ring_str is not None: if polygon is None: ring = json.loads(ring_str) polygon = Polygon(ring) p = Point(remark[14],remark[15]) # 如果该点不在这个区域内,则不存储 if not polygon.intersects(p): continue coord_str = str(remark[15])+","+str(remark[14]) if coord_str not in result_data["point"]: result_data["point"][coord_str] = { "name":remark[13], "geoCoord":[ remark[14], remark[15] ], "value":1 } else: result_data["point"][coord_str]["value"]+=1 return result_data
def evidence_to_grid(evidences, grid_map): """ Put polygon evidences in evidencegrid. :param evidences: :param grid_map: :return: """ evid_var = {} for e in evidences: if not e.variable_name in evid_var: evid_var[e.variable_name] = [] evid_var[e.variable_name].append(e) grid_vars = {} ## Evidences to Grid # For each variable for var_name, evids in evid_var.items(): # Create evidencegrid grid = copy.deepcopy(grid_map) grid_vars[var_name] = grid # for each cell in evidencegrid for i, j in zip(grid.n_rows, grid.n_columns): cell = Polygon(grid.cell_points(i, j)) # For each evidence for e in evids: boundary = Polygon(e.boundary) # If cell is in evidence boundary if not cell.intersects(boundary): continue if grid.get(i, j) is None: grid.set(i, j, [0, 0]) false_evidences, true_evidences = grid.get(i, j) # For each true state for st in e.get_detections(): polygon_state = Polygon(st) if polygon_state.intersects(cell): true_evidences += 1 false_evidences += 1 if true_evidences == 0 else 0 # Se the update evidences. grid.set(i, j, [false_evidences, true_evidences]) return grid_vars
class Track: def __init__(self, level: Level): self.__outside = Polygon(np.reshape(level.outer_track, (-1, 2))) self.__inside = Polygon(np.reshape(level.inner_track, (-1, 2))) all_obstacles = create_obstacles_collision_boxes(level.obstacles) self.__obstacles = list( filter( lambda obs: self.__outside.intersects(obs) and not self. __inside.covers(obs), all_obstacles)) def contains(self, geometry): return self.__outside.contains(geometry) and \ not self.__inside.intersects(geometry) and \ not any([obs.intersects(geometry) for obs in self.__obstacles])
def get_iou(gt, dr): # 对于p是针对预测结果而言的,对每一个预测结果在gt中寻找是否命中 p = np.zeros(len(dr)) for i, d1 in enumerate(dr): # 将预测结果数组信息进行一层float32格式的转换,并封装成多边形对象 dr_bbox = Polygon(get_box_coordinate(d1)) # 遍历 for j, d2 in enumerate(gt): # 获得gt多边形对象 gt_bbox = Polygon(get_box_coordinate(d2)) # 判断是否重合 if dr_bbox.intersects(gt_bbox): # 计算交集 intersection = dr_bbox.intersection(gt_bbox).area # 计算并集 union = dr_bbox.union(gt_bbox).area # 计算iou iou = intersection / union # 精度的iou阈值为0.5 if iou > 0.5: p[i] = 1 # 对于是针对gt而言的,对每一个gt在dr中寻找是否命中 r = np.zeros(len(gt)) for i, d1 in enumerate(gt): gt_bbox = Polygon(get_box_coordinate(d1)) for j, d2 in enumerate(dr): dr_bbox = Polygon(get_box_coordinate(d2)) if gt_bbox.intersects(dr_bbox): intersection = gt_bbox.intersection(dr_bbox).area union = gt_bbox.union(dr_bbox).area iou = intersection / union # 召回的iou阈值为0.7 if iou > 0.7: r[i] = 1 return p, r
def poly_outer_intersection(poly: Polygon, delete_polys: List[Polygon]) -> Polygon: """ Returns the polygon without the areas contained inside $delete_polys :param poly: The area polygon from which we remove areas :param delete_polys: The areas we want to remove :return: The "cut-out" polygon """ poly = copy.deepcopy(poly) for delete_poly in delete_polys: if poly.intersects(delete_poly): # If they intersect, create a new polygon that removes the area where they intersect poly = poly.difference(delete_poly.buffer(1e-5)) assert not poly.intersects(delete_poly), "shouldn't intersect" return poly
def is_player_alive(self, player): p = Polygon(player.get_polygon()) for c in self.static_spike_arr: s = Polygon(c) if p.intersects(s): player.is_alive = False for c in self.spike_arr: s = Polygon(c) if p.intersects(s): player.is_alive = False if not player.is_alive: self.draw_end_game_msg(player)
def _checkforOverlap(self, filterbbox, featurebbox): """ Uses Shapely Polygons to calculate bounding box intersections """ log.debug('comparing against %s' % str(filterbbox)) filterpolygon = Polygon( ((filterbbox[0], filterbbox[1]), (filterbbox[0], filterbbox[3]), (filterbbox[2], filterbbox[3]), (filterbbox[2], filterbbox[1]))) featurepolygon = Polygon( ((featurebbox[0], featurebbox[1]), (featurebbox[0], featurebbox[3]), (featurebbox[2], featurebbox[3]), (featurebbox[2], featurebbox[1]))) log.debug(dir(filterpolygon)) log.debug('intersect result%s' % featurepolygon.intersects(filterpolygon)) return filterpolygon.intersects(featurepolygon)
def parse_modis_coordinates(url_xml, coordinates, verbose): upperleft = (float(coordinates.split(',')[0]), float(coordinates.split(',')[1])) # lat, lon downright = (float(coordinates.split(',')[2]), float(coordinates.split(',')[3])) # lat, lon upperright = (upperleft[0], downright[1]) downleft = (downright[0], upperleft[1]) requested_bbox = Polygon((upperleft, upperright, downright, downleft)) if verbose: LOG.info("UL: LAT -> %s, LON -> %s" % upperleft) LOG.info("DR: LAT -> %s, LON -> %s" % downright) req = urllib2.Request("%s" % url_xml, None, HEADERS) print(url_xml) root = etree.parse(urllib2.urlopen(req)) bbox = [] for point in root.xpath('/GranuleMetaDataFile/GranuleURMetaData/SpatialDomainContainer/' 'HorizontalSpatialDomainContainer/GPolygon/Boundary/Point'): lon = point.xpath('./PointLongitude') lat = point.xpath('./PointLatitude') bbox.append((float(lat[0].text), float(lon[0].text))) product_bbox = MultiPoint(bbox).convex_hull if verbose: for point in bbox: (lat, lon) = point LOG.info("Point: LAT -> %s LON -> %s" % (lat, lon)) if requested_bbox.intersects(product_bbox): LOG.info("Compatible") return True else: LOG.info("Not Compatible") return False
def rbox_iou(a, b): b = angle2point(b) a = angle2point(a) poly1 = Polygon( a).convex_hull # python四边形对象,会自动计算四个点,最后四个点顺序为:左上 左下 右下 右上 左上 poly2 = Polygon(b).convex_hull union_poly = np.concatenate((a, b)) # 合并两个box坐标,变为8*2 if not poly1.intersects(poly2): # 如果两四边形不相交 iou = 0 else: try: inter_area = poly1.intersection(poly2).area # 相交面积 # print(inter_area) # union_area = poly1.area + poly2.area - inter_area union_area = MultiPoint(union_poly).convex_hull.area # print(union_area) if union_area == 0: iou = 0 # iou = float(inter_area) / (union_area-inter_area) #错了 iou = float(inter_area) / union_area # iou=float(inter_area) /(poly1.area+poly2.area-inter_area) # 源码中给出了两种IOU计算方式,第一种计算的是: 交集部分/包含两个四边形最小多边形的面积 # 第二种: 交集 / 并集(常见矩形框IOU计算方式) except shapely.geos.TopologicalError: print('shapely.geos.TopologicalError occured, iou set to 0') iou = 0 return iou
def pack_shape_scale_linear(self): center = self.random_point() base = self.base_shapes[0] ph = np.random.random() * 2 * np.pi R = np.matrix([[np.cos(ph), -np.sin(ph)], [np.sin(ph), np.cos(ph)]]) rbase = base * R # linear search on scale to find best fit r = 0 delta = 2 ** -4 while True: p = Polygon(r * rbase + center) intersected = False for shape in self.shapes: for poly in shape: if p.intersects(poly): intersected = True break if intersected: break # if any([p.intersects(poly) for poly in polys]): if intersected: break r += delta print(' %f' % r) self.shapes.append(p)
def rectangle_riou(pred_box, gt_box): """ 计算预测和gt的iou :param pred_box: list [x1, y1, x2, y2] :param gt_box: list [x1, y1, x2, y2] :return: """ def rectangle2polygon(box): return [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], [box[0], box[3]]] pred_polygon_points = np.array(rectangle2polygon(pred_box)).reshape(4, 2) pred_poly = Polygon(pred_polygon_points).convex_hull gt_polygon_points = np.array(rectangle2polygon(gt_box)).reshape(4, 2) gt_poly = Polygon(gt_polygon_points).convex_hull if not pred_poly.intersects(gt_poly): iou = 0 else: try: inter_area = pred_poly.intersection(gt_poly).area # union_area = gt_box.area union_area = gt_poly.area if union_area == 0: return 0 iou = float(inter_area) / union_area except shapely.geos.TopologicalError: print('shapely.geos.TopologicalError occured, iou set to 0') iou = 0 return iou
def crop_shapefile_to_raster(shapefile, raster): """ Intersects of a GeoDataFrame with a raster This creates the intersection between a Geopandas shapefile and a rasterio raster. It returns a new shapefile containing only the polygons resulting from this intersection. :param shapefile: reference GeoDataFrame :param raster: RasterIO raster object :return: a GeoDataFrame containing the intersected polygons """ xmin, ymin, xmax, ymax = raster.bounds xmin_s, ymin_s, xmax_s, ymax_s = shapefile.total_bounds bounds_shp = Polygon([(xmin_s, ymin_s), (xmin_s, ymax_s), (xmax_s, ymax_s), (xmax_s, ymin_s)]) bounds_raster = Polygon([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]) if bounds_shp.intersects(bounds_raster): # Compute the intersection of the bounds with the shapes shapefile['geometry'] = shapefile['geometry'].intersection( bounds_raster) # Filter empty shapes shapes_cropped = shapefile[shapefile.geometry.area > 0] return shapes_cropped else: return None
def generate_zones(poly_points, lon_unit, lat_unit, lons, lats): poly = Polygon(poly_points) zones = {} geo_json = {"type": "FeatureCollection", "features": []} for i, lon in enumerate(lons): for j, lat in enumerate(lats): leftBottom, rightBottom = (lon, lat), (lon + lon_unit, lat) rightTop, leftTop = (lon + lon_unit, lat + lat_unit), (lon, lat + lat_unit) polyPoints_gps = [leftBottom, rightBottom, rightTop, leftTop, leftBottom] cCoor_gps = (lon + lon_unit / 2.0, lat + lat_unit / 2.0) zone_poly = Polygon(polyPoints_gps) if poly.contains(zone_poly): boundary_relation = zone.IN elif poly.intersects(zone_poly): boundary_relation = zone.INTERSECT else: boundary_relation = zone.OUT zones[(i, j)] = zone(boundary_relation, i, j, cCoor_gps, polyPoints_gps) feature = {"type":"Feature", "id": '%d#%d' % (i,j), "properties": {"cCoor_gps": cCoor_gps}, "geometry": {"type": "Polygon", "coordinates": [[leftBottom, rightBottom, rightTop, leftTop, leftBottom ]] } } geo_json["features"].append(feature) return zones, geo_json
def polygonize_raster(mask, transforms, min_area=15): # write mask to polygon polygons = [] border = LineString([ Point(transforms * (0, 0)), Point(transforms * (0, mask.shape[1])), Point(transforms * (mask.shape[0], mask.shape[1])), Point(transforms * (mask.shape[0], 0)), Point(transforms * (0, 0)) ]) border = border.buffer(1) is_border = [] edges = cv2.findContours(image=mask, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)[0] for edge in edges: pol = Polygon([transforms * ele[0] for ele in edge]) if pol.area > min_area: polygons.append(pol) is_border.append(pol.intersects(border)) if len(polygons) > 0: return polygons, is_border else: return False, False
def get_IOU(self, coord1, coord2): line1 = coord1 #四边形四个点坐标的一维数组表示,[x,y,x,y....] a = np.array(line1).reshape(4, 2) #四边形二维坐标表示 poly1 = Polygon( a).convex_hull #python四边形对象,会自动计算四个点,最后四个点顺序为:左上 左下 右下 右上 左上 line2 = coord2 b = np.array(line2).reshape(4, 2) poly2 = Polygon(b).convex_hull union_poly = np.concatenate((a, b)) #合并两个box坐标,变为8*2 #print(union_poly) if not poly1.intersects(poly2): #如果两四边形不相交 iou = 0 else: try: inter_area = poly1.intersection(poly2).area #相交面积 union_area = MultiPoint(union_poly).convex_hull.area if union_area == 0: iou = 0 iou = float(inter_area) / union_area # 源码中给出了两种IOU计算方式,第一种计算的是: 交集部分/包含两个四边形最小多边形的面积 # 第二种: 交集 / 并集(常见矩形框IOU计算方式) except shapely.geos.TopologicalError: print('shapely.geos.TopologicalError occured, iou set to 0') iou = 0 return iou
def checkPosition(curr, qr_pos): position = Point(curr[0],curr[1]) qrBox = Polygon(qr_pos) if qrBox.intersects(position): return True else: return False
def detect_boxes(image, NETWORK, CLASS_NAMES, CLASS_COLORS, mask_polygon): list_bboxes, list_scores, list_labels = predict_yolov4( image, NETWORK, CLASS_NAMES, CLASS_COLORS) mask_polygon = Polygon(mask_polygon) new_list_bboxes = [] new_list_scores = [] new_list_labels = [] for bbox, score, label in zip(list_bboxes, list_scores, list_labels): x_min = bbox[0] y_min = bbox[1] x_max = bbox[2] y_max = bbox[3] p1 = (x_min, y_min) p2 = (x_max, y_min) p3 = (x_max, y_max) p4 = (x_min, y_max) bb = Polygon([p1, p2, p3, p4]) if mask_polygon.intersects(bb): new_list_bboxes.append(bbox) new_list_scores.append(score) new_list_labels.append(label) return new_list_bboxes, new_list_scores, new_list_labels
def checkTextBox(curr, text_w, text_h, qr_pos): textBox = Polygon([ tuple(curr), (curr[0] + text_w, curr[1]), (curr[0] + text_w, curr[1] + text_h), (curr[0], curr[1] + text_h) ]) qrBox = Polygon(qr_pos) return textBox.intersects(qrBox)
def get_random_instance(): n = np.random.randint(3, 30) p = generate_star_polygon(n, 1000, 0).astype(np.int) poly = Polygon(p) min_x, max_x = p[:, 0].min(), p[:, 0].max() min_y, max_y = p[:, 1].min(), p[:, 1].max() coords_x = np.arange(min_x, max_x + 1) coords_y = np.arange(min_y, max_y + 1) xx, yy = np.meshgrid(coords_x, coords_y) num_inside = sum(1 if poly.intersects(Point(x, y)) else 0 for x, y in zip(np.ravel(xx), np.ravel(yy))) #p_inside = np.array([[x, y] for x, y in zip(np.ravel(xx), np.ravel(yy)) if poly.intersects(Point(x, y))]) #p_outside = np.array([[x, y] for x, y in zip(np.ravel(xx), np.ravel(yy)) if not poly.intersects(Point(x, y))]) #num_inside = len(p_inside) #print(p) # plt.plot(list(p[:, 0]) + [p[0, 0]], list(p[:, 1]) + [p[0, 1]]) # plt.scatter(p_inside[:, 0], p_inside[:, 1]) # plt.scatter(p_outside[:, 0], p_outside[:, 1], c='red') # plt.scatter(list(p[:, 0]) + [p[0, 0]], list(p[:, 1]) + [p[0, 1]], c='black') # plt.suptitle(f"num_inside = {num_inside}") # plt.show() input_str = f"{n}\n" + '\n'.join(f"{x} {y}" for x, y in p) output_str = f"{num_inside}\n" return input_str, output_str
def is_pair(item_1, item_2): """ Determine if two Planet Items are a pair Valid pairs have equal satellite id's, equal strip id's, equal provider values, acquired times less than two seconds apart, and geometry polyons that intersect. Args: item_1 (dict): Planet API Item reference item_2 (dict): Planet API Item reference """ # Check item properties props_1 = item_1['properties'] props_2 = item_2['properties'] if (props_1['satellite_id'] != props_2['satellite_id'] or props_1['strip_id'] != props_2['strip_id']): return False # Check time difference t1 = dateutil.parser.parse(props_1['acquired']) t2 = dateutil.parser.parse(props_2['acquired']) t_diff = abs(t1 - t2).total_seconds() if t_diff > 2: return False # Check geometry intersection geom_1 = item_1['geometry'] geom_2 = item_2['geometry'] if (geom_1['type'] != 'Polygon' or geom_2['type'] != 'Polygon'): return False poly_1 = Polygon(geom_1['coordinates'][0]) poly_2 = Polygon(geom_2['coordinates'][0]) if poly_1.intersects(poly_2): return True
def bbox_iou_eval(box1, box2): ''' 利用python的库函数实现非矩形的IoU计算 :param box1: list,检测框的四个坐标[x1,y1,x2,y2,x3,y3,x4,y4] :param box2: lsit,检测框的四个坐标[x1,y1,x2,y2,x3,y3,x4,y4] :return: IoU ''' box1 = np.array(box1).reshape(4, 2) # 四边形二维坐标表示 # python四边形对象,会自动计算四个点,并将四个点重新排列成 # 左上,左下,右下,右上,左上(没错左上排了两遍) poly1 = Polygon(box1).convex_hull box2 = np.array(box2).reshape(4, 2) poly2 = Polygon(box2).convex_hull if not poly1.intersects(poly2): # 如果两四边形不相交 iou = 0 else: try: inter_area = poly1.intersection(poly2).area # 相交面积 iou = float(inter_area) / (poly1.area + poly2.area - inter_area) except shapely.geos.TopologicalError: print('shapely.geos.TopologicalError occured, iou set to 0') iou = 0 return iou
def get_intersection_over_union(pD, pG): a = np.array(pG).reshape(4, 2) # 四边形二维坐标表示 poly1 = Polygon( a).convex_hull # python四边形对象,会自动计算四个点,最后四个点顺序为:左上 左下 右下 右上 左上 b = np.array(pD).reshape(4, 2) poly2 = Polygon(b).convex_hull union_poly = np.concatenate((a, b)) #合并两个box坐标,变为8*2 #print(union_poly) #print(MultiPoint(union_poly).convex_hull) #包含两四边形最小的多边形点 # poly1 = polygon_from_points(pD) # poly2 = polygon_from_points(pG) if not poly1.intersects(poly2): #如果两四边形不相交 iou = 0 else: try: inter_area = poly1.intersection(poly2).area #相交面积 # print(inter_area) union_area = poly1.area + poly2.area - inter_area # union_area = MultiPoint(union_poly).convex_hull.area # print(union_area) if union_area == 0: iou = 0 iou = float(inter_area) / union_area # iou=float(inter_area) /(pD.area+pG.area-inter_area) # 源码中给出了两种IOU计算方式,第一种计算的是: 交集部分/包含两个四边形最小多边形的面积 # 第二种: 交集 / 并集(常见矩形框IOU计算方式) except shapely.geos.TopologicalError: print('shapely.geos.TopologicalError occured, iou set to 0') iou = 0 return iou
class Leaf(object): def __init__(self,**kwargs): """ """ self.angle = kwargs['angle'] self.ra= kwargs['a_mag'] self.rb= kwargs['b_mag'] self.x0 = kwargs['x0'] self.y0 = kwargs['y0'] self.Nb= kwargs['Nb'] self.surface = Polygon(ellipse(self.ra,self.rb,self.angle,self.x0,self.y0,Nb = 100)) self.sunlit_areas = [] def addSunlitArea(self,surface): self.sunlit_areas.append(surface) def getSunlitAreas(self): return self.sunlit_areas def getSunlitAreasAbove(self,area): return [a for a in self.sunlit_areas if area.light_strength < a.light_strength] def intersects(self,another_surface): return self.surface.intersects(another_surface) def getAbsorbedEnergy(self): energy = 0 for a in self.sunlit_areas: energy += a.polygon.area * a.light_strength * (1 - exp(LIGHT_DEC_FACTOR)) return energy
def distance_to_car(frame, top_left, bottom_right): distance = None # myRoi_array= np.array([[(0, 490), (309, 269), (490, 270), (800,473)]]) # process_img = region_of_interest(frame, myRoi_array) # cv2.imshow("precess_img", process_img) # roi = Polygon([(15, 472), (330, 321), (470, 321), (796, 495)]) roi = Polygon([(100, 470), (350, 280), (450, 280), (700, 470)]) car = box(top_left[0], top_left[1], bottom_right[0], bottom_right[1]) if roi.intersects(car): mid_x = (bottom_right[0] + top_left[0]) / 2 mid_y = (top_left[1] + bottom_right[1]) / 2 distance = round( (1 - ((bottom_right[0] / 800) - (top_left[0] / 800)))**4, 1) frame = cv2.putText(frame, '{}'.format(distance), (int(mid_x), int(mid_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) cv2.putText( frame[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]], 'WARNING!', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) return frame, distance
def cal_IoU(rect_real, rect_detect): a = np.array(rect_real).reshape(4, 2) # 四边形二维坐标表示 poly1 = Polygon( a).convex_hull # python四边形对象,会自动计算四个点,最后四个点顺序为:左上 左下 右下 右上 左上 b = np.array(rect_detect).reshape(4, 2) poly2 = Polygon(b).convex_hull union_poly = np.concatenate((a, b)) # 合并两个box坐标,变为8*2 # print(union_poly) if not poly1.intersects(poly2): # 如果两四边形不相交 return 0 else: try: inter_area = poly1.intersection(poly2).area # 相交面积 # print(inter_area) # union_area = poly1.area + poly2.area - inter_area # union_area = MultiPoint(union_poly).convex_hull.area union_area = poly1.area if union_area == 0: return 0 # iou = float(inter_area) / (union_area-inter_area) #错了 iou = float(inter_area) / union_area # iou=float(inter_area) /(poly1.area+poly2.area-inter_area) # 源码中给出了两种IOU计算方式,第一种计算的是: 交集部分/包含两个四边形最小多边形的面积 # 第二种: 交集 / 并集(常见矩形框IOU计算方式) return iou except shapely.geos.TopologicalError: print('shapely.geos.TopologicalError occured, iou set to 0') return 0
def get_reachable(self, coord, extra_coords): res = [] for c in [(node.x, node.y) for node in self.nodes] + extra_coords: if c == coord: continue dirvec = (c[0]-coord[0], c[1]-coord[1]) norm = (dirvec[0]**2 + dirvec[1]**2)**.5 scl = self.uav_radius / norm norvecs = [(v[0]*scl, v[1]*scl) for v in [(-dirvec[1], dirvec[0]), (dirvec[1], -dirvec[0])]] corners = [ (c[0]+norvecs[0][0], c[1]+norvecs[0][1]), (c[0]+norvecs[1][0], c[1]+norvecs[1][1]), (coord[0]+norvecs[0][0], coord[1]+norvecs[0][1]), (coord[0]+norvecs[1][0], coord[1]+norvecs[1][1]) ] path_poly = Polygon(corners) # ls = LineString([coord, c]) canReach = True for o in self.obstacles: # if ls.intersects(o): # canReach = False if path_poly.intersects(o): canReach = False #if not self.fly_zone.contains(ls): #canReach = False if canReach: res.append(c) return res
def GetLinesInRegion(self, region, lines): list = [] if len(region.coords) != 2: region = Polygon(region.coords) # convert for intersect to work for j in lines: if region.intersects(j): # shapely has lots of functions for this. list.append(j) # intersects() seemed to work best. return list
def isStateValid(state): #returns True if state is not in collision assert len(state) == 5 #cheaper to check velocity if np.linalg.norm(state[[0,1]]) > 2: return False ship_sprite.update_pose(state[2],state[3]) ship_poly = Polygon(ship_sprite.get_ship_path().vertices) return not ship_poly.intersects(obstacles_multipoly)
def test_measurement_boundary(self): # Calculated using /Users/jim/Dropbox/Documents/Msc/Thesis/A4/Experiments/sensor_boundry.py # base case (0,0,0) range = 1 self.sensor_properties.range = 1 self.sensor_properties.fov = pi/3. # Changed this to fit in with the self.sensor_properties.location.heading = 0 expected_results = Polygon([[0, 0], [1, -0.57735026918962562], [1, 0.57735026918962562]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0]))) expected_results = [[0.0, 0.0], [0.8650980420904953, -0.4994645874763656], [0.8650980420904953, -0.4994645874763656], [0.8650980420904955, 0.49946458747636563], [0.8819212643483519, 0.4713967368260034], [0.8819212643483553, -0.4713967368259972], [0.9238795325112841, 0.3826834323650961], [0.923879532511287, -0.3826834323650894], [0.9569403357322068, 0.29028467725446927], [0.9569403357322089, -0.2902846772544621], [0.980785280403229, 0.1950903220161357], [0.9807852804032304, -0.19509032201612808], [0.9951847266721962, 0.09801714032956847], [0.9951847266721969, -0.0980171403295605], [1.0, 0.0], [1.0, 8.238535137130597e-15]] self.assertItemsEqual(expected_results,sorted(self.sensor_properties.calculate_measurement_boundary()[0])) # Rotate Sensor by 90 degrees self.sensor_properties.location.heading = pi/2. expected_results = Polygon([[0, 0], [-0.57735026918962562, 1], [0.57735026918962562, 1]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0]))) # Rotate Sensor by -90 degrees self.sensor_properties.location.heading = -pi/2. expected_results = Polygon([[0, 0], [-0.57735026918962562, -1], [0.57735026918962562, -1]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0]))) # Rotate Sensor by -180 degrees self.sensor_properties.location.heading = -pi expected_results = Polygon([[0, 0], [-1, -0.57735026918962562], [-1, 0.57735026918962562]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0]))) # Move Base Co-ordinate -=-=-=-=-=--=-=-=-=-=--=-=-=-=-=--=-=-=-=-=--=-=-=-=-=--=-=-=-=-=--=-=-=-=-=- self.sensor_properties.location = Position(1,1,0) expected_results = Polygon([[1, 1], [2, 0.4226497308103744], [2, 1.57735026918962562]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0]))) # Move Base Co-ordinate 90 degress self.sensor_properties.location.heading = pi/2. expected_results = Polygon([[1, 1], [0.4226497308103744, 2], [1.57735026918962562, 2]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0]))) # Rotate Sensor by -90 degrees self.sensor_properties.location = Position(25,36,0) self.sensor_properties.location.heading = -pi/2. expected_results = Polygon([[25, 36], [24.422649730810374, 35], [25.57735026918962562, 35]]) self.assertTrue(expected_results.intersects(Polygon(self.sensor_properties.calculate_measurement_boundary()[0])))
def dohullsintersect(hull1_coord, hull2_coord): hull1 = [] hull2 = [] for coord in hull1_coord: hull1.append([coord[0], coord[1]]) for coord in hull2_coord: hull2.append([coord[0], coord[1]]) hull1 = Polygon(hull1) hull2 = Polygon(hull2) return hull1.intersects(hull2)
def in_box(self, status): """recreate twitter filter to check if a tweet is in the bounding box 1. See if coordinates in box 2. check if place polygon intersects box """ #try: if not self.location: return True # no bounding box => anything is valid locationbox = [(float(self.location[0]), float(self.location[1])), (float(self.location[0]), float(self.location[3])),\ (float(self.location[2]), float(self.location[1])), (float(self.location[2]), float(self.location[3]))] if status['coordinates']: c = status['coordinates'] if c['type'] == u'Point': coord = c['coordinates'] if coord[0] <= self.location[0] and coord[0] >= self.location[2]\ and coord[1] >= self.location[1] and coord[1] <= self.location[3]: return True else: return False elif c['type'] == u'Polygon': loc = Polygon([tuple(point) for point in c['coordinates']]) box = Polygon(locationbox) if loc.intersects(box): return True else: return False elif status['place']: if status['place']['bounding_box']['type'] == u'Point': coord = status['place']['bounding_box']['coordinates'] if coord[0] <= self.location[0] and coord[0] >= self.location[2]\ and coord[1] >= self.location[1] and coord[1] <= self.location[3]: return True else: return False elif status['place']['bounding_box']['type'] == u'Polygon': loc = Polygon([tuple(point) for point in status['place']['bounding_box']['coordinates']][0]) box = Polygon(locationbox) if loc.intersects(box): return True else: return False else: return False
def intersect_bpoly(footprint, bounding_polygon): """ """ footprint[1:, 0] += np.round((footprint[0, 0]-footprint[1:, 0])/360.)*360 bounding_lon = [point[0] for point in bounding_polygon] meanbplon = (min(bounding_lon) + max(bounding_lon)) / 2. meanfplon = (footprint[:, 0].min() + footprint[:, 0].max()) / 2. footprint[:, 0] += np.round((meanbplon - meanfplon) / 360.) * 360 bpoly = Polygon(bounding_polygon) footp = Polygon(footprint) return bpoly.intersects(footp)
def test_invalid_intersection(self): # Make a self-intersecting polygon polygon_invalid = Polygon(((0, 0), (1, 1), (1, -1), (0, 1), (0, 0))) self.assertFalse(polygon_invalid.is_valid) # Intersect with a valid polygon polygon = Polygon(((-.5, -.5), (-.5, .5), (.5, .5), (.5, -5))) self.assertTrue(polygon.is_valid) self.assertTrue(polygon_invalid.intersects(polygon)) self.assertRaises(TopologicalError, polygon_invalid.intersection, polygon) self.assertRaises(TopologicalError, polygon.intersection, polygon_invalid) return
def clip_route(raster, rte, resolution, bf_size=400.0): """ define a function to extract CDL info based on overlay of bird survey route list of function parameters: - raster: raster map image of CDL data (2D numpy array of float) - pts: coordinates of stops along a route - resolution: resolution of CDL raster image, unit: degree/pixel - dx: x reference of lower-left (SW) point on CDL raster map - dy: y reference of upper-right (NE) point on CDL raster map - bf_size: radius of buffer zone, unit: degree - box_size: size of a larger box in which buffer was defined, unit: pixel """ # create a (nType x nPoint) 2D array for crop counting at each stop # each row has nType elements, mapping to each LandType groups in CDL layer # it represents counts of each group within the buffer zone stat = np.zeros((len(LandType.cdl_group), len(rte.stops)), dtype=np.float) dc = int(floor(bf_size / resolution) + 2) half_res = resolution / 2.0 # loop through all stops to count crops inside a buffer around each point for n in range(len(rte.stops)): p = Point(rte.stops[n][0], rte.stops[n][1]) # read Point array b = p.buffer(bf_size) # create a buffer dx, dy = states_by_id[rte.stateID].coord xr, yr = (p.x - dx) % resolution, (dy - p.y) % resolution nx, ny = int((p.x-dx-xr) / resolution), int((dy-p.y-yr) / resolution) if xr > half_res: nx += 1 if yr > half_res: ny += 1 # loop through larger box drawn on CDL cdl layer, if a pixel falls # within the previously defined buffer, count the crop at this pixel for i in range(- dc, dc + 1): for j in range(- dc, dc + 1): cx, cy = nx + i, ny + j rx, ry = dx + cx * resolution, dy - cy * resolution cell = Polygon([(rx - half_res, ry - half_res), (rx - half_res, ry + half_res), (rx + half_res, ry + half_res), (rx + half_res, ry - half_res)]) if cell.intersects(b): intersect = b.intersection(cell) fraction = intersect.area / (resolution ** 2) stat[cdl_index[raster[cy, cx]].group, n] += fraction return stat
def get_tiles(ra=180.0,dec=40,width=(1.0,1.0),script_name=None,exptime=100,filter='g'): """ Get tile positions within a box. If script_name is provided, a corresponding observing script would be generated. ra: dec: box center width: box width script_name: name of the observing script output: return a list of 2-ele truple or list: [i,j] i is the TID? and j is the index """ tiles=fits.getdata(tilefile,1) nt=len(tiles) rat=np.hstack([tiles['DRA1'],tiles['DRA2'],tiles['DRA3']]) dect=np.hstack([tiles['DDEC1'],tiles['DDEC2'],tiles['DDEC3']]) idt=np.hstack([tiles['DID1'],tiles['DID2'],tiles['DID3']]) ntiles=len(idt) ratwd=1.08/np.cos(np.deg2rad(dect))/2 dectwd=1.03/2 rawd=width[0]/np.cos(np.deg2rad(dec))/2 decwd=width[1]/2 ps=Polygon([(ra-rawd,dec-decwd),(ra-rawd,dec+decwd), (ra+rawd,dec+decwd),(ra+rawd,dec-decwd)]) index=[] if script_name is not None: f=open(script_name,mode='w') for i in range(ntiles): ira=rat[i];idec=dect[i];w1=ratwd[i];w2=dectwd pc=Polygon([(ira-w1,idec-w2),(ira-w1,idec+w2), (ira+w1,idec+w2),(ira+w1,idec-w2)]) if ps.intersects(pc): if script_name is not None: c=SkyCoord(ira,idec,unit='deg') rastr=c.ra.to_string(sep="",precision=2,unit='hour',pad=True) decstr=c.dec.to_string(sep="",precision=1,unit='deg',pad=True,alwayssign=True) script='obs {0:6.1f} '.format(exptime)+' object '+idt[i]+' 1 '+filter+' '+rastr+' '+decstr+' 2000.0\n' f.write(script) index.append([i//nt+1,i%nt]) if script_name is not None: f.close() return index
def tfr_search(location, distance) : tfrs = tfr_loader(tfr_list_loader()) nearby_tfrs = [] user_rectangle = Polygon(user_rectangle_points(location, distance)) for tfr_id in tfrs : tfr = tfrs[tfr_id] zone_match = False for zone in tfr.zones : zone_shape = Polygon(zone.points) if user_rectangle.intersects(zone_shape) : zone_match = True if zone_match : nearby_tfrs.append(tfr) return nearby_tfrs
def polygons_intersect(poly1, poly2): """ Identify if two polygons intersect. If the polygons are invalid, convex hull for the set of points is used. :param poly1: set of points that form apolygon, :param poly2: set of points that form apolygon. :return: true if intersection """ pol1 = Polygon(poly1) if not pol1.is_valid: pol1 = MultiPoint(poly1).convex_hull pol2 = Polygon(poly2) if not pol2.is_valid: pol2 = MultiPoint(poly2).convex_hull return pol1.intersects(pol2)
def ways_overlap(a, b): """Determines if two Way objects represent overlapping polygons For example, if we have two overlapping ways: >>> from boundaries import Way, Node >>> w1 = Way('1', nodes=[Node('10', latitude=53, longitude=0), ... Node('11', latitude=53, longitude=4), ... Node('12', latitude=49, longitude=4), ... Node('13', latitude=49, longitude=0), ... Node('10', latitude=53, longitude=0)]) >>> w2 = Way('2', nodes=[Node('14', latitude=51, longitude=2), ... Node('15', latitude=51, longitude=6), ... Node('16', latitude=47, longitude=6), ... Node('17', latitude=47, longitude=2), ... Node('14', latitude=51, longitude=2)]) >>> ways_overlap(w1, w2) True Or a non-overlapping one: >>> w3 = Way('3', nodes=[Node('18', latitude=51, longitude=7), ... Node('19', latitude=51, longitude=11), ... Node('20', latitude=47, longitude=11), ... Node('21', latitude=47, longitude=7), ... Node('18', latitude=51, longitude=7)]) >>> ways_overlap(w1, w3) False Passing in a Way with too few points is an error: >>> w_open = Way('4', nodes=[Node('18', latitude=51, longitude=7), ... Node('19', latitude=51, longitude=11)]) >>> ways_overlap(w1, w_open) Traceback (most recent call last): ... ValueError: A LinearRing must have at least 3 coordinate tuples """ tuples_a = [(float(n.lon), float(n.lat)) for n in a] tuples_b = [(float(n.lon), float(n.lat)) for n in b] polygon_a = Polygon(tuples_a) polygon_b = Polygon(tuples_b) return polygon_a.intersects(polygon_b)
def write_josm_file(self, filename, tilezoom=14): """ create a osm file for the editor JOSM, that only contains the download boundary information. Load the file in JOSM and update the data. Note: Please do not missuse this function to download large areas with josm """ from shapely.geometry import LineString, Polygon f_out = open(filename,'w') f_out.write("<?xml version='1.0' encoding='UTF-8'?>\n") f_out.write("<osm version='0.6' upload='true' generator='JOSM'>\n") for i, op in enumerate(self.outer_polygons): # create coordinate list and then a polygon plist = [(node.lat, node.lon) for node in op] outer_polygon = Polygon(LineString(plist)) if not outer_polygon.is_valid: raise ValueError('outer polygon no %i is not valid' % (i+1)) (minlat, minlon, maxlat, maxlon) = outer_polygon.bounds (x1, y2) = deg2num(minlat, minlon, tilezoom) (x2, y1) = deg2num(maxlat, maxlon, tilezoom) for ty in range(y1, y2 + 1): for tx in range(x1, x2 + 1): tile_rectangle = [num2deg(tx, ty, tilezoom), num2deg(tx+1, ty, tilezoom), num2deg(tx+1, ty+1, tilezoom), num2deg(tx, ty+1, tilezoom), num2deg(tx, ty, tilezoom)] tile_polygon = Polygon(tile_rectangle) if outer_polygon.contains(tile_polygon) or outer_polygon.intersects(tile_polygon): minlat = tile_rectangle[3][0] minlon = tile_rectangle[3][1] maxlat = tile_rectangle[1][0] maxlon = tile_rectangle[1][1] f_out.write(' <bounds minlat="%.7f" minlon="%.7f" maxlat="%.7f" maxlon="%.7f" />\n' \ % (minlat-0.0000001, minlon-0.0000001, maxlat+0.0000001, maxlon+0.0000001)) f_out.write("</osm>\n") f_out.close
def generate_zones(poly_points, hl_unit, vl_unit, x_points, y_points): poly = Polygon(poly_points) zones = {} for i, x in enumerate(x_points): for j, y in enumerate(y_points): zone_poly = Polygon([[x, y], [x + hl_unit, y], [x + hl_unit, y + vl_unit], [x, y + vl_unit]] ) if poly.contains(zone_poly): relation = zone.IN elif poly.intersects(zone_poly): relation = zone.INTERSECT else: relation = zone.OUT zones[(i, j)] = zone(relation, i, j, x, y) return zones
def get_fracture_intersection_diff_w_segs(self, fracture, segs, face): (divided_polygons, full_frac_poly) = fracture.divide_polygon_for_intersection(segs) R = fracture.build_rotation_matrix() face_poly_list = [] for point_index in face: point = self.get_point(point_index) rot_point = np.linalg.solve(R, point - fracture.center) face_poly_list.append(rot_point[:2]) face_poly = Polygon(face_poly_list) if not face_poly.intersects(divided_polygons) or full_frac_poly.contains(face_poly): return (False, None, None) else: new_faces = [] for poly in divided_polygons: poly1 = poly.intersection(face_poly) poly1_ret = [] if not poly1.is_empty: for point in list(poly1.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly1_ret.append(rot_point) new_faces.append(poly1_ret) poly2 = face_poly.difference(full_frac_poly) poly2_ret = [] if type(poly2) == type(MultiPolygon()): for poly in poly2: poly2_ret.append([]) for point in list(poly.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly2_ret[-1].append(rot_point) else: poly2_ret.append([]) for point in list(poly2.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly2_ret[-1].append(rot_point) return (True, new_faces, poly2_ret)
def get_fracture_intersection_diff(self, fracture, face): R = fracture.build_rotation_matrix() fracture_poly_list = [] face_poly_list = [] for point in fracture.points: rot_point = np.linalg.solve(R, point - fracture.center) fracture_poly_list.append(rot_point[:2]) for point_index in face: point = self.get_point(point_index) rot_point = np.linalg.solve(R, point - fracture.center) face_poly_list.append(rot_point[:2]) face_poly = Polygon(face_poly_list) fracture_poly = Polygon(fracture_poly_list) if not face_poly.intersects(fracture_poly) or fracture_poly.contains(face_poly): return (False, None, None) else: poly1 = fracture_poly.intersection(face_poly) poly1_ret = [] for point in list(poly1.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly1_ret.append(rot_point) poly2 = face_poly.difference(fracture_poly) poly2_ret = [] if type(poly2) == type(MultiPolygon()): for poly in poly2: poly2_ret.append([]) for point in list(poly.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly2_ret[-1].append(rot_point) else: poly2_ret.append([]) for point in list(poly2.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly2_ret[-1].append(rot_point) return (True, [poly1_ret], poly2_ret)
def test_prepared_predicates(): # check prepared predicates give the same result as regular predicates polygon1 = Polygon([ (0, 0), (0, 1), (1, 1), (1, 0), (0, 0) ]) polygon2 = Polygon([ (0.5, 0.5), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5) ]) point2 = Point(0.5, 0.5) polygon_empty = Polygon() prepared_polygon1 = PreparedGeometry(polygon1) for geom2 in (polygon2, point2, polygon_empty): assert polygon1.disjoint(geom2) == prepared_polygon1.disjoint(geom2) assert polygon1.touches(geom2) == prepared_polygon1.touches(geom2) assert polygon1.intersects(geom2) == prepared_polygon1.intersects(geom2) assert polygon1.crosses(geom2) == prepared_polygon1.crosses(geom2) assert polygon1.within(geom2) == prepared_polygon1.within(geom2) assert polygon1.contains(geom2) == prepared_polygon1.contains(geom2) assert polygon1.overlaps(geom2) == prepared_polygon1.overlaps(geom2)
class node(): def __init__(self,dx,dy,xyverts,top,bot): self.dx = float(dx) self.dy = float(dy) self.dz = float(np.abs(top-bot)) self.xy = Polygon(xyverts) self.top = float(top) self.bot = float(bot) def intersects(self,other): #--if other node instance intersects in xy plane and is in the range of [top,bot] if self.xy.intersects(other.xy) and self.zrange(other): return True return False def zrange(self,other): if other.top <= self.top and other.top >= self.bot: return True elif other.bot <= self.top and other.bot >= self.bot: return True else: return False def z_overlap(self,other): zo = min(self.top,other.top) - max(self.bot,other.bot) return zo def intersection(self,other): #--calc the fractional volumne of over lap between the self and other node instance xy = self.xy.intersection(other.xy) dx = np.abs(xy.bounds[0] - xy.bounds[2]) dy = np.abs(xy.bounds[1] - xy.bounds[3]) dz = self.z_overlap(other) return (xy.area * dz) / self.volume @property def volume(self): return self.xy.area * self.dz
def find_overlapping(self, mosaic_name, selector): """Returns a list of mosaic names (``_id``) for mosaics overlapping the principal mosaic, and the fractional area of the overlap compared to the area of the principal footprint. Parameters ---------- mosaic_name : str `_id` of the mosaic to test other mosaics against. selector : dict query document to select mosaics to test overlaps with. Returns ------- overlaps : list Sequence of `(_id, overlap fraction)` tuples. """ main_doc = self.find({"_id": mosaic_name}, one=True) verts = np.array(main_doc['footprint.radec_poly']) ra0, dec0 = np.mean(verts, axis=0) xi, eta = eq_to_tan(verts[:, 0], verts[:, 1], ra0, dec0) main_poly = Polygon(zip(xi, eta)) # need to implement an RA, Dec centroid and perform spatial # queries against those as a first pass overlaps = [] for doc in self.find(selector): field_verts = np.array(doc['footprint.radec_poly']) xi, eta = eq_to_tan(field_verts[:, 0], field_verts[:, 1], ra0, dec0) poly = Polygon(zip(xi, eta)) if main_poly.intersects(poly): iter_area = main_poly.intersection(poly).area frac_overlap = iter_area / main_poly.area overlaps.append((doc['_id'], frac_overlap)) return overlaps
def test_HasWGS84PointGeom(self): """ Test to ensure that every Postgres feature has a point geometry within a WGS84 BBOX. """ world_bbox = Polygon([(-180, 90), (180, 90), (180, -90), (-180, -90)]) features_no_points = [] for record in self.test_data: # Iterate through a feature's geometries, check for point attr, # then check for population of point attr has_valid_point = False if 'geometry' in record.keys(): for geom in record['geometry']['geometries']: if geom['type'] == 'Point': # Check point is within WGS84 BBOX shapely_pt = shape(geom) if world_bbox.intersects(shapely_pt): has_valid_point = True # if we have no point or an invalid point, flag it. if not has_valid_point: composite_key = self._get_comp_primary_key(record) features_no_points.append(composite_key) # Raise error if we don't have an empty error list self.assertEqual(len(features_no_points), 0, msg="The following features have invalid point geometries %s" % features_no_points)