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


Python base.BaseGeometry方法代码示例

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


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

示例1: __getitem__

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def __getitem__(self, geometry):
        if isinstance(geometry, BaseGeometry) or getattr(geometry, "__geo_interface__", None) is not None:
            if self._tms_meta._bounds is None:
                return self.aoi(geojson=mapping(geometry), from_proj=self.proj)
            image = GeoDaskImage.__getitem__(self, geometry)
            image._tms_meta = self._tms_meta
            return image
        else:
            result = super(TmsImage, self).__getitem__(geometry)
            image = super(TmsImage, self.__class__).__new__(self.__class__, result)
            if all([isinstance(e, slice) for e in geometry]) and len(geometry) == len(self.shape):
                xmin, ymin, xmax, ymax = geometry[2].start, geometry[1].start, geometry[2].stop, geometry[1].stop
                xmin = 0 if xmin is None else xmin
                ymin = 0 if ymin is None else ymin
                xmax = self.shape[2] if xmax is None else xmax
                ymax = self.shape[1] if ymax is None else ymax

                g = ops.transform(self.__geo_transform__.fwd, box(xmin, ymin, xmax, ymax))
                image.__geo_interface__ = mapping(g)
                image.__geo_transform__ = self.__geo_transform__ + (xmin, ymin)
            else:
                image.__geo_interface__ = self.__geo_interface__
                image.__geo_transform__ = self.__geo_transform__
            image._tms_meta = self._tms_meta
            return image 
开发者ID:DigitalGlobe,项目名称:gbdxtools,代码行数:27,代码来源:tms_image.py

示例2: clip

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def clip(self, shape: base.BaseGeometry) -> Optional["Flight"]:
        linestring = LineString(list(self.xy_time))
        intersection = linestring.intersection(shape)
        begin: Optional[datetime] = None

        if intersection.is_empty:
            return None

        if isinstance(intersection, LineString):
            begin, *_, end = list(
                datetime.fromtimestamp(t, timezone.utc)
                for t in np.stack(intersection.coords)[:, 2]
            )

        else:
            for x in LineString(list(self.xy_time)).intersection(shape):
                begin_, *_, end = list(
                    datetime.fromtimestamp(t, timezone.utc)
                    for t in np.stack(x.coords)[:, 2]
                )
                if begin is None:
                    begin = begin_

        return self.between(begin, end) 
开发者ID:xoolive,项目名称:traffic,代码行数:26,代码来源:so6.py

示例3: to_dict

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def to_dict(obj):
    """
    Makes the following types into serializable form:

    * ApertureMacro
    * BaseGeometry

    :param obj: Shapely geometry.
    :type obj: BaseGeometry
    :return: Dictionary with serializable form if ``obj`` was
        BaseGeometry or ApertureMacro, otherwise returns ``obj``.
    """
    if isinstance(obj, ApertureMacro):
        return {
            "__class__": "ApertureMacro",
            "__inst__": obj.to_dict()
        }
    if isinstance(obj, BaseGeometry):
        return {
            "__class__": "Shply",
            "__inst__": sdumps(obj)
        }
    return obj 
开发者ID:Denvi,项目名称:FlatCAM,代码行数:25,代码来源:camlib.py

示例4: __getitem__

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def __getitem__(self, key):
        if isinstance(key, tuple):
            xx, yy = key

            minx = int(math.floor(xx.start / self.resolution))
            miny = int(math.floor(yy.start / self.resolution))
            maxx = int(math.ceil(xx.stop / self.resolution))
            maxy = int(math.ceil(yy.stop / self.resolution))

            height, width = self.data.shape
            minx = max(0, minx - self.x)
            miny = max(0, miny - self.y)
            maxx = max(0, maxx - self.x)
            maxy = max(0, maxy - self.y)

            return self.data[miny:maxy, minx:maxx].ravel()

        from shapely.geometry.base import BaseGeometry
        if isinstance(key, BaseGeometry):
            bounds = self._get_geometry_bounds(key)
            return self.data[self.get_geometry_cells(key, bounds)]

        raise TypeError('GeometryIndexed index must be a shapely geometry or tuple, not %s' % type(key).__name__) 
