当前位置: 首页>>代码示例>>Python>>正文


Python Polygon.union方法代码示例

本文整理汇总了Python中shapely.geometry.Polygon.union方法的典型用法代码示例。如果您正苦于以下问题:Python Polygon.union方法的具体用法?Python Polygon.union怎么用?Python Polygon.union使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shapely.geometry.Polygon的用法示例。


在下文中一共展示了Polygon.union方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PolygonJoiner

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
class PolygonJoiner(object):
    def __init__(self, robot_name, data_polygons):
        self.robot_name = robot_name
        self.open_area = Polygon()
        self.full_area = Polygon()


        for id_robot, pol_data in data_polygons.items():
            # pol_data = [polygon, closed, time]

            try:
                available = not pol_data[1]
                pol = Polygon(pol_data[0])

                # Invalid polygons cannot be join.
                if not pol.is_valid:
                    pol = MultiPoint(pol_data[0]).convex_hull

                if available or robot_name == id_robot:

                    self.open_area = self.open_area.union(pol)
                else:
                    self.full_area = self.full_area.union(pol)

            except Exception:
                print "Error Joining polygons", SystemError.message

    def point_in_open_anomaly(self, point):
        p = Point(point)
        return p.within(self.open_area)
        pass

    def point_in_full_anomaly(self, point):
        p = Point(point)
        return p.within(self.full_area)
开发者ID:dsaldana,项目名称:roomba_sensor_network,代码行数:37,代码来源:polygon_joiner.py

示例2: main

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def main():
	results = open('results.txt','w')
	parser = argparse.ArgumentParser(description='Runs text detector on relevant images at window level')
	parser.add_argument('classifier_file', help='Path to classifier CLF')
	parser.add_argument('-l', '--limit', type=int, metavar='COUNT', required=False, help='Maximum number of images to use')
	parser.add_argument('-r', '--random', action="store_true", default=False, required=False, help='Fetch images ordered randomly if limit is active')
	args = parser.parse_args()
	parameters["classifier_file"] = args.classifier_file
	parameters["evaluate_windows"] = True
	i = rigor.runner.Runner('text', parameters, limit=args.limit, random=args.random)
	results.write("threshold\timageid\texpected\tdetected\n")
	for cascade_threshold in (.5,):
		parameters['cascade_threshold'] = cascade_threshold
		for result in i.run():
			image_id = result[0]
			detected = result[1]
			undetected = result[2]
			expected_blob = Polygon()
			for expected in result[3]:
				expected_blob = expected_blob.union(Polygon(expected))
			for dbox in detected:
				box = Polygon(dbox)
				intersection = expected_blob.intersection(box)
				if intersection and (intersection.area / box.area) > parameters["minimum_percent_overlap"]:
					results.write("{}\t{}\t1\t1\t\n".format(cascade_threshold,image_id))
				else:
					results.write("{}\t{}\t1\t0\t\n".format(cascade_threshold,image_id))
			for dbox in undetected:
				box = Polygon(dbox)
				intersection = expected_blob.intersection(box)
				if intersection and (intersection.area / box.area) > parameters["minimum_percent_overlap"]:
					results.write("{}\t{}\t0\t1\t\n".format(cascade_threshold,image_id))
				else:
					results.write("{}\t{}\t0\t0\t\n".format(cascade_threshold,image_id))
开发者ID:blindsightcorp,项目名称:rigor,代码行数:36,代码来源:text-windows-roc.py

示例3: calculate_errors

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def calculate_errors(image,path,groups,groups_edges, err_name):
	df = pd.DataFrame(columns=["image","path","radius",err_name])

	for grp in groups.keys():
		#edges
		if grp not in groups_edges.keys():
			edge_err = 1.0

		else:
			a = Polygon(groups_edges[grp])
			b = Polygon(groups[grp])

			if not (a.is_valid and b.is_valid):
				edge_err = 1.0

			else:

				Adiff1 = a.difference(b).area
				Adiff2 = b.difference(a).area
				Adiff = Adiff1+Adiff2
				Aunion = a.union(b).area
				edge_err = Adiff/Aunion

		b = Polygon(groups[grp])

		df = df.append({
			"image": image,
			"path": path,
			"group":grp,
			"radius": sqrt(b.area/pi),
			err_name: edge_err
			}, ignore_index=True)

	return df
