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


Python affinity.scale函数代码示例

本文整理汇总了Python中shapely.affinity.scale函数的典型用法代码示例。如果您正苦于以下问题:Python scale函数的具体用法?Python scale怎么用?Python scale使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: olson_transform

def olson_transform(geojson, scale_values):
    """
    Scale GeoJSON features.

    Inplace scaling transformation of each polygon of the geojson provided
    according to the "scale values" also provided.

    Parameters
    ----------
    geojson: dict
        The geojson of polygon to transform
        (it might be useful to have choosen an appropriate projection as we
        want to deal with the area)
    scale_values: list
        The pre-computed scale values for olson transformation
        (1 = no transformation)

    Returns
    -------
        Nothing
    """
    if len(geojson["features"]) != len(scale_values):
        raise ValueError("Inconsistent number of features/values")
    for val, feature in zip(scale_values, geojson['features']):
        geom = shape(feature["geometry"])
        feature['properties']['ref_area'] = geom.area
        if hasattr(geom, '__len__'):
            feature["geometry"] = mapping(
                MultiPolygon([scale(g, xfact=val, yfact=val) for g in geom]))
        else:
            feature["geometry"] = mapping(scale(geom, xfact=val, yfact=val))
    geojson['features'].sort(
        key=lambda x: x['properties']['ref_area'], reverse=True)
开发者ID:mthh,项目名称:noname-stuff,代码行数:33,代码来源:geo.py

示例2: handle

    def handle(self, *args, **options):
        minx = options['minx']
        miny = options['miny']
        maxx = options['maxx']
        maxy = options['maxy']

        if minx >= maxx:
            raise CommandError(_('minx has to be lower than maxx'))
        if miny >= maxy:
            raise CommandError(_('miny has to be lower than maxy'))

        width = maxx-minx
        height = maxy-miny

        model = {'areas': Area, 'obstacles': Obstacle}[options['type']]

        namespaces = {'svg': 'http://www.w3.org/2000/svg'}

        svg = ElementTree.fromstring(options['svgfile'].read())
        svg_width = float(svg.attrib['width'])
        svg_height = float(svg.attrib['height'])

        for element in svg.findall('.//svg:clipPath/..', namespaces):
            for clippath in element.findall('./svg:clipPath', namespaces):
                element.remove(clippath)

        for element in svg.findall('.//svg:symbol/..', namespaces):
            for clippath in element.findall('./svg:symbol', namespaces):
                element.remove(clippath)

        if svg.findall('.//*[@transform]'):
            raise CommandError(_('svg contains transform attributes. Use inkscape apply transforms.'))

        if model.objects.filter(space=options['space'], import_tag=options['name']).exists():
            raise CommandError(_('objects with this import tag already exist in this space.'))

        with MapUpdate.lock():
            changed_geometries.reset()
            for path in svg.findall('.//svg:path', namespaces):
                for polygon in self.parse_svg_data(path.attrib['d']):
                    if len(polygon) < 3:
                        continue
                    polygon = Polygon(polygon)
                    polygon = scale(polygon, xfact=1, yfact=-1, origin=(0, svg_height/2))
                    polygon = scale(polygon, xfact=width / svg_width, yfact=height / svg_height, origin=(0, 0))
                    polygon = translate(polygon, xoff=minx, yoff=miny)
                    obj = model(geometry=polygon, space=options['space'], import_tag=options['name'])
                    obj.save()
            MapUpdate.objects.create(type='importsvg')

        logger = logging.getLogger('c3nav')
        logger.info('Imported, map update created.')
        logger.info('Next step: go into the shell and edit them using '
                    '%s.objects.filter(space_id=%r, import_tag=%r)' %
                    (model.__name__, options['space'].pk, options['name']))
开发者ID:nomoketo,项目名称:c3nav-new,代码行数:55,代码来源:importsvg.py

示例3: map_to_polygon

def map_to_polygon(shape,origin,position,rotation,size):
    geom_obj=Polygon(shape)
    geom_obj=affinity.translate(geom_obj, -origin[0],-origin[1],0)
    geom_obj=affinity.scale(geom_obj,size[0],size[1],origin=(0,0))
    geom_obj=affinity.rotate(geom_obj,int(rotation*360),origin=(0,0))
    geom_obj=affinity.translate(geom_obj, position[0],position[1],0)
    return geom_obj