开发者ID:c3nav,项目名称:c3nav,代码行数:25,代码来源:indexed.py

示例5: _convert_bounds_to_shapely_polygons

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def _convert_bounds_to_shapely_polygons(
        geojson_labels: Dict[str, Dict[str, Any]]
    ) -> Dict[str, BaseGeometry]:
        """
        Takes a dictionary of labels and bounds expressed as lists of geojson shapes
        and returns a dictionary of labels and bounds expressed as Shapely polygons.

        Parameters
        ----------
        geojson_labels : dict
            String -> geojson mappings
        Returns
        -------
        dict
            Dict of labels mapped to lists of shapely polygons

        """
        bounds_dict = {}
        for label, geom in geojson_labels.items():
            try:
                bounds_dict[label] = shape(geom)
            except (AttributeError, IndexError, ValueError) as e:
                raise ValueError(f"Geometry for {label} is not valid: {e}")
        return bounds_dict 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:26,代码来源:label_event_score.py

示例6: _load_geometry

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def _load_geometry(self, geometry_spec):
        if isinstance(geometry_spec, BaseGeometry):
            return geometry_spec

        if isinstance(geometry_spec, dict):
            return SimpleShape(geometry_spec['coordinates'],
                               geometry_spec["type"])

        try:
            return load_wkb(geometry_spec)
        except Exception:
            try:
                return load_wkt(geometry_spec)
            except Exception:
                return None 
开发者ID:tilezen,项目名称:mapbox-vector-tile,代码行数:17,代码来源:encoder.py

示例7: pxbounds

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def pxbounds(self, geom, clip=False):
        """ Returns the bounds of a geometry object in pixel coordinates

        Args:
            geom: Shapely geometry object or GeoJSON as Python dictionary or WKT string
            clip (bool): Clip the bounds to the min/max extent of the image

        Returns:
            list: bounds in pixels [min x, min y, max x, max y] clipped to image bounds
        """

        try:
            if isinstance(geom, dict):
                if 'geometry' in geom:
                    geom = shape(geom['geometry'])
                else:
                    geom = shape(geom)
            elif isinstance(geom, BaseGeometry):
                geom = shape(geom)
            else:
                geom = wkt.loads(geom)
        except:
            raise TypeError ("Invalid geometry object")

        # if geometry doesn't overlap the image, return an error
        if geom.disjoint(shape(self)):
            raise ValueError("Geometry outside of image bounds")
        # clip to pixels within the image
        (xmin, ymin, xmax, ymax) = ops.transform(self.__geo_transform__.rev, geom).bounds
        _nbands, ysize, xsize = self.shape
        if clip:
            xmin = max(xmin, 0)
            ymin = max(ymin, 0)
            xmax = min(xmax, xsize)
            ymax = min(ymax, ysize)

        return (xmin, ymin, xmax, ymax) 
开发者ID:DigitalGlobe,项目名称:gbdxtools,代码行数:39,代码来源:meta.py

示例8: geos_geometrycollection_from_py

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def geos_geometrycollection_from_py(ob):
    """Creates a GEOS GeometryCollection from a list of geometries"""
    L = len(ob)
    N = 2
    subs = (c_void_p * L)()
    for l in range(L):
        assert(isinstance(ob[l], BaseGeometry))
        if ob[l].has_z:
            N = 3
        geom, n = geos_geom_from_py(ob[l])
        subs[l] = geom
    
    return (lgeos.GEOSGeom_createCollection(7, subs, L), N)

# Test runner 
开发者ID:enricofer,项目名称:go2mapillary,代码行数:17,代码来源:collection.py

示例9: shapeup

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def shapeup(self, ob):
        if isinstance(ob, BaseGeometry):
            return ob
        else:
            try:
                return asShape(ob)
            except ValueError:
                return asLineString(ob) 
