def update(self, agent_coor, goal): ind = random.randint(0, len(self.polygon_list) - 1) old_polygon = self.polygon_list[ind] count = 5 move_success = False while count > 0 and not move_success: print("Count", count) pol_move = random.choice(self.list_move) new_polygon = [] for point in old_polygon: point = np.array(point) + pol_move new_polygon.append(tuple(point)) print(new_polygon, old_polygon) new_polygon_obj = Polygon(new_polygon) agent_point = Point(agent_coor[1], agent_coor[0]) flag = True if new_polygon_obj.touches( agent_point) or new_polygon_obj.overlaps( agent_point) or new_polygon_obj.crosses(agent_point): count -= 1 flag = False else: for i, p in enumerate(self.polygon_objs): if i != ind and (new_polygon_obj.overlaps(p) or new_polygon_obj.touches(p) or new_polygon_obj.intersects(agent_point)): count -= 1 flag = False break if flag: move_success = True if not move_success: return self.__draw.polygon(old_polygon, outline=0) print(f"Polygon {ind} move {pol_move}") self.__draw.polygon(new_polygon, outline=ind + 1) self.polygon_list[ind] = new_polygon self.polygon_objs[ind] = new_polygon_obj
def checkIfFireInCountyByName(fires,counties,firename,countyname): fire = getfirewithname(fires,firename) if fire == None: print("ERROR: No such fire with name: " + firename) county = getcountywithname(counties,countyname) if county == None: print("ERROR: No such county with name: " + countyname) firePoints = np.array(fire[0]) countyPoints = np.array(county[0]) firePoly = Polygon(firePoints) countyPoly = Polygon(countyPoints) return countyPoly.overlaps(firePoly) or countyPoly.contains(firePoly) or firePoly.contains(countyPoly)
def get_overlap_cells(self, poly: geometry.Polygon) -> List[OccupancyCell]: """Determines which cells in the grid intersect the provided polygon. This will return no cells if the polygon is smaller then a single cell and contained within it.""" cells = [] for r in range(self.rows): for c in range(self.cols): cell = self.get_cell(r, c) if (poly.overlaps(cell.poly) or cell.poly.within(poly)): cells.append(cell) return cells
def _calculate_position_between_objects(self, boxA: BoundBox, boxB: BoundBox): polygon = Polygon(self.convert_top_bottom_to_polygon(boxA)) other_polygon = Polygon(self.convert_top_bottom_to_polygon(boxB)) vsName = boxA.label + ' vs ' + boxB.label positions = {vsName: {}} # positions[vsName] if polygon.crosses(other_polygon): positions[vsName]['crosses'] = polygon.crosses(other_polygon) if polygon.contains(other_polygon): positions[vsName]['contains'] = polygon.contains(other_polygon) if polygon.disjoint(other_polygon): positions[vsName]['disjoint'] = polygon.disjoint(other_polygon) if polygon.intersects(other_polygon): positions[vsName]['intersects'] = polygon.intersects(other_polygon) if polygon.overlaps(other_polygon): positions[vsName]['overlaps'] = polygon.overlaps(other_polygon) if polygon.touches(other_polygon): positions[vsName]['touches'] = polygon.touches(other_polygon) if polygon.within(other_polygon): positions[vsName]['within'] = polygon.within(other_polygon) return positions
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)
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)
def overlap_fraction(img, header, frame, verbose=True): """ Calculate the overlap between a given CFHT frame and a given image. Parameters: img (numpy 2-D array): image array. header: header of the image, typically ``astropy.io.fits.header`` object. frame: This is one row of ``mega_cat``, containing "position_bounds". verbose (bool): Whether print out intersection percentage. Return: percentage (float): The overlapping fraction (with respect to the input CFHT frame). """ # Frame is one row of mega_cat. from shapely.geometry import Polygon w = wcs.WCS(header) ra_bound = list(map(float, frame['position_bounds'].split(' ')[1:]))[0::2] dec_bound = list(map(float, frame['position_bounds'].split(' ')[1:]))[1::2] x_bound, y_bound = w.wcs_world2pix(ra_bound, dec_bound, 0) img_bound = Polygon(list(zip([0, img.shape[1], img.shape[1], 0], [0, 0, img.shape[0], img.shape[0]]))) frame_bound = Polygon(list(zip(x_bound, y_bound))) if frame_bound.contains(img_bound): if verbose: print('# The intersection accounts for 100 %') return 1 elif not frame_bound.overlaps(img_bound): print('# No Intersection!') return 0 else: intersect = frame_bound.intersection(img_bound) if verbose: print('# The intersection accounts for {} %'.format( round(intersect.area / img_bound.area * 100, 2))) percentage = intersect.area / img_bound.area return percentage
def collidesX(self, avatar, sprite, game): ATL, ATR, ABL, ABR = (avatar.rect.topleft, avatar.rect.topright, avatar.rect.bottomleft, avatar.rect.bottomright) STL, STR, SBL, SBR = (sprite.rect.topleft, sprite.rect.topright, sprite.rect.bottomleft, sprite.rect.bottomright) ATL = (ATL[0], -ATL[1]) ATR = (ATR[0], -ATR[1]) ABL = (ABL[0], -ABL[1]) ABR = (ABR[0], -ABR[1]) STL = (STL[0], -STL[1]) STR = (STR[0], -STR[1]) SBL = (SBL[0], -SBL[1]) SBR = (SBR[0], -SBR[1]) mod = game.width * game.block_size line1 = Polygon([(0, ATL[1]), (mod, ATL[1]), (0, ABL[1]), (mod, ABL[1])]) sprite = Polygon([STL, STR, SBL, SBR]) if (line1.overlaps(sprite)): return True return False
def checkIfFireInCounty(fire,county): firePoints = np.array(fire[0]) countyPoints = np.array(county[0]) firePoly = Polygon(firePoints) countyPoly = Polygon(countyPoints) return countyPoly.overlaps(firePoly) or countyPoly.contains(firePoly) or firePoly.contains(countyPoly)
def fld_demo1(image, regions, split_x): image_height, image_width = image.shape[:2] landscape = [] # 横向 longitudinal = [] # 纵向 class_above_edge = [ 'solve', 'solve0', 'attention', 'choice', 'cloze', 'composition', 'composition0', 'correction' ] for index, region_box in enumerate(regions): xmin = region_box['bounding_box']['xmin'] ymin = region_box['bounding_box']['ymin'] xmax = region_box['bounding_box']['xmax'] ymax = region_box['bounding_box']['ymax'] if region_box['class_name'] in class_above_edge: line1 = LineString([(xmin, ymin), (xmin, ymax)]) line2 = LineString([(xmax, ymin), (xmax, ymax)]) line3 = LineString([(xmin, ymin), (xmax, ymin)]) line4 = LineString([(xmin, ymax), (xmax, ymax)]) longitudinal.extend([line1, line2]) landscape.extend([line3, line4]) landscape = sorted(landscape, key=lambda k: k.bounds[0]) # 横向 longitudinal = sorted(longitudinal, key=lambda k: k.bounds[1]) # 纵向 img_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # ret, binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) fld = cv2.ximgproc.createFastLineDetector() dlines = fld.detect(img_gray) lines = [line[0] for line in dlines.tolist()] lines_arr = np.array(lines) width_ = lines_arr[:, 2] - lines_arr[:, 0] height_ = lines_arr[:, 3] - lines_arr[:, 1] lines_index1 = np.where(width_ > 50)[0] lines_index2 = np.where(height_ > 50)[0] lines_index = np.hstack([lines_index1, lines_index2]) new_lines = [lines[ele] for ele in lines_index] new_lines = clean_repeat_lines(new_lines) line_block = [] split_x.insert(0, 0) split_x.append(image_width) # line 分栏 for index, split in enumerate(split_x[1:]): left_boarder, right_boarder = split_x[index], split_x[index + 1] top_boarder, bottom_boarder = 1, image_height - 1 block_list = [] for line in new_lines: # if round(line[2]) < round(line[0]) and round(line[3]) > round(line[1]): # line_new = [line[0], line[1], line[0], line[3]] # elif round(line[2]) > round(line[0]) and round(line[3]) < round(line[1]): # line_new = [line[0], line[1], line[2], line[1]] # else: # line_new = line line_new = line line_tmp = LineString([(line_new[0], line_new[1]), (line_new[2], line_new[3])]) polygon_tmp = Polygon([(left_boarder, top_boarder), (right_boarder, top_boarder), (right_boarder, bottom_boarder), (left_boarder, bottom_boarder)]) decision = [ polygon_tmp.contains(line_tmp), polygon_tmp.within(line_tmp), polygon_tmp.overlaps(line_tmp) ] if True in decision: block_list.append(line_new) block_dict = {} block_dict['boarder'] = [ left_boarder, top_boarder, right_boarder, bottom_boarder ] block_dict['block_list'] = block_list line_block.append(block_dict) # print(line_block) # get intersect point # landscape, longitudinal是box的,不是直线检测得到的直线 landscape_points_list = get_intersection_points(landscape, longitudinal, image, line_block) print(landscape_points_list)
def writeTerrainMesh(objName, meshVerts, meshElevs, meshTris, bbox): # crop to bbox numTris = meshTris.shape[0] trisInside = [False for _ in range(numTris)] for ti in range(numTris): tri = meshTris[ti] triVerts = meshVerts[tri, :] poly = Polygon(triVerts) if poly.overlaps(bbox): xpoly = poly.intersection(bbox).exterior vertId = [-1 for _ in range(len(xpoly.coords) - 1)] for pi, p in enumerate(triVerts): v = Point(p) if bbox.contains(v): vertId[np.argmin([ v.distance(Point(x)) for x in xpoly.coords ])] = tri[pi] for pi in range(len(vertId)): if vertId[pi] < 0: vertId[pi] = len(meshVerts) meshVerts = np.vstack([ meshVerts, [xpoly.coords[pi][0], xpoly.coords[pi][1]] ]) meshElevs = np.hstack([meshElevs, np.array([0])]) meshTris[ti] = [vertId[0], vertId[1], vertId[2]] for vi in range(3, len(vertId)): meshTris = np.vstack( [meshTris, [vertId[0], vertId[vi - 1], vertId[vi]]]) else: trisInside[ti] = True # clean unused verts vertInMesh = np.full((meshVerts.shape[0], ), False) vertInMesh[meshTris.flatten()] = True vertNewIdx = np.cumsum(vertInMesh) # write obj fout = open(objName, 'w') fout.write('# obj file\n') for i, v in enumerate(meshVerts): if vertInMesh[i]: fout.write('v %.2f %.5f %.5f\n' % (np.clip(v[0], bbox.bounds[0], bbox.bounds[2]), np.clip(v[1], bbox.bounds[1], bbox.bounds[3]), 0.001 * meshElevs[i])) for i, tri in enumerate(meshTris): p0 = np.array([meshVerts[tri[0]][0], meshVerts[tri[0]][1], 0]) p1 = np.array([meshVerts[tri[1]][0], meshVerts[tri[1]][1], 0]) p2 = np.array([meshVerts[tri[2]][0], meshVerts[tri[2]][1], 0]) if np.cross(p1 - p0, p2 - p0)[2] > 0: fout.write( 'f %d %d %d\n' % (vertNewIdx[tri[0]], vertNewIdx[tri[1]], vertNewIdx[tri[2]])) else: fout.write( 'f %d %d %d\n' % (vertNewIdx[tri[2]], vertNewIdx[tri[1]], vertNewIdx[tri[0]])) fout.close()