开发者ID:gmaher,项目名称:tcl_code,代码行数:36,代码来源:groups_toCSV.py

示例4: tri_generator

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def tri_generator(n):
    a = random2d()
    b = random2d()
    c = random2d()
    tlist = [(0, 1, 2)]
    plist = [a, b, c]
    trisequence = Polygon(plist)
    id = [1, 2]
    pcount = 2
    
    #initialization of the greedy path
    enterance = a[:]
    enterance , dis = seg_p_dis(enterance, b, c)
    greedy = dis
    elist = [enterance]
    #start routing
    for i in range(n-1):
        pcount = pcount + 1
        new = point_generator(trisequence, plist[id[0]], plist[id[1]])
        tri = Polygon([plist[id[0]], plist[id[1]], new])
        trisequence = trisequence.union(tri)
        tlist.append((id[0],id[1],pcount))
        plist.append(new)        
        id[randint(0,1)] = pcount
        if i< n-2 :
            enterance, dis = seg_p_dis(enterance, plist[id[0]], plist[id[1]])
            elist.append(enterance)
        else:
            dis = sum([(enterance[i]-new[i])**2 for i in range(2)])**.5
            elist.append(new)
        greedy = greedy + dis
    return plist, tlist, elist, greedy 
开发者ID:glimmercn,项目名称:Online-Routing,代码行数:34,代码来源:main.py

示例5: __init__

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
class CircularAdapter:
    def __init__(self, rotation, size, radius):
        self._rotation = rotation
        self._size = size
        self._radius = radius

        points = [(0, 0)]
        count = max(2, math.ceil(self._size * 16 / 360))
        angle = math.radians(self._rotation - self._size/2)
        size = math.radians(self._size)
        for i in range(count+1):
            x = math.cos(angle + i/count * size) * self._radius
            y = math.sin(angle + i/count * size) * self._radius
            points.append((x, y))

        self._shape = Polygon(points)

    @property
    def area(self):
        return self._shape.area

    def intersection(self, other):
        result = self._shape.intersection(other._shape)
        return CircularWrapper(result)

    def union(self, other):
        result = self._shape.union(other._shape)
        return CircularWrapper(result)

    def distance(self, other):
        dist_a = (self._rotation - other._rotation) % 360
        dist_b = (other._rotation - self._rotation) % 360
        dist = min(dist_a, dist_b) - (self._size + other._size) / 2
        return max(0, dist)
开发者ID:alepulver,项目名称:my-thesis,代码行数:36,代码来源:cottle.py

示例6: nms_discard

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
 def nms_discard(self, proposal, accepted_detections, dataframe):
 
   p_idx = proposal[0]
   p_label = proposal[1].index[0]
   p_xmin = dataframe.iloc[p_idx]['xmin']
   p_xmax = dataframe.iloc[p_idx]['xmax']
   p_ymin = dataframe.iloc[p_idx]['ymin']
   p_ymax = dataframe.iloc[p_idx]['ymax']
   p_poly = Polygon([(p_xmin,p_ymin), (p_xmax,p_ymin), (p_xmax,p_ymax), (p_xmin, p_ymax)])
 
   for detection in accepted_detections:
     detection = accepted_detections[detection]
     d_idx = detection[0]
     d_label = detection[1].index[0]
     if d_label != p_label:
       # No point checking if it isn't the same class of object
       continue
     else:
       d_xmin = dataframe.iloc[d_idx]['xmin']
       d_xmax = dataframe.iloc[d_idx]['xmax']
       d_ymin = dataframe.iloc[d_idx]['ymin']
       d_ymax = dataframe.iloc[d_idx]['ymax']
       d_poly = Polygon([(d_xmin,d_ymin), (d_xmax,d_ymin), (d_xmax,d_ymax), (d_xmin, d_ymax)])
  
       intersection = p_poly.intersection(d_poly)
       union = p_poly.union(d_poly)
       if intersection.area / union.area > 0.3:
         return True
         break
 
   return False
