コード例 #1
0
def DualUnitBall(L):
    #produces the dual unit ball for an element of the MCG
    pts = WalkOnList(L)
    newpts = np.asarray(pts)
    hull = ConvexHull(newpts)
    poly = MultiPoint(pts).convex_hull
    MD = []
    for i in hull.vertices:
        vertex = np.asarray(pts[i])
        neighbours = [vertex + (0,1), vertex + (1,1), vertex + (1,0), vertex + (1,-1), vertex + (0,-1), vertex + (-1,-1), vertex + (-1,0), vertex + (-1,1)]
        a1 = Point(tuple(neighbours[0]))
        a2 = Point(tuple(neighbours[1]))
        a3 = Point(tuple(neighbours[2]))
        a4 = Point(tuple(neighbours[3]))
        a5 = Point(tuple(neighbours[4]))
        a6 = Point(tuple(neighbours[5]))
        a7 = Point(tuple(neighbours[6]))
        a8 = Point(tuple(neighbours[7]))
        if poly.intersects(a1):
            if poly.intersects(a2) and poly.intersects(a3):
                MD.append(vertex + (0.5, 0.5))
            if poly.intersects(a7) and poly.intersects(a8):
                MD.append(vertex + (-0.5, 0.5))
        if poly.intersects(a5):
            if poly.intersects(a3) and poly.intersects(a4):
                MD.append(vertex + (0.5, -0.5))
            if poly.intersects(a6) and poly.intersects(a7):
                MD.append(vertex + (-0.5, -0.5))
    return(MD)
コード例 #2
0
class Region(object):
    @classmethod
    def from_dict(cls, data):
        A = np.array(data['A'])
        B = np.array([data['B']]).T
        vertices = np.array(data['points'])
        new_reg = cls(A=A, B=B, vertices=vertices, region_id=data['region_id'])
        return new_reg

    @classmethod
    def from_vertices(cls, vertices, region_id):
        A, B = compute_hull(vertices)
        return cls(A, B, vertices, region_id)

    def __init__(self, A, B, vertices, region_id):
        # Vertices are arrays N x 2
        self.A = A
        self.B = B
        self.vertices = vertices
        #self.iris_region = iris_region
        self.region_id = region_id
        self.poly = MultiPoint(vertices).convex_hull

    def intersects(self, other_region):
        return self.poly.intersects(other_region.poly)

    def contains_point(self, point):
        return self.poly.intersects(Point(point))

    def draw(self, ax=None, **kwargs):
        if ax is None:
            ax = plt.gca()
        hull = scipy.spatial.ConvexHull(self.vertices)
        kwargs.setdefault("facecolor", "none")
        return [
            ax.add_patch(plt.Polygon(xy=self.vertices[hull.vertices],
                                     **kwargs))
        ]

    def __repr__(self):
        return "<Region {}>".format(self.region_id)

    # def __eq__(self, other):
    #     if isinstance(other, self.__class__):
    #         return check_equal_vertices(self.vertices, other.vertices, tol=1e-1)
    #     return NotImplemented
    # def __ne__(self, other):
    #     """Define a non-equality test"""
    #     if isinstance(other, self.__class__):
    #         return not self.__eq__(other)
    #     return NotImplemented

    def to_dict(self):
        ir = {}
        ir['points'] = self.vertices.tolist()  # (xi,yi) each line
        ir['A'] = self.A.tolist()  # row by row
        ir['B'] = self.B[:, 0].tolist()  # transpose of B
        return ir
コード例 #3
0
def post_process_coords(
    corner_coords: List, imsize: Tuple[int, int] = (1600, 900)
) -> Union[Tuple[float, float, float, float], None]:
    """
    Get the intersection of the convex hull of the reprojected bbox corners and the image canvas, return None if no
    intersection.
    :param corner_coords: Corner coordinates of reprojected bounding box.
    :param imsize: Size of the image canvas.
    :return: Intersection of the convex hull of the 2D box corners and the image canvas.
    """
    polygon_from_2d_box = MultiPoint(corner_coords).convex_hull
    img_canvas = box(0, 0, imsize[0], imsize[1])

    if polygon_from_2d_box.intersects(img_canvas):
        img_intersection = polygon_from_2d_box.intersection(img_canvas)
        intersection_coords = np.array(
            [coord for coord in img_intersection.exterior.coords])

        min_x = min(intersection_coords[:, 0])
        min_y = min(intersection_coords[:, 1])
        max_x = max(intersection_coords[:, 0])
        max_y = max(intersection_coords[:, 1])

        return min_x, min_y, max_x, max_y
    else:
        return None
