def chunksToPolys(chunks):#this does more cleve chunks to Poly with hierarchies... ;) #print ('analyzing paths') #verts=[] #pverts=[] polys=[] for ch in chunks:#first convert chunk to poly if len(ch.points)>2: pchunk=[] for v in ch.points: pchunk.append((v[0],v[1])) ch.poly=Polygon.Polygon(pchunk) ch.poly.simplify() for ppart in chunks:#then add hierarchy relations for ptest in chunks: if ppart!=ptest and len(ptest.poly)>0 and len(ppart.poly)>0 and ptest.poly.nPoints(0)>0 and ppart.poly.nPoints(0)>0: if ptest.poly.isInside(ppart.poly[0][0][0],ppart.poly[0][0][1]): #hierarchy works like this: - children get milled first. #ptest.children.append(ppart) ppart.parents.append(ptest) for ch in chunks:#now make only simple polygons with holes, not more polys inside others #print(len(chunks[polyi].parents)) found=False if len(ch.parents)%2==1: for parent in ch.parents: if len(parent.parents)+1==len(ch.parents): ch.nparents=[parent]#nparents serves as temporary storage for parents, not to get mixed with the first parenting during the check found=True break if not found: ch.nparents=[] for ch in chunks:#then subtract the 1st level holes ch.parents=ch.nparents ch.nparents=None if len(ch.parents)>0: #print(len(ch.parents)) #ch.parents[0].poly=ch.parents[0].poly-ch.poly ch.parents[0].poly.addContour(ch.poly[0],1) returnpolys=[] for polyi in range(0,len(chunks)):#export only the booleaned polygons ch=chunks[polyi] if len(ch.parents)==0: ch.poly.simplify()#TODO:THIS CHECK returnpolys.append(ch.poly) #print(len(returnpolys)) return returnpolys
def plotPoly(self,c,string,w = 1): """ Plot polygons inside the boundary c = polygon to be plotted with matlabplot string = string that specify color w = width of the line plotting """ if bool(c): for i in range(len(c)): toPlot = Polygon.Polygon(c.contour(i)) & self.all if bool(toPlot): for j in range(len(toPlot)): BoundPolyPoints = asarray(PolyUtils.pointList(Polygon.Polygon(toPlot.contour(j)))) if self.operate_system == 2: self.ax.plot(BoundPolyPoints[:,0],BoundPolyPoints[:,1],string,linewidth=w) self.ax.plot([BoundPolyPoints[-1,0],BoundPolyPoints[0,0]],[BoundPolyPoints[-1,1],BoundPolyPoints[0,1]],string,linewidth=w) else: self.ax.plot(BoundPolyPoints[:,0],BoundPolyPoints[:,1],string,linewidth=w) self.ax.plot([BoundPolyPoints[-1,0],BoundPolyPoints[0,0]],[BoundPolyPoints[-1,1],BoundPolyPoints[0,1]],string,linewidth=w) self.setPlotLimitXYZ()
def generate_boundary(self): node_list = [] edge_list = [] for i in range(2): node_list.append(Node.Node(self.size[i], self.size[2])) node_list.append(Node.Node(self.size[i], self.size[3])) convexhull = Convex_hull(node_list) convexhull.run() for i in range(len(convexhull.hull) - 1): edge_list.append(Edge.Edge(convexhull.hull[i], convexhull.hull[i + 1])) self.boundary = Polygon.Polygon(edge_list)
def Circle(r,np): c=[] pi=math.pi v=mathutils.Vector((r,0,0)) e=mathutils.Euler((0,0,2.0*pi/np)) for a in range(0,np): c.append((v.x,v.y)) v.rotate(e) p=Polygon.Polygon(c) return p
def polygon(self): ccds = self.geometry p = None for ccd in ccds: vertices = ((ccd[0], ccd[1]), (ccd[0], ccd[3]), (ccd[2], ccd[3]), (ccd[2], ccd[1]), (ccd[0], ccd[1])) if p is None: p = Polygon.Polygon(vertices) else: p.addContour(vertices) return p
def tileBSPExample(): # read Polygon from file p = Polygon('testpoly.gpf') print "tileBSP() - may need some time...", # generate a list of tiles tiles = list(tileBSP(p)) # write results writeSVG('tileBSP.svg', tiles) if hasPDFExport: writePDF('tileBSP.pdf', tiles) print "done!"
def contours_to_poly(contours, hierarchy): def is_hole(idx): if hierarchy[idx][3] < 0: return False return not is_hole(hierarchy[idx][3]) p = Polygon.Polygon() hierarchy = hierarchy[0] for idx, c in enumerate(contours): p.addContour(c.reshape((c.shape[0], c.shape[2])), is_hole(idx)) return p
def generate_contours(self): allPoly = ps.open(self.shp_link) blobPoly = [None for i in range(len(np.unique(self.regions)))] for i in range(len(allPoly)): if (blobPoly[int(self.regions[i])] == None): blobPoly[int(self.regions[i])] = pl.Polygon( allPoly[i].vertices) else: blobPoly[int(self.regions[i])] = blobPoly[int( self.regions[i])] + pl.Polygon(allPoly[i].vertices) outputPoly = [] contours_to_blobs = [] counter = 0 for poly in blobPoly: for i in range(len(poly)): outputPoly.append(Polygon(poly.contour(i))) contours_to_blobs.append(counter) counter += 1 self.contours = outputPoly self.contours_to_blobs = contours_to_blobs
def tensor2poly(gt_polys: torch.Tensor): #(b,150,4,2) results = [] for array in gt_polys: image_polys = [] for points in array: if points[0, 0] != 0: poly_gon = plg.Polygon(points.cpu().numpy()) image_polys.append(poly_gon) results.append(image_polys) return results
def IndivToPolygon(indiv, PolyCut): N = indiv.size / 2 xc, yc = indiv.reshape((2, N)) xc, yc = indiv.reshape((2, N)) xy = np.zeros((xc.size, 2), np.float32) xy[:, 0] = xc xy[:, 1] = yc vor = Voronoi(xy) #incremental=True) LPolygon = [] regions, vertices = ModVoronoi.voronoi_finite_polygons_2d(vor) for iR, region in enumerate(regions): polygon = vertices[region] PP = (Polygon.Polygon(polygon) & Polygon.Polygon(PolyCut)) if PP.area() > 0: LPolygon.append(np.array(PP[0])) else: LPolygon.append(np.array(PP)) return LPolygon
def countryNameListOfBBox(self, bbox): nameList=list() bboxCPolygon=Polygon.Polygon([(bbox[0], bbox[3]), (bbox[2], bbox[3]), (bbox[2], bbox[1]), (bbox[0], bbox[1])]) for poly in self.polyData.values(): name=poly["name"] polygons=poly["coords"] for cPolygon in polygons: if cPolygon.overlaps(bboxCPolygon): nameList.append(name) return nameList
def make_polygon_obj(self): point_matrix = np.empty((4, 2), np.int32) point_matrix[0][0] = int(self.points[0]) point_matrix[0][1] = int(self.points[1]) point_matrix[1][0] = int(self.points[2]) point_matrix[1][1] = int(self.points[3]) point_matrix[2][0] = int(self.points[4]) point_matrix[2][1] = int(self.points[5]) point_matrix[3][0] = int(self.points[6]) point_matrix[3][1] = int(self.points[7]) return polygon3.Polygon(point_matrix)
def __make_poly(self, verts, indices, material): plane = self.plane_from_points(verts[indices[0], :], verts[indices[1], :], verts[indices[2], :]) polygon = Polygon.Polygon(plane, len(indices), material) pi = 0 for i in indices: xy, z = plane.project(verts[i, :]) polygon.set_vertex(pi, xy) pi += 1 self.add_poly(polygon) return polygon
def plg_nms_area(pred_boxes, sample_range=None): pred_boxes = overlap_coord_transfer(pred_boxes) boxes = [plg.Polygon(box.reshape((4,2))) for box in pred_boxes] overlaps = np.zeros((len(boxes), len(boxes)), dtype=np.float32) for k in range(len(boxes)): for n in range(k,len(boxes)): inter = boxes[k] & boxes[n] area_inter = inter.area() if len(inter)>0 else 0 overlaps[k,n] = area_inter / boxes[n].area() if boxes[n].area()>0 else 1 overlaps[n,k] = area_inter / boxes[k].area() if boxes[k].area()>0 else 1 return overlaps
def rectangle_to_polygon(rect): resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(rect.xmin) resBoxes[0, 4] = int(rect.ymax) resBoxes[0, 1] = int(rect.xmin) resBoxes[0, 5] = int(rect.ymin) resBoxes[0, 2] = int(rect.xmax) resBoxes[0, 6] = int(rect.ymin) resBoxes[0, 3] = int(rect.xmax) resBoxes[0, 7] = int(rect.ymax) pointMat = resBoxes[0].reshape([2, 4]).T return plg.Polygon(pointMat)
def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ num_points = len(points) # resBoxes=np.empty([1,num_points],dtype='int32') resBoxes = np.empty([1, num_points], dtype='float32') for inp in range(0, num_points, 2): resBoxes[0, inp // 2] = float(points[inp]) resBoxes[0, inp // 2 + num_points // 2] = float(points[inp + 1]) pointMat = resBoxes[0].reshape([2, num_points // 2]).T return plg.Polygon(pointMat)
def testDataStyle(self): p = Polygon.Polygon(self.cont) # tuple Polygon.setDataStyle(Polygon.STYLE_TUPLE) self.assertEqual(p[0], tuple(self.cont)) # list Polygon.setDataStyle(Polygon.STYLE_LIST) self.assertEqual(p[0], self.cont) if Polygon.withNumPy: import numpy Polygon.setDataStyle(Polygon.STYLE_NUMPY) self.assertEqual(type(p[0]), numpy.ndarray)
def createRegionPolygon(self, region, hole=None): """ This function takes in the region points and make it a Polygon. """ if hole == None: pointArray = [x for x in region.getPoints()] else: pointArray = [x for x in region.getPoints(hole_id=hole)] pointArray = map(self.coordmap_map2lab, pointArray) regionPoints = [(pt[0], pt[1]) for pt in pointArray] formedPolygon = Polygon.Polygon(regionPoints) return formedPolygon
def testCoverOverlap(self): p1 = Star(radius=1.0, beams=6) p2 = Polygon.Polygon(p1) p2.scale(0.9, 0.9) self.assertEqual(p1.covers(p2), 1) self.assertEqual(p1.overlaps(p2), 1) p2.shift(0.2, 0.2) self.assertEqual(p1.covers(p2), 0) self.assertEqual(p1.overlaps(p2), 1) p2.shift(5.0, 0.0) self.assertEqual(p1.covers(p2), 0) self.assertEqual(p1.overlaps(p2), 0)
def findRegionBetween(regionA, regionB,name = 'newRegion'): """ Find the region between two given regions (doesn't include the given regions) """ newRegion = Region() # the new region will have most features same as the old one newRegion.name = name newRegion.type = reg_POLY polyA = Polygon.Polygon([x for x in regionA.getPoints()]) polyB = Polygon.Polygon([x for x in regionB.getPoints()]) betw_AB = Polygon.Utils.convexHull(polyA+polyB)-polyA-polyB newRegion.pointArray = [Point(*x) for x in Polygon.Utils.pointList(betw_AB)] newRegion.alignmentPoints = [False] * len([x for x in newRegion.getPoints()]) newRegion.recalcBoundingBox() return newRegion
def __init__(self, proj, shared_data, robot_type): """ Rapidly-Exploring Random Trees alogorithm motion planning controller robot_type (int): Which robot is used for execution. Nao is 1, STAGE is 2,ODE is 3(default=3) """ # Get references to handlers we'll need to communicate with self.drive_handler = proj.h_instance['drive'] self.pose_handler = proj.h_instance['pose'] # Get information about regions self.proj = proj #self.proj.rfi = proj.rfi self.coordmap_map2lab = proj.coordmap_map2lab self.coordmap_lab2map = proj.coordmap_lab2map self.last_warning = 0 self.previous_next_reg = None # Store the Rapidly-Exploring Random Tress Built self.RRT_V = None # array containing all the points on the RRT Tree self.RRT_E = None # array specifying the connection of points on the Tree self.RRT_V_toPass = None self.RRT_E_toPass = None self.point_to_go = None self.heading = None self.E_prev = None self.Velocity = None self.currentRegionPoly = None self.nextRegionPoly = None self.map = {} self.all = Polygon.Polygon() # Information about the robot if robot_type not in [1, 2, 3]: robot_type = 1 self.system = robot_type ## 1: Nao ; 2: STAGE; 3: 0DE if self.system == 1: self.radius = 0.15 * 1.2 elif self.system == 2: self.radius = 0.1 elif self.system == 3: self.radius = 5 for region in self.proj.rfi.regions: self.map[region.name] = self.createRegionPolygon(region) for n in range(len(region.holeList)): # no of holes self.map[region.name] -= self.createRegionPolygon(region, n) for regionName, regionPoly in self.map.iteritems(): self.all += regionPoly
def cube(self, center, cube_dimension, material, add_to_scene=True): polygons = [] origin = np.asarray(center) plane = self.horizontal_plane(origin + [0, 0, cube_dimension / 2], True) polygons.append(Polygon.Polygon(plane, 4, material)) plane = self.horizontal_plane(origin - [0, 0, cube_dimension / 2], False) polygons.append(Polygon.Polygon(plane, 4, material)) plane = self.vertical_plane(origin + [0, cube_dimension / 2, 0], 0) polygons.append(Polygon.Polygon(plane, 4, material)) plane = self.vertical_plane(origin + [cube_dimension / 2, 0, 0], 90) polygons.append(Polygon.Polygon(plane, 4, material)) plane = self.vertical_plane(origin - [0, cube_dimension / 2, 0], 180) polygons.append(Polygon.Polygon(plane, 4, material)) plane = self.vertical_plane(origin - [cube_dimension / 2, 0, 0], 270) polygons.append(Polygon.Polygon(plane, 4, material)) for p in polygons: p.square(cube_dimension) if add_to_scene: self.add_poly(p) return polygons
def get_msra_result(pred_path_root,gt_path_root): th = 0.5 pred_list = file_util.read_dir(pred_path_root) count, tp, fp, tn, ta = 0, 0, 0, 0, 0 for pred_path in pred_list: count = count + 1 preds = get_pred(pred_path) gt_path = gt_path_root + pred_path.split('/')[-1].split('.')[0].split('res_')[-1] + '.gt' gts, tags = get_gt(gt_path) ta = ta + len(preds) for gt, tag in zip(gts, tags): gt = np.array(gt) gt = gt.reshape(int(gt.shape[0] / 2), 2) gt_p = plg.Polygon(gt) difficult = tag flag = 0 for pred in preds: pred = np.array(pred) pred = pred.reshape(int(pred.shape[0] / 2), 2) pred_p = plg.Polygon(pred) union = get_union(pred_p, gt_p) inter = get_intersection(pred_p, gt_p) iou = float(inter) / union if iou >= th: flag = 1 tp = tp + 1 break if flag == 0 and difficult == 0: fp = fp + 1 recall = float(tp) / (tp + fp) precision = float(tp) / ta hmean = 0 if (precision + recall) == 0 else 2.0 * precision * recall / (precision + recall) print('p: %.4f, r: %.4f, f: %.4f' % (precision, recall, hmean)) return hmean
def to_Polygons(self): import Polygon if (self.Polys != None): return self.Polys mymap = self.get_map() self.Polys = [] for p in self.polygons: xy = [mymap.to_xy(p.get_segment(i)) for i in range(len(p.X))] self.Polys.append(Polygon.Polygon(xy)) return self.Polys
def testDataStyle(self): p = Polygon.Polygon(self.cont) # tuple Polygon.setDataStyle(Polygon.STYLE_TUPLE) self.assertEqual(p[0], self.cont) # list Polygon.setDataStyle(Polygon.STYLE_LIST) self.assertEqual(p[0], list(self.cont)) if Polygon.withNumeric: # array import Numeric Polygon.setDataStyle(Polygon.STYLE_ARRAY) self.assertEqual(p[0], Numeric.array(self.cont))
def reduceExample(): # read Polygon from file p = Polygon('testpoly.gpf') # use ireland only, I know it's contour 0 pnew = Polygon(p[0]) # number of points l = len(pnew[0]) # get shift value to show many polygons in drawing bb = pnew.boundingBox() xs = 1.1 * (bb[1] - bb[0]) # list with polygons to plot plist = [pnew] while l > 30: # reduce points to the half l /= 2 print "Reducing contour to %d points" % l pnew = Polygon(reducePoints(pnew[0], l)) pnew.shift(xs, 0) plist.append(pnew) # draw the results print "Plotting ReduceExample.svg" drawSVG(plist, height=400, ofile="ReduceTest.svg")
def active_area_process(embryo_list, mode='pca'): active_area_list=[] for egg in embryo_list: poly = Polygon(egg) bd = Boundary(egg) bd.detect_head_tail(mode) poly.detect_area(boundary=bd) #poly.view_area() active_area_list.append(poly) return np.array(active_area_list)
def execute(self, context):#this is almost same as getobjectoutline, just without the need of operation data ob=bpy.context.active_object self.silh=utils.getObjectSilhouete('OBJECTS', objects=bpy.context.selected_objects) poly=Polygon.Polygon() for p in self.silh: for ci in range(0,len(p)): poly.addContour(p[ci]) bpy.context.scene.cursor_location=(0,0,0) polygon_utils_cam.polyToMesh(ob.name+'_silhouette',poly,0)# bpy.ops.object.convert(target='CURVE') bpy.context.scene.cursor_location=ob.location bpy.ops.object.origin_set(type='ORIGIN_CURSOR') return {'FINISHED'}
def clip_gshhs(path_init, x0, y0, x1, y1, pas_fin, resol, level): poly_init_file = path_init + resol + level + '.dat' print poly_init_file poly_init = Polygon(poly_init_file) x = x0 while x < x1: y = y0 while y < y1: xc = x * 1000000 yc = y * 1000000 pas1c = pas_fin * 1000000 path_fin = path_init + str(x) + '_' + str(y) + '_to_' + str( x + pas_fin) + '_' + str(y + pas_fin) + '/' if os.path.isdir(path_fin) == 0: os.mkdir(path_fin) poly_finish_file = path_fin + resol + level + '.dat' print poly_finish_file poly_clip = Polygon(((xc, yc), (xc + pas1c, yc), (xc + pas1c, yc + pas1c), (xc, yc + pas1c))) poly_finish = poly_init & poly_clip poly_finish.write(poly_finish_file) if pas_fin == 15: clip_gshhs(path_fin, x, y, x + pas_fin, y + pas_fin, 5, resol, level) if pas_fin == 5: clip_gshhs(path_fin, x, y, x + pas_fin, y + pas_fin, 1, resol, level) y = y + pas_fin x = x + pas_fin
def generate_kernels(self, img_size, text_polys, shrink_ratio, max_shrink=sys.maxsize, ignore_tags=None): """Generate text instance kernels for one shrink ratio. Args: img_size (tuple(int, int)): The image size of (height, width). text_polys (list[list[ndarray]]: The list of text polygons. shrink_ratio (float): The shrink ratio of kernel. Returns: text_kernel (ndarray): The text kernel mask of (height, width). """ assert isinstance(img_size, tuple) assert check_argument.is_2dlist(text_polys) assert isinstance(shrink_ratio, float) h, w = img_size text_kernel = np.zeros((h, w), dtype=np.float32) for text_ind, poly in enumerate(text_polys): instance = poly[0].reshape(-1, 2).astype(np.int32) area = plg.Polygon(instance).area() peri = cv2.arcLength(instance, True) distance = min( int(area * (1 - shrink_ratio * shrink_ratio) / (peri + 0.001) + 0.5), max_shrink) pco = pyclipper.PyclipperOffset() pco.AddPath(instance, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON) shrinked = np.array(pco.Execute(-distance)) # check shrinked == [] or empty ndarray if len(shrinked) == 0 or shrinked.size == 0: if ignore_tags is not None: ignore_tags[text_ind] = True continue try: shrinked = np.array(shrinked[0]).reshape(-1, 2) except Exception as e: print_log(f'{shrinked} with error {e}') if ignore_tags is not None: ignore_tags[text_ind] = True continue cv2.fillPoly(text_kernel, [shrinked.astype(np.int32)], text_ind + 1) return text_kernel, ignore_tags