开发者ID:MetaDev,项目名称:thesis-hypergenerator,代码行数:7,代码来源:mapping.py

示例4: on_create_alignment_holes

    def on_create_alignment_holes(self):
        axis = self.mirror_axis.get_value()
        mode = self.axis_location.get_value()

        if mode == "point":
            px, py = self.point.get_value()
        else:
            selection_index = self.box_combo.currentIndex()
            bb_obj = self.app.collection.object_list[selection_index]  # TODO: Direct access??
            xmin, ymin, xmax, ymax = bb_obj.bounds()
            px = 0.5 * (xmin + xmax)
            py = 0.5 * (ymin + ymax)

        xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]

        dia = self.drill_dia.get_value()
        tools = {"1": {"C": dia}}

        # holes = self.alignment_holes.get_value()
        holes = eval("[{}]".format(self.alignment_holes.text()))
        drills = []

        for hole in holes:
            point = Point(hole)
            point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
            drills.append({"point": point, "tool": "1"})
            drills.append({"point": point_mirror, "tool": "1"})

        def obj_init(obj_inst, app_inst):
            obj_inst.tools = tools
            obj_inst.drills = drills
            obj_inst.create_geometry()

        self.app.new_object("excellon", "Alignment Drills", obj_init)
开发者ID:suchdileep,项目名称:flatcam,代码行数:34,代码来源:DblSidedTool.py

示例5: reinforcement_polygon

def reinforcement_polygon(asf_file, diametrs_dop, elements, scale = 1.1):
    out = sha.scale(elements[0], xfact=scale , yfact=scale )
    for i,d in enumerate(diametrs_dop):
        if d != 0:
            el = sha.scale(elements[i], xfact=scale , yfact=scale)
            out = out.union(el)
    if out.geom_type != 'Polygon':
        for i,el in enumerate(out):
            minx, miny, maxx, maxy = el.bounds
            a = sha.scale(sh.box(minx, miny, maxx, maxy), xfact=scale , yfact=scale)
            if i == 0:      
                out = a
            else:
                out = out.union(a)
    out = out.intersection(asf_file.plate)
    return out
开发者ID:kuvbur,项目名称:asf-reinforcement,代码行数:16,代码来源:parse.py

示例6: get_circles_centers

def get_circles_centers(bbox, radius=5000, polygons=None):
	"""
	Function calculates centers for circles, that would cover all the bounding box, or area inside polygons. 
	Used to create points for collectors, where radius small enough to matter (Instagram, VKontakte).

	Args:
		bbox (List[float]): long-lat corners for bounding box, that should be covered.
		radius (int): radius of circles, that will cover bounding box, in meters.
		polygons (shapely.geometry.polygon): geo polygon to describe monitoring area more precisely, and exclude some surplus centers.
	"""
	from math import radians, cos
	from itertools import product
	lat = radians(max([abs(bbox[1]), abs(bbox[3])]))
	# Calculate the length of a degree of latitude and longitude in meters
	latlen = 111132.92 - (559.82 * cos(2 * lat)) + (1.175 * cos(4 * lat)) + (-0.0023 * cos(6 * lat))
	longlen = (111412.84 * cos(lat)) - (93.5 * cos(3 * lat)) + (0.118 * cos(5 * lat))
	radius_x = radius/longlen
	radius_y = radius/latlen
	x_marks = [x for x in drange(bbox[0], bbox[2], radius_x)]
	y_marks = [y for y in drange(bbox[1], bbox[3], radius_y)]
	centers = [x for x in product(x_marks[0::2], y_marks[0::2])] + [x for x in product(x_marks[1::2], y_marks[1::2])]
	if polygons:
		cleaned_centers = []
		from shapely.geometry import Point
		from shapely.affinity import scale
		for center in centers:
			circle = scale(Point(center[0], center[1]).buffer(1), xfact=radius_x, yfact=radius_y)
			if polygons.intersects(circle):
				cleaned_centers.append(center)
		centers = cleaned_centers
	return centers
开发者ID:city-pulse,项目名称:mskpulse.backend,代码行数:31,代码来源:utilities.py

示例7: mirror_x

 def mirror_x(self, x = 0):
     ofigs = []
     center=(x,0,0)
     for f in self.figs:
         tmp = affinity.scale(f, xfact=-1, yfact=1,origin=center)
         ofigs.append(tmp)
     self.figs = ofigs