开发者ID:elliottd,项目名称:vdrparser,代码行数:33,代码来源:RCNNObjectExtractor.py

示例7: create_polygon

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
    def create_polygon(self):
        center = (self.x, self.y)
        polygon_vertex = [(self.x, self.y)]
        step = float(self.cell.bw)/self.poly_lines
        self.geo_polygon.append((self.cell.lat, self.cell.long))
        for i in range(self.poly_lines + 1):
            angle_from_x = ( (self.edgeR - step*i)) % 360
            angle_from_y = (90 - self.edgeR - step*i) % 360
            yrad = math.radians(angle_from_y)
            xrad = math.radians(angle_from_x)
            polygon_vertex.append(((self.x + math.cos(xrad) * self.cell.radius),
                                      (self.y + math.sin(xrad) * self.cell.radius)))
            origin = geopy.Point(self.cell.lat, self.cell.long)
            dest = VincentyDistance(kilometers=self.cell.radius).destination(origin, angle_from_x)
            self.geo_polygon.append((dest.latitude, dest.longitude))
        #self.geo_polygon.append((self.cell.lat, self.cell.long))
        #for lat,long in self.geo_polygon:
        #    print lat, long
        #    print "Latitude"    

        polygon1 = Polygon(polygon_vertex)
        self.polygon = polygon1
        for delta in (0, 0.01, -0.01):
            self.polygon = polygon1.union(Point(center).buffer(0.6 + delta))
            if self.polygon.is_valid:
                break;
开发者ID:madhurrajn,项目名称:blueEye,代码行数:28,代码来源:core.py

示例8: ins_loc

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def ins_loc(data=None,return_obj=False,area_type='area'):
    #if area_type not in times: times[area_type]=0
    #times[area_type]+=1
    #logline='inserting %s, data %s - return obj = %s, time %d'%(area_type,data,return_obj,times[area_type])
    #log.debug(logline)
    #if times[area_type]>1: raise Exception(logline)

    if not data:
        coords = parse_polydata(request.params.get('coords'))
    else:
        coords = parse_polydata(data)

    #make sure that poly is valid - 
    if area_type=='area':
        from shapely.geometry import Polygon
        poly = Polygon([(float(p[0]),float(p[1])) for p in coords])
        poly.centroid
        poly.area
        poly.union(Polygon([(5,5),(5.5,5),(5.5,6)]))
        if len(coords)==4 and coords[1]==coords[2] and coords[0]==coords[3]:
            from shapely.geos import TopologicalError
            raise TopologicalError('its not a polygon but a line!')
        #raise Exception('area %s, centroid %s'%(poly.area,poly.centroid))
    
    a = Area()
    if not c.user_id: raise Exception('no user in ins_loc!')
    a.user_id = c.user_id
    a.area_type=unicode(area_type)
    meta.Session.add(a)
    #meta.Session.commit()
    for coord in coords:
        cobj = AreaPoint()
        #cobj.area_id = a.id
        cobj.area = a
        cobj.pos_lon = coord[0]
        cobj.pos_lat = coord[1]
        meta.Session.add(cobj)

    meta.Session.commit()
    if return_obj:
        return a
    return get_area(a=a)
开发者ID:guyromm,项目名称:greencouriers,代码行数:44,代码来源:signup.py