コード例 #4
0
def project_camera( corners, cam_model ):
    """ -------------------------------------------------------------------------------------------------------------
    Project a 3D bounding box into camera (image) space (the origin of the camera space is top left corner).

    This function is taken from post_process_coords() in
    nuscenes-devkit/python-sdk/nuscenes/scripts/export_2d_annotations_as_json.py
    
    corners:        [np.array] the 8 corners of the 3D box
    cam_model:      ???

    return:         [tuple of int] ??? INT OR FLOAT
                    coordinates of the 2D box, None if the object is outside the camera frame
    ------------------------------------------------------------------------------------------------------------- """
    front       = np.argwhere( corners[ 2, :] > 0 )         # check which corners are in front of the camera
    corners     = corners[ :, front.flatten() ]             # and take those only

    corners_p   = view_points( corners, cam_model, True )   # project the 3D corners in camera space
    corners_p   = corners_p.T[ :, : 2 ]                     # take only X and Y in camera space

    poly        = MultiPoint( corners_p.tolist() ).convex_hull
    img         = box( 0, 0, img_size[ 0 ], img_size[ 1 ] )
    if not poly.intersects( img ):
        return None                                         # return None if the projection is out of the camera frame

    inters  = poly.intersection( img )
    coords  = np.array( [ c for c in inters.exterior.coords ] )
    min_x   = min( coords[ :, 0 ] )
    min_y   = min( coords[ :, 1 ] )
    max_x   = max( coords[ :, 0 ] )
    max_y   = max( coords[ :, 1 ] )

    return min_x, min_y, max_x, max_y
    def detectObstacle(self, rrt, path, newObstacle):
        '''
        Function to detect whether obstacle is actually bloocking the path or not

        Parameters
        ----------
        rrt : object of RRT()
            Object which stores information of the tree expanded by RRT*.
        path : list(int)
            List of indices of the nodes in the tree which form the path traversed
            by the robot.
        newObstacle : Polygon
            The dynamic obstacle in question.

        Returns
        -------
        bool
            A boolean which determines whetehr obstacle intersects the path (TRUE)
            or not (FALSE).

        '''
        points = []
        points = rrt.nodes[path,0:2]
        points_shapely = MultiPoint(points)
        if points_shapely.intersects(newObstacle):
            return True
        else:
            return False
コード例 #6
0
    def _anno_to_2d_bbox(self, anno, pc_file, cam_front, lidar_top,
                         ego_pose_cam, ego_pose_lidar, cam_intrinsic):
        # Make pixel indexes 0-based
        dists = []
        nusc_box = self.nusc.get_box(anno['token'])

        # Move them to the ego-pose frame.
        nusc_box.translate(-np.array(ego_pose_cam['translation']))
        nusc_box.rotate(Quaternion(ego_pose_cam['rotation']).inverse)

        # Move them to the calibrated sensor frame.
        nusc_box.translate(-np.array(cam_front['translation']))
        nusc_box.rotate(Quaternion(cam_front['rotation']).inverse)

        dists.append(np.linalg.norm(nusc_box.center))
        # Filter out the corners that are not in front of the calibrated sensor.
        #Corners is a 3x8 matrix, first four corners are the ones facing forward, last 4 are ons facing backward
        #(0,1) top, forward
        #(2,3) bottom, forward
        #(4,5) top, backward
        #(6,7) bottom, backward
        corners_3d = nusc_box.corners()
        #Getting first 4 values of Z
        dists.append(np.mean(corners_3d[2, :4]))
        # z is height of object for ego pose or lidar
        # y is height of object for camera frame
        #TODO: Discover why this is taking the Z axis
        in_front = np.argwhere(corners_3d[2, :] > 0).flatten()
        corners_3d = corners_3d[:, in_front]
        #print(corners_3d)
        #above    = np.argwhere(corners_3d[2, :] > 0).flatten()
        #corners_3d = corners_3d[:, above]
        # Project 3d box to 2d.
        corner_coords = view_points(corners_3d, cam_intrinsic,
                                    True).T[:, :2].tolist()
        #print(corner_coords)
        # Keep only corners that fall within the image.

        polygon_from_2d_box = MultiPoint(corner_coords).convex_hull
        img_canvas = box(0, 0, self._imwidth - 1, self._imheight - 1)

        if polygon_from_2d_box.intersects(img_canvas):
            img_intersection = polygon_from_2d_box.intersection(img_canvas)
            intersection_coords = np.array(
                [coord for coord in img_intersection.exterior.coords])

            min_x = min(intersection_coords[:, 0])
            min_y = min(intersection_coords[:, 1])
            max_x = max(intersection_coords[:, 0])
            max_y = max(intersection_coords[:, 1])
            #print('contained pts {}'.format(contained_points))
            return [min_x, min_y, max_x, max_y], dists
        else:
            return None, dists
コード例 #7
0
def check_on_boundaries(lon_min, lon_max, lat_min, lat_max, point_dict):
    # core function to check if the data falls inside the user geographic boundaries

    # create the geographic polygon containing the user input searching area:
    data_longitudes = [x["Longitude"] for x in point_dict]
    data_latitudes = [x["Latitude"] for x in point_dict]
    data_lat_lon_coords = tuple(zip(data_latitudes, data_longitudes))
    data_polygon_obj = MultiPoint(data_lat_lon_coords).convex_hull

    # create the geographic polygon containing the current data
    user_lat_lon_coords = tuple(
        zip([lat_min, lat_min, lat_max, lat_max],
            [lon_min, lon_max, lon_min, lon_max]))
    user_polygon_obj = MultiPoint(user_lat_lon_coords).convex_hull

    # check if the data polygon is at least partially intersected by the user polygon
    boundaries_are_matching = user_polygon_obj.intersects(data_polygon_obj)

    return boundaries_are_matching