开发者ID:infinity0n3,项目名称:python-fabtotum,代码行数:7,代码来源:shapely_backend.py

示例8: _add_slope

    def _add_slope(self, bounds, altitude1, altitude2, point1, point2, bottom=False):
        altitude_diff = altitude2-altitude1
        altitude_middle = (altitude1+altitude2)/2
        altitude_halfdiff = altitude_diff/2
        altitude_base = altitude1
        line = LineString([point1, point2])

        minx, miny, maxx, maxy = bounds
        points_2d = [(minx-100, miny-100), (maxx+100, miny-100), (maxx+100, maxy+100), (minx-100, maxy+100)]
        points_3d = []
        for i, (x, y) in enumerate(points_2d):
            point = Point((x, y))
            pos = line.project(point)
            while pos <= 0 or pos >= line.length-1:
                line = scale(line, xfact=2, yfact=2, zfact=2)
                altitude_diff *= 2
                altitude_halfdiff *= 2
                altitude_base = altitude_middle-altitude_halfdiff
                pos = line.project(point)
            z = ((pos/line.length)*altitude_diff)+altitude_base
            points_3d.append((x, y, z/1000))

        extrude = abs(altitude1-altitude2)/1000+100
        if bottom:
            extrude = -extrude
        self._add_python(
            'last_slope = add_polygon_3d(name=%(name)r, coords=%(coords)r, extrude=%(extrude)f)' % {
                'name': 'tmpslope',
                'coords': tuple(points_3d),
                'extrude': extrude,
            }
        )
开发者ID:nomoketo,项目名称:c3nav-new,代码行数:32,代码来源:blender.py

示例9: calibrate_measurement_model

    def calibrate_measurement_model(self, arg_model_params):
        x1, y1, x2, y2 = self.container.floor.polygon.bounds
        world_size = (x2 / float(self.container.scale), y2 / float(self.container.scale))
        usable_area_poly = sa.scale(self.container.usable_area.polygon,
                                     1 / float(self.container.scale), 1 / float(self.container.scale),
                                     origin=(0, 0, 0))

        self.particle_filter_model_param = ParticleFilterModelParameters(arg_number_of_particles=arg_model_params.number_of_particles,
                                                         arg_world_dimensions=world_size,
                                                         arg_sensor_noise=arg_model_params.sensor_noise,
                                                         arg_turn_noise=arg_model_params.turn_noise,
                                                         arg_forward_noise=arg_model_params.forward_noise,
                                                         arg_speed=arg_model_params.forward_speed,
                                                         arg_turn=arg_model_params.iteration_turn,
                                                         arg_world_usable_area=usable_area_poly.exterior.coords[:])

        # Sensor Geometry needs to be translated to position relative to origin taken to be top left corner of room
        # on floor plan i.e. bounding box for usable area

        min_from_origin = min([np.sqrt(pow(j[0],2)+pow(j[1],2)) for j in usable_area_poly.exterior.coords[:]])
        minx, miny = [i for i in usable_area_poly.exterior.coords[:]
                      if np.sqrt(pow(i[0],2)+pow(i[1],2)) ==min_from_origin ][0]

        # self.sensor_properties = copy.deepcopy(self.sensor_properties)
        # 
        for k, sensor_prop in self.sensor_properties.items():
            self.sensor_properties[k].measurement_boundary_poly = usable_area_poly.intersection(
                self.sensor_properties[k].measurement_boundary_poly)
            self.sensor_properties[k].measurement_boundary = [
                self.sensor_properties[k].measurement_boundary_poly.exterior.coords[:]]

        self.pir_model = ParticleFilter(self.particle_filter_model_param, self.sensor_properties.values())
开发者ID:tS7hKamAYL84j91,项目名称:Infrared-IPS,代码行数:32,代码来源:angular_measurement_fusion_model.py

示例10: _do_inverse_transform

 def _do_inverse_transform(shape, rotation, mirrored, rotation_origin=(0,0), scale_origin=(0,0)):
     if shape is None or shape.is_empty:
         return shape
     r = shape
     r = affinity.scale(r, xfact=(-1 if mirrored else 1), origin=scale_origin)
     r = affinity.rotate(r, -rotation, origin=rotation_origin)
     return r;
开发者ID:NVSL,项目名称:Swoop,代码行数:7,代码来源:ShapelySwoop.py