示例9: PolygonPointSampler

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
class PolygonPointSampler(object):

    def __init__(self, polygon=''):
        """
        Initialize a new PolygonPointSampler object using the specified polygon
        object (as allocated by Shapely). If no polygon is given a new empty
        one is created and set as the base polygon.
        """
        if polygon:
            self.polygon = polygon
        else:
            self.polygon = Polygon()
        self.samples = list()
        self.sample_count = 0
        self.prepared = False

    def add_polygon(self, polygon):
        """
        Add another polygon entity to the base polygon by geometrically
        unifying it with the current one.
        """
        self.polygon = self.polygon.union(polygon)
        self.prepared = False

    def print_samples(self):
        """
        Print all sample points using their WKT representation.
        """
        for sample_pt in self.samples:
            print(sample_pt)

    def prepare_sampling(self):
        """
        Prepare the actual sampling procedure by splitting up the specified
        base polygon (that may consist of multiple simple polygons) and
        appending its compartments to a dedicated list.
        """
        self.src = list()
        if hasattr(self.polygon, 'geoms'):
            for py in self.polygon:
                self.src.append(py)
        else:
            self.src.append(self.polygon)
        self.prepared = True

    def perform_sampling(self):
        """
        Create a stub for the actual sampling procedure.
        """
        raise NotImplementedError
开发者ID:leaffan,项目名称:geo,代码行数:52,代码来源:polygon_point_sampler.py

示例10: sample_tuples_near_shape

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def sample_tuples_near_shape(shape, tuples, *, n=100, neighbor_dist=100):
    """Return a random subsample of at most N of the data tuples in
       TUPLES.  Each tuple must have 'lat' and 'lon' properties.  No
       two selected tuples will be closer to each other than
       NEIGHBOR_DIST kilometers. Tuples whose lat and lon lie within
       SHAPE will be selected first; if there are not enough, the
       shape will be progressively enlarged until either enough have
       been found, or we run out.
    """
    population = []
    covered = Polygon()
    neighbor_dist *= 1000
    for t in tuples:
        k = (t.lon, t.lat)
        if not covered.contains(Point(*k)):
            population.append(t)
            covered = covered.union(DiskOnGlobe(*k, neighbor_dist))

    if len(population) <= n:
        return population

    subsample = []
    while True:
        fshape = sh_prep(shape)
        hits = []
        rest = []
        for t in population:
            if fshape.contains(Point(t.lon, t.lat)):
                hits.append(t)
            else:
                rest.append(t)

        want = n - len(subsample)
        have = len(hits)
        if have == want:
            subsample.extend(hits)
            return subsample
        elif have > want:
            subsample.extend(random.sample(hits, want))
            return subsample
        else:
            subsample.extend(hits)
            if not rest:
                return subsample
            population = rest
            shape = shape.buffer(5)
开发者ID:zackw,项目名称:active-geolocator,代码行数:48,代码来源:geometry.py

示例11: iter_chars_on_line

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def iter_chars_on_line(chars, line, start_len, step=0.6):
    '''
    Yields single character geometries placed on line.

    :param chars: iterable generated by ``generate_char_geoms``
    :param line: :class:`shapely.geometry.LineString`
    :param start_len: length or start position on line as int or float
    :param step: distance a character is moved on line at each iteration
        (decrease for more accuracy and increase for faster rendering)

    :yields: character geometries as :class:`shapely.geometry.MultiLineString`
    '''

    # make sure first character is not rendered directly at the edge of the line
    cur_len = max(start_len, 1)
    # geometry containing path of all rotated characters
    text_geom = Polygon()
    for paths, width, spacing in chars:
        cur_len += spacing
        last_rad = None
        for _ in xrange(30):
            # get current position on line
            pos = line.interpolate(cur_len)
            # get radians of gradient
            rad = linestring_char_radians(line, cur_len, width)
            #: only rotate if radians changed
            if rad != last_rad:
                rot_coords = tuple(tuple(rotate_coords(geom, rad))
                    for geom in paths)
            last_rad = rad
            # move rotated char to current position
            rot = MultiPolygon(tuple(
                Polygon(tuple(translate_coords(c, pos.x, pos.y)))
                for c in rot_coords
            ))
            # check whether distance to previous characters is long enough
            if (
                text_geom.distance(rot) >= spacing
                or text_geom.geom_type == 'GeometryCollection'
            ):
                text_geom = text_geom.union(rot)
                cur_len += width
                yield rot
                break
            cur_len += step