コード例 #8
0
    def __findCrossedAirspaces(self):
        flightPoints = []
        for fix in self.igcFlight.fixes:
            flightPoints.append((fix.lon, fix.lat))
        trackPoints = MultiPoint(flightPoints)

        crossedAirspacesDict = {}

        for i, feature in enumerate(self.geojsonAirspace.features):
            coords = np.array(feature.geometry.coordinates[0])
            coords2 = np.empty((len(coords), ), dtype=object)
            coords2[:] = [tuple(i) for i in coords]

            polygon = Polygon(coords2.tolist())

            inside = trackPoints.intersects(polygon)
            if inside:
                crossedAirspacesDict[i] = polygon
                #print(f"Point crosses airspace (Horizontal only): {i} # {feature.properties.CLASS} # {feature.properties.NAME} # {feature.properties.CEILING} / {feature.properties.FLOOR}" )
                airspaceCeiling = stringToMeter(feature.properties.CEILING)
                airspaceFloor = stringToMeter(feature.properties.FLOOR)
        return crossedAirspacesDict
コード例 #9
0
    def assign_label(self, tile_starts, tile_ends, regions, region_labels):
        ''' calculates overlap of tile with xml regions and creates dictionary based on unique labels '''

        tile_box = [tile_starts[0],
                    tile_starts[1]], [tile_starts[0], tile_ends[1]
                                      ], [tile_ends[0], tile_starts[1]
                                          ], [tile_ends[0], tile_ends[1]]
        tile_box = list(tile_box)
        tile_box = MultiPoint(tile_box).convex_hull

        tile_label = {}
        # create a dictionary of label/value pairs: returns percent of tile containing unique
        for label in set(region_labels):

            # grab regions that correspond to this label
            label_list = [i for i, e in enumerate(region_labels) if e == label]
            labels = tuple(regions[i] for i in label_list)

            # loop over every region associated with a given label, sum the overlap
            box_label = False  # initialize
            ov = 0  # initialize
            for reg in labels:
                poly = Polygon(reg)
                if poly.is_valid == False:
                    poly = poly.buffer(0)
                poly_label = tile_box.intersects(poly)
                if poly_label == True:
                    box_label = True
                    ov_reg = tile_box.intersection(poly)
                    ov += ov_reg.area / tile_box.area

            if box_label == True:
                tile_label[label] = ov

        # p.s. if you are curious, you can plot the polygons by the following
        #   plt.plot(*poly.exterior.xy) and plt.plot(*tile_box.exterior.xy)
        return tile_label
コード例 #10
0
            metrics1 = metrics1 / len(better_matches)
            f1.write(str(metrics1) + '\n')

            points = list()
            for i in range(0, 4):
                l = list()
                l.append(dst[i][0][0])
                l.append(dst[i][0][1])
                points.append(l)
            polygon = MultiPoint(points).convex_hull
            error1 = list()
            x2_1 = np.float32([x.pt for x in matched2_1])
            for i in range(0, len(matched2_1)):
                p = shapely.geometry.Point(x2_1[i])

                k = polygon.intersects(p)
                error1.append(k)
            metrics2 = sum(error1) / len(error1)

            f3.write(str(metrics2) + '\n')
    else:
        src_pts = np.float32([x.pt for x in matched1]).reshape(-1, 1, 2)
        dst_pts = np.float32([x.pt for x in matched2]).reshape(-1, 1, 2)
        M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC, 6.0)
        if M is None:
            f1.write('findHomography error\n')
            f3.write('findHomography error\n')
        else:
            matchesMask = mask.ravel().tolist()

            pts = np.float32([[167, 290], [167, 1016], [719, 1016],
コード例 #11
0
ファイル: Demo1.py プロジェクト: Jondamer/MarineTraffic
print(polygon3.area)
# 2 3多边形是否相交
# b = polygon2.contains(polygon3)
# print('2和3多边形的', b)
# c = polygon2.covers(polygon3)
# print('c', c)
# d = polygon3.crosses(polygon2)
# print('d', d)
#
# e = polygon2.disjoint(polygon3)
# print('e', e)
# f = polygon3.intersection(polygon2)
# print('f', f)
# g = polygon2.intersects(polygon3)
# print('g', g)
h = polygon3.intersects(polygon4)
print('h', h)
if (h):
    u = cascaded_union([polygon3, polygon4])
print(u.area)
# print(u.boundary)
# print(u.centroid)

# df = pd.read_csv('../cu2/cu-1', header=None)
# df = df.iloc[:, 0:2]
# train_data = np.array(df)  # np.ndarray()
# train_x_list = train_data.tolist()  # list
# # print(train_x_list)
# # print(type(train_x_list))
# points = MultiPoint(train_x_list)
# py1 = points.convex_hull