當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。