开发者ID:ahojnnes,项目名称:mapython,代码行数:47,代码来源:utils.py

示例12: localizationAccuracy

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def localizationAccuracy(truth, pred):
    truth = Polygon(truth)
    pred = Polygon(pred)

    inter = truth.intersection(pred)
    union = truth.union(pred)
    lr = inter.area / union.area

    print ''
    print 'tr points -> {0}'.format(truth)
    print 'pr points -> {0}'.format(pred)
    print ''
    print 'inter {0}'.format(inter.area)
    print 'union {0}'.format(union.area)
    print 'IR {0}'.format(lr)
    print ''

    return lr
开发者ID:allansp84,项目名称:license-plate,代码行数:20,代码来源:utils.py

示例13: concave_hull

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def concave_hull(points, alpha, delunay_args=None):
    """Computes the concave hull (alpha-shape) of a set of points.
    """
    delunay_args = delunay_args or {
        'furthest_site': False,
        'incremental': False,
        'qhull_options': None
    }
    triangulation = Delaunay(np.array(points))
    alpha_complex = get_alpha_complex(alpha, points, triangulation.simplices)
    X, Y = [], []
    for s in triangulation.simplices:
        X.append([points[s[k]][0] for k in [0, 1, 2, 0]])
        Y.append([points[s[k]][1] for k in [0, 1, 2, 0]])
    poly = Polygon(list(zip(X[0], Y[0])))
    for i in range(1, len(X)):
        poly = poly.union(Polygon(list(zip(X[i], Y[i]))))
    return poly
开发者ID:alpha-beta-soup,项目名称:errorgeopy,代码行数:20,代码来源:utils.py

示例14: intersect_area_area

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def intersect_area_area(a1,a2):
	a1points = [(float(p.pos_lon),float(p.pos_lat)) for p in a1.points]
	poly1 = Polygon(a1points);
	area1=poly1.area
	a1.area_vol = area1

	a2points = [(float(p.pos_lon),float(p.pos_lat)) for p in a2.points]
	poly2 = Polygon(a2points);
	area2=poly2.area
	a2.area_vol = area2

	un = poly1.union(poly2)
	joint_area=un.area
	area_diff = abs(area1 + area2 - joint_area)

	if area_diff>0.0001:
		rt= area_diff / area1 * 100
		#raise Exception('here %s , %s'%(area_diff,rt))
                return rt
	else:
		return False
开发者ID:guyromm,项目名称:greencouriers,代码行数:23,代码来源:__init__.py

示例15: areaOverlapError

# 需要导入模块: from shapely.geometry import Polygon [as 别名]
# 或者: from shapely.geometry.Polygon import union [as 别名]
def areaOverlapError(truth, edge):
    '''
    Function to calculate the area of overlap error between two contours

    args:
    	@a truth: numpy array, shape=(num points,2)
    	@a edge: same as truth
    '''
    if truth==[] or edge==[]:
        return 1.0
    if len(truth)<3 or len(edge)<3:
        return 1.0
    truth_tups = zip(truth[:,0],truth[:,1])
    edge_tups = zip(edge[:,0],edge[:,1])

    t = Polygon(truth_tups)
    e = Polygon(edge_tups)
    if not (e.is_valid and t.is_valid):
    	print "invalid geometry, error = 1.0"
    	return 1.0
    Aunion = e.union(t).area
    Aintersection = e.intersection(t).area

    return 1.0-float(Aintersection)/Aunion
开发者ID:gmaher,项目名称:tcl_code,代码行数:26,代码来源:utility.py


注:本文中的shapely.geometry.Polygon.union方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。