本文整理汇总了Python中shapely.affinity.scale方法的典型用法代码示例。如果您正苦于以下问题:Python affinity.scale方法的具体用法?Python affinity.scale怎么用?Python affinity.scale使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.affinity
的用法示例。
在下文中一共展示了affinity.scale方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_as_shapely
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def get_as_shapely(self, cell, layer=None, datatype=None):
geometry = []
gdspy_cell = self.gdslib.cells[cell] if isinstance(cell, str) else cell
for polygon in gdspy_cell.polygons:
if self.layer is not None and layer != polygon.layers[0]:
continue
if self.datatype is not None and datatype != polygon.datatypes[0]:
continue
geometry.append(Polygon(polygon.polygons[0]).buffer(0)) # .buffer(0) for healing geometries
for reference in gdspy_cell.references:
sub_geometry = self.get_as_shapely(reference.ref_cell, layer, datatype)
if sub_geometry.is_empty:
continue
sub_geometry = scale(sub_geometry,
*[reference.magnification] * 2) if reference.magnification else sub_geometry
sub_geometry = scale(sub_geometry, -1) if reference.x_reflection else sub_geometry
sub_geometry = rotate(sub_geometry, reference.rotation,
origin=(0, 0)) if reference.rotation else sub_geometry
sub_geometry = translate(sub_geometry, *reference.origin)
geometry.extend(sub_geometry)
return MultiPolygon(geometry)
示例2: mirror
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def mirror(self, axis, point):
"""
Mirrors the object around a specified axis passign through
the given point.
:param axis: "X" or "Y" indicates around which axis to mirror.
:type axis: str
:param point: [x, y] point belonging to the mirror axis.
:type point: list
:return: None
"""
px, py = point
xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
## solid_geometry ???
# It's a cascaded union of objects.
self.solid_geometry = affinity.scale(self.solid_geometry,
xscale, yscale, origin=(px, py))
示例3: scale
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def scale(self, factor):
"""
Scales geometry on the XY plane in the object by a given factor.
Tool sizes, feedrates an Z-plane dimensions are untouched.
:param factor: Number by which to scale the object.
:type factor: float
:return: None
:rtype: NOne
"""
# Drills
for drill in self.drills:
drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
self.create_geometry()
示例4: get_shapely_object
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def get_shapely_object(self):
# Start with the "rays"
# noinspection PyTypeChecker
ray_angles = np.linspace(0, np.pi / 2, 8) + np.pi / 2
outer_ray_positions = (np.array([np.cos(ray_angles), np.sin(ray_angles)]) * self.height).T + (self.height, 0)
inner_ray_positions = (np.array([np.cos(ray_angles), np.sin(ray_angles)])
* self.height * self.min_radius_fraction).T + (self.height, 0)
polygons = list()
for outer, inner in zip(outer_ray_positions.reshape(-1, 2, 2), inner_ray_positions.reshape(-1, 2, 2)):
polygons.append(Polygon([outer[0], outer[1], inner[1], inner[0]]))
pass
# Draw the letters
d = self.height * 0.077
k_upper_branch = rotate(box(0, -d, sqrt(2) * self.height / 2 + sqrt(2) * d, d), 45, origin=(0, 0))
k_lower_branch = scale(k_upper_branch, yfact=-1., origin=(0, 0))
k_uncut = k_upper_branch.union(k_lower_branch)
k_unscaled = k_uncut.intersection(box(0, -self.height / 2., self.height / 2. + sqrt(2) * d, self.height / 2.))
k = scale(k_unscaled, 0.8, origin=(0, 0))
polygons.append(translate(k, self.height * 1.05, self.height / 2.))
i = box(0, 0, 2 * d, self.height)
polygons.append(translate(i, self.height * 1.6))
t_overlap = 2
t = box(-d, 0, d, self.height).union(
box(-d * (1 + t_overlap), self.height - 2 * d, d * (1 + t_overlap), self.height))
polygons.append(translate(t, self.height * 2.05))
logo = cascaded_union(polygons)
return translate(logo, *self.origin)
示例5: on_create_alignment_holes
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
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()
model_index = self.app.collection.index(selection_index, 0, self.object_combo.rootModelIndex())
bb_obj = model_index.internalPointer().obj
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)
示例6: import_svg
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def import_svg(self, filename, flip=True):
"""
Imports shapes from an SVG file into the object's geometry.
:param filename: Path to the SVG file.
:type filename: str
:return: None
"""
# Parse into list of shapely objects
svg_tree = ET.parse(filename)
svg_root = svg_tree.getroot()
# Change origin to bottom left
# h = float(svg_root.get('height'))
# w = float(svg_root.get('width'))
h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
geos = getsvggeo(svg_root)
if flip:
geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
# Add to object
if self.solid_geometry is None:
self.solid_geometry = []
if type(self.solid_geometry) is list:
self.solid_geometry.append(cascaded_union(geos))
else: # It's shapely geometry
self.solid_geometry = cascaded_union([self.solid_geometry,
cascaded_union(geos)])
return
示例7: convert_units
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def convert_units(self, units):
"""
Converts the units of the object to ``units`` by scaling all
the geometry appropriately. This call ``scale()``. Don't call
it again in descendents.
:param units: "IN" or "MM"
:type units: str
:return: Scaling factor resulting from unit change.
:rtype: float
"""
log.debug("Geometry.convert_units()")
if units.upper() == self.units.upper():
return 1.0
if units.upper() == "MM":
factor = 25.4
elif units.upper() == "IN":
factor = 1 / 25.4
else:
log.error("Unsupported units: %s" % str(units))
return 1.0
self.units = units
self.scale(factor)
return factor
示例8: _add_slope
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
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,
}
)
示例9: get_places_bbox
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def get_places_bbox(
bbox: str = Query(
...,
title="Bounding box to search",
description="Format: left_lon,bottom_lat,right_lon,top_lat",
example="-4.56,48.35,-4.42,48.46",
),
category: Optional[List[str]] = Query(None),
raw_filter: Optional[List[str]] = Query(None),
source: Optional[str] = Query(None),
q: Optional[str] = Query(None, title="Query", description="Full text query"),
size: Optional[int] = Query(None),
lang: Optional[str] = Query(None),
verbosity: Optional[str] = Query(None),
extend_bbox: bool = Query(False),
) -> PlacesBboxResponse:
params = PlacesQueryParam(**locals())
source = params.source
if source is None:
if (
params.q or (params.category and all(c.get("pj_filters") for c in params.category))
) and pj_source.bbox_is_covered(params.bbox):
params.source = PoiSource.PAGESJAUNES
else:
params.source = PoiSource.OSM
places_list = await _fetch_places_list(params)
bbox_extended = False
if params.extend_bbox and len(places_list) == 0:
original_bbox = params.bbox
original_bbox_width = original_bbox[2] - original_bbox[0]
original_bbox_height = original_bbox[3] - original_bbox[1]
original_bbox_size = max(original_bbox_height, original_bbox_width)
if original_bbox_size < EXTENDED_BBOX_MAX_SIZE:
# Compute extended bbox and fetch results a second time
scale_factor = EXTENDED_BBOX_MAX_SIZE / original_bbox_size
new_box = scale(box(*original_bbox), xfact=scale_factor, yfact=scale_factor)
params.bbox = new_box.bounds
bbox_extended = True
places_list = await _fetch_places_list(params)
if len(places_list) == 0:
results_bbox = None
else:
points = MultiPoint([(p.get_coord()["lon"], p.get_coord()["lat"]) for p in places_list])
results_bbox = points.bounds
result_places = await run_in_threadpool(
lambda: [p.load_place(params.lang, params.verbosity) for p in places_list]
)
return PlacesBboxResponse(
places=result_places, source=params.source, bbox=results_bbox, bbox_extended=bbox_extended,
)
示例10: offset
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def offset(self, vect):
"""
Offsets the objects' geometry on the XY plane by a given vector.
These are:
* ``buffered_paths``
* ``flash_geometry``
* ``solid_geometry``
* ``regions``
NOTE:
Does not modify the data used to create these elements. If these
are recreated, the scaling will be lost. This behavior was modified
because of the complexity reached in this class.
:param vect: (x, y) offset vector.
:type vect: tuple
:return: None
"""
dx, dy = vect
## Solid geometry
self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
# def mirror(self, axis, point):
# """
# Mirrors the object around a specified axis passign through
# the given point. What is affected:
#
# * ``buffered_paths``
# * ``flash_geometry``
# * ``solid_geometry``
# * ``regions``
#
# NOTE:
# Does not modify the data used to create these elements. If these
# are recreated, the scaling will be lost. This behavior was modified
# because of the complexity reached in this class.
#
# :param axis: "X" or "Y" indicates around which axis to mirror.
# :type axis: str
# :param point: [x, y] point belonging to the mirror axis.
# :type point: list
# :return: None
# """
#
# px, py = point
# xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
#
# ## solid_geometry ???
# # It's a cascaded union of objects.
# self.solid_geometry = affinity.scale(self.solid_geometry,
# xscale, yscale, origin=(px, py))
示例11: img_to_wkt
# 需要导入模块: from shapely import affinity [as 别名]
# 或者: from shapely.affinity import scale [as 别名]
def img_to_wkt(img, scale_rate, target_name, W, H, Xmax, Ymin, t_value, cla):
W_dash = W * W / (W + 1)
H_dash = H * H / (H + 1)
if scale_rate < 0.99:
img_tiny = rescale(img, scale_rate)
else:
img_tiny = img
bmp_image_path = '_temp/' + target_name + '.bmp'
target_json_path = '_temp/' + target_name + '.json'
with warnings.catch_warnings():
warnings.simplefilter("ignore")
imsave(bmp_image_path, img_tiny)
os.system('potrace -a 2 -t ' + str(t_value) + ' -b geojson -i ' + bmp_image_path + ' -o ' + target_json_path)
f = open(target_json_path)
data = json.load(f)
f.close()
os.remove(target_json_path)
os.remove(bmp_image_path)
# type of 'data' is feature collection
# we only need focus on features
features = data['features']
list_polygons = list()
for i in range(len(features)):
shapely_polygon = shape(geojson.loads(json.dumps(features[i]['geometry'])))
if scale_rate < 0.99:
shapely_polygon = scale(shapely_polygon, 1/scale_rate, 1/scale_rate, origin=(0, 0))
list_polygons.append(shapely_polygon.buffer(0.0))
multi = MultiPolygon(list_polygons)
multi = scale(multi, 1, -1, 1, origin=(float(W)/2, float(H)/2))
multi = scale(multi, Xmax / W_dash, Ymin / H_dash, origin=(0, 0))
if cla != 6:
multi = multi.simplify(1e-6, preserve_topology=True)
else:
multi = multi.simplify(1e-5, preserve_topology=True)
multi = multi.buffer(0)
if multi.type == 'Polygon':
multi = MultiPolygon([multi])
return multi
# tpex's evaluation code can validate topology more strictly
# https://github.com/cxz/tpex