开发者ID:enricofer,项目名称:go2mapillary,代码行数:10,代码来源:ops.py

示例10: _load_geometry

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def _load_geometry(self, geometry_spec):
        if isinstance(geometry_spec, BaseGeometry):
            return geometry_spec

        if isinstance(geometry_spec, dict):
            return SimpleShape(geometry_spec['coordinates'],
                               geometry_spec["type"])

        try:
            return load_wkb(geometry_spec)
        except:
            try:
                return load_wkt(geometry_spec)
            except:
                return None 
开发者ID:enricofer,项目名称:go2mapillary,代码行数:17,代码来源:encoder.py

示例11: __init__

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def __init__(self, config_file: Path) -> None:
        self.config_file = config_file

        self.polygons: Dict[str, base.BaseGeometry] = {}
        self.elements: Dict[str, List[Airspace]] = defaultdict(list)
        self.airspaces: Dict[str, List[str]] = defaultdict(list)
        self.description: Dict[str, str] = dict()
        self.types: Dict[str, str] = dict()
        self.initialized = False 
开发者ID:xoolive,项目名称:traffic,代码行数:11,代码来源:airspaces.py

示例12: inside_bbox

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def inside_bbox(self, bounds: Union[Airspace, Tuple[float, ...]]) -> "SO6":
        """
        Selects all Flights intersecting the bounding box of the given airspace.

        A tuple (west, south, east, north) is also accepted as a parameter.

        .. code:: python

            >>> bdx_so6 = so6.inside_bbox(nm_airspaces["LFBBBDX"])
            >>> f"before: {len(so6)} flights, after: {len(bdx_so6)} flights"
            before: 11043 flights, after: 1548 flights

        """

        if isinstance(bounds, Airspace):
            bounds = bounds.flatten().bounds

        if isinstance(bounds, base.BaseGeometry):
            bounds = bounds.bounds

        west, south, east, north = bounds

        # the numexpr query is 10% faster than the regular
        # data[data.lat1 >= ...] conjunctions of comparisons
        query = "{0} <= lon1 <= {2} and {1} <= lat1 <= {3}"
        query = query.format(west, south, east, north)

        data = self.data.query(query)

        callsigns: Set[str] = set(data.callsign)

        return SO6(
            self.data.groupby("flight_id").filter(
                lambda data: data.iloc[0].callsign in callsigns
            )
        ) 
开发者ID:xoolive,项目名称:traffic,代码行数:38,代码来源:so6.py

示例13: shape

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def shape(self) -> base.BaseGeometry:
        return linemerge(shape(x["geometry"]) for x in self.geojson()) 
开发者ID:xoolive,项目名称:traffic,代码行数:4,代码来源:runways.py

示例14: clip

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def clip(self, shape: Union["Airspace", base.BaseGeometry]):
        ... 
开发者ID:xoolive,项目名称:traffic,代码行数:4,代码来源:traffic.py

示例15: inside_bbox

# 需要导入模块: from shapely.geometry import base [as 别名]
# 或者: from shapely.geometry.base import BaseGeometry [as 别名]
def inside_bbox(
    geography: T,
    bounds: Union[
        ShapelyMixin, base.BaseGeometry, Tuple[float, float, float, float]
    ],
) -> Optional[T]:
    """Returns the part of the DataFrame with coordinates located within the
    bounding box of the shape passed in parameter.

        The bounds parameter can be:

        - an Airspace,
        - a shapely Geometry,
        - a tuple of floats (west, south, east, north)

    """

    if isinstance(bounds, Airspace):
        bounds = bounds.flatten().bounds

    elif isinstance(bounds, base.BaseGeometry):
        bounds = bounds.bounds

    elif hasattr(bounds, "shape"):
        bounds = bounds.shape.bounds  # type: ignore

    west, south, east, north = bounds

    query = "{0} <= longitude <= {2} and {1} <= latitude <= {3}"
    query = query.format(*bounds)

    return geography.query(query) 
开发者ID:xoolive,项目名称:traffic,代码行数:34,代码来源:airspace.py


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