示例11: compute_voronoi

def compute_voronoi(keypoints, intersection=None, geometry=False, s=30): # ADDED
        """
        Creates a voronoi diagram for all edges in a graph, and assigns a given
        weight to each edge. This is based around voronoi polygons generated
        by scipy's voronoi method, to determine if an image has significant coverage.

        Parameters
        ----------
        graph : object
               A networkx graph object

        clean_keys : list
                     Of strings used to apply masks to omit correspondences

        s : int
            Offset for the corners of the image
        """
        vor_keypoints = []

        keypoints.apply(lambda x: vor_keypoints.append((x['x'], x['y'])), axis = 1)

        if intersection is None:
            keypoint_bounds = Polygon(vor_keypoints).bounds
            intersection = shapely.geometry.box(keypoint_bounds[0], keypoint_bounds[1],
                                                    keypoint_bounds[2], keypoint_bounds[3])

        scaled_coords = np.array(scale(intersection, s, s).exterior.coords)

        vor_keypoints = np.vstack((vor_keypoints, scaled_coords))
        vor = Voronoi(vor_keypoints)
        # Might move the code below to its own method depending on feedback
        if geometry:
            voronoi_df = gpd.GeoDataFrame(data = keypoints, columns=['x', 'y', 'weight', 'geometry'])
        else:
            voronoi_df = gpd.GeoDataFrame(data = keypoints, columns=['x', 'y', 'weight'])

        i = 0
        vor_points = np.asarray(vor.points)
        for region in vor.regions:
            region_point = vor_points[np.argwhere(vor.point_region==i)]

            if not -1 in region:
                polygon_points = [vor.vertices[i] for i in region]

                if len(polygon_points) != 0:
                    polygon = Polygon(polygon_points)

                    intersection_poly = polygon.intersection(intersection)

                    voronoi_df.loc[(voronoi_df["x"] == region_point[0][0][0]) &
                                   (voronoi_df["y"] == region_point[0][0][1]),
                                   'weight'] = intersection_poly.area
                    if geometry:
                        voronoi_df.loc[(voronoi_df["x"] == region_point[0][0][0]) &
                                       (voronoi_df["y"] == region_point[0][0][1]),
                                       'geometry'] = intersection_poly
            i += 1

        return voronoi_df
开发者ID:Kelvinrr,项目名称:autocnet,代码行数:59,代码来源:cg.py

示例12: ellipse

def ellipse(width, length):
    """Create ellipse when given width and length.
    """
    circle = geo.Point(0, 0).buffer(1)
    stretched = aff.scale(circle, xfact=width/2, yfact=length/2)
    rotated = aff.rotate(stretched, -45)

    return rotated
开发者ID:Jothy,项目名称:electronfactors,代码行数:8,代码来源:genericshape.py

示例13: get_intersection

    def get_intersection(self, vertex_line, line, center):
        while not line.crosses(vertex_line):
            line = affinity.scale(line, xfact=2.0, yfact=2.0, origin=center)

        object_of_intersection = line.intersection(vertex_line)
        for coord in object_of_intersection.coords:
            if not self.almost_equals(center, coord):
                return geometry.Point(coord)
开发者ID:wangjohn,项目名称:shape_of_stones,代码行数:8,代码来源:stone.py

示例14: coordinate_conversion

def coordinate_conversion(data, width, height):
    scaleX=ncol * pixelFormat / width * pixelSize
    scaleY=nrow * pixelFormat / height * pixelSize
    Xmap=map(int, data[:, 0].tolist())
    Ymap=map(int, data[:, 1].tolist())
    geom=Polygon(zip(Xmap, Ymap))
    geom2=scale(geom, xfact=scaleX, yfact=scaleY, origin=((0, 0)))
    return geom2, scaleX, scaleY
开发者ID:jpabbuehl,项目名称:CSC_submission,代码行数:8,代码来源:lightsheet+data+analysis.py

示例15: load_marker

def load_marker(z):
    sx, sy = W / 600, H / 800
    s = min(sx, sy)
    polygon = loads(WKT)
    polygon = scale(polygon, s, s)
    polygon = polygon.buffer(0.125)
    g = GCode.from_geometry(polygon, G0Z, z)
    g = g.move(3, 4, 0.5, 0.5)
    return g
开发者ID:fogleman,项目名称:Carolina,代码行数:9,代码来源:marker.py


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