示例#1
0
    def create_polygon(self, shape_polygon, alpha=np.nan):
        """ Creates a polygon surrounding a cloud of shapepoints

        :param shape_polygon: string, path to save the shapefile
        :param alpha: float, excentricity of the alphashape (polygon) to be created

        :returns: saves the polygon (*.shp) with the selected filename
        """
        if np.isfinite(alpha):
            try:
                polygon = alphashape.alphashape(self.gdf, alpha)
                polygon.crs = self.crs
                polygon.to_file(shape_polygon)
                print('Polygon *.shp saved successfully.')
            except FileNotFoundError as e:
                print(e)
        else:
            try:
                polygon = alphashape.alphashape(self.gdf)
            except FileNotFoundError as e:
                print(e)
            else:
                polygon.crs = self.crs
                polygon.to_file(shape_polygon)
                print('Polygon *.shp saved successfully.')
示例#2
0
def cocave_hull():
    """
    Using alphashape() method from library to get both convex-hull points(alpha ≈ 0) and alpha shape points(high alpha value).
    Deleting those points in alpha shape that are within the certain radius of each point in convex-hull.
    Uning OpenCV approxPolyDP() to generate a fitted polygon.
    """
    al_shape = alphashape.alphashape(data, 0.02)
    hull_pts = al_shape.exterior.coords.xy
    x = hull_pts[0]
    y = hull_pts[1]
    x, y = fine_tune(x, y, 0.8)

    al_shape2 = alphashape.alphashape(data, 0.1285)
    hull_pts2 = al_shape2.exterior.coords.xy
    x5 = hull_pts2[0]
    y5 = hull_pts2[1]
    x5, y5 = fine_tune(x5, y5, 0.8)

    for i in range(len(x)):
        for j in range(len(x5) - 1, -1, -1):
            dist = np.sqrt((x[i] - x5[j])**2 + (y[i] - y5[j])**2)
            if (dist < 15):
                x5 = np.delete(x5, j)
                y5 = np.delete(y5, j)
    return x5, y5
示例#3
0
def surface_plot(fn):
    pts = np.load(fn)
    Cl = pts[:-1, 0]
    Cm = pts[:-1, 1]
    Cn = pts[:-1, 2]
    ClCn = []
    ClCm = []
    CnCm = []
    for i in range(len(Cl)):
        ClCn.append((Cl[i], -Cn[i]))
        ClCm.append((Cl[i], Cm[i]))
        CnCm.append((-Cn[i], Cm[i]))

    alpha_ClCn = alphashape.alphashape(ClCn, 5.0)
    fig_ClCn, ax_ClCn = plt.subplots()
    ax_ClCn.scatter(*zip(*ClCn))
    ax_ClCn.scatter(pts[-1, 0], pts[-1, 2], color='r')
    ax_ClCn.add_patch(PolygonPatch(alpha_ClCn, alpha=0.2, color='g'))

    alpha_ClCm = alphashape.alphashape(ClCm, 2.0)
    fig_ClCm, ax_ClCm = plt.subplots()
    ax_ClCm.scatter(*zip(*ClCm))
    ax_ClCm.scatter(pts[-1, 0], pts[-1, 1], color='r')
    ax_ClCm.add_patch(PolygonPatch(alpha_ClCm, alpha=0.2, color='g'))

    alpha_CnCm = alphashape.alphashape(CnCm, 5.0)
    fig_CnCm, ax_CnCm = plt.subplots()
    ax_CnCm.scatter(*zip(*CnCm))
    ax_CnCm.scatter(pts[-1, 2], pts[-1, 1], color='r')
    ax_CnCm.add_patch(PolygonPatch(alpha_CnCm, alpha=0.2, color='g'))
示例#4
0
def hull_about(inside_points, outside_points, max_alpha, min_alpha):
    alpha = max_alpha
    shape = alphashape.alphashape(inside_points, alpha)
    caught = [shapely.geometry.point.Point(p) for p in outside_points]
    caught = [p for p in caught if shape.contains(p)]
    while caught:
        alpha *= 0.8
        if alpha < min_alpha:
            print("Min alpha reached")
            break
        shape = alphashape.alphashape(inside_points, alpha)
        caught = [p for p in caught if shape.contains(p)]
    return shape
示例#5
0
def generate_image_and_stats(data, cluster_coords, regions_image,
                             optional_params, axes):
    """Adds cluster shape to shapes image and also returns regionprops of that shape"""
    one_region_image = np.zeros((data["dimensions"][0], data["dimensions"][1]),
                                np.uint8)
    concave_hull = alphashape.alphashape(cluster_coords)
    border_points = concave_hull.exterior.coords
    list_array = []
    for coord in border_points:
        list_array.append(coord)
    # border_points = cluster_coords[spatial.ConvexHull(cluster_coords).vertices]
    hull = spatial.ConvexHull(cluster_coords)
    border_points = np.array(list_array, dtype='int32')

    regions_image = cv2.fillPoly(regions_image, np.int32([border_points]),
                                 (255, 255, 255))
    one_region_image = cv2.fillPoly(one_region_image,
                                    np.int32([border_points]), 255)

    labeled_image = label(one_region_image, background=0)
    properties = regionprops(labeled_image)
    degrees = math.degrees(properties[0].orientation)
    parameters = ((properties[0].centroid[1], properties[0].centroid[0]),
                  (int(properties[0].major_axis_length),
                   int(properties[0].minor_axis_length)), float(degrees))
    regions_image = cv2.ellipse(regions_image, parameters, (0, 0, 255))
    add_outline(border_points, axes, optional_params, properties)
    ellipticity = compute_ellipticity_area_based(data, border_points)
    return regions_image, properties, ellipticity, hull.area, hull.volume
示例#6
0
def get_coor(image):
    X, Y, Z = de_hole1(image)
    Xk = roi(image)[0]
    arr_X = []
    arr_Y = []
    for z in Z:
        for x in X:
            if z[0] == x[0] or z[1] == z[1]:
                if check(z, x):
                    arr_X.append(z)
    for z in Z:
        for x in Y:
            if z[0] == x[0] or z[1] == z[1]:
                if check(z, x):
                    arr_Y.append(z)
    output = []
    arr = arr_X + arr_Y
    for x in arr:
        if x not in output:
            output.append(x)
    alpha = 0.3 * alphashape.optimizealpha(output)
    hull = alphashape.alphashape(output, alpha)
    hull_pts = hull.exterior.coords.xy
    arr = []
    for i in range(len(hull_pts[0])):
        arr.append([int(hull_pts[0][i]), int(hull_pts[1][i])])
    #r1=[[img[0]+Xk[0],img[1]+Xk[1]] for img in arr]
    return arr
示例#7
0
def calculate_concave_hull_of_points(pixel_coords, alpha=0.2):
    """
        Return the alpha shape of the highlighted pixels using the alpha
        entered by the user.
        :param pixel_coords: the coordinates of the contour pixels
        :return: List of lists of points ordered to form polygon(s).
        """
    # Get all the pixels in the drawing window's list of highlighted
    # pixels, excluding the removed pixels.
    target_pixel_coords = [(item[0] + 1, item[1] + 1) for item in pixel_coords]
    # Calculate the concave hull of the points.
    # TODO: auto-generate an optimized alpha value
    # alpha = 0.95 * alphashape.optimizealpha(points)
    hull = target_pixel_coords
    try:
        hull = alphashape(target_pixel_coords, alpha)
    except QhullError:
        pass
    polygon_list = []
    if isinstance(hull, Polygon):
        polygon_list.append(hull_to_points(hull))
    elif isinstance(hull, MultiPolygon):
        for polygon in hull:
            polygon_list.append(hull_to_points(polygon))
    return polygon_list
示例#8
0
def get_alphashape(pdb, chain=None, plot=False):
    '''
    Returns an AlphaShape object of a pdb file, outlining its general
    shape for use in a clash filter.
    '''
    if chain:
        atoms = prody.parsePDB(pdb, chain=chain)
    else:
        atoms = prody.parsePDB(pdb)
        atoms = atoms.select('not chain A')
    # For some reason there is a level which is not populated. This may
    # be for proteins w/ multiple chains.
    coordsets = atoms.getCoordsets()
    coords = []
    for coordset in coordsets:
        coords.extend(coordset)

    # coords = [(0., 0.), (0., 1.), (1., 1.), (1., 0.), (0.5, 0.5)]

    alpha_shape = alphashape.alphashape(coords, 0.18)

    if plot:
        helix = prody.parsePDB(pdb, chain='A')
        helixcoords = helix.getCoordsets()[0]
        fig = plt.figure()
        # ax = fig.add_subplot(projection='3d')
        ax = Axes3D(fig)
        ax.scatter(*zip(*coords))
        ax.scatter(*zip(*helixcoords))
        # # ax.add_patch(PolygonPatch(alpha_shape, alpha=0.2))
        ax.plot_trisurf(*zip(*alpha_shape.vertices),
                        triangles=alpha_shape.faces,
                        alpha=0.3)
        plt.show()
    return alpha_shape
示例#9
0
def _testalpha(points, alpha):
    """
    Evaluates an alpha parameter.

    This helper function creates an alpha shape with the given points and alpha
    parameter.  It then checks that the produced shape is a Polygon and that it
    intersects all the input points.

    Args:
        points (``shapely.geometry.Multipoint``): data points
        alpha (float): alpha value

    Returns:
        bool: True if the resulting alpha shape is a single polygon that
            intersects all the input data points.
    """
    try:
        from alphashape import alphashape
    except ImportError:
        from .alphashape import alphashape
    polygon = alphashape(points, alpha)
    if isinstance(polygon, shapely.geometry.polygon.Polygon) and all(
        [polygon.intersects(point) for point in points]):
        return True
    else:
        return False
示例#10
0
def export_alphashape(path,files,params):
    for idx in range(len(files)):
        file_path = path + files[idx] + ext
        points = []
        with open(file_path) as f:
            l_strip = [s.strip() for s in f.readlines()]
            for l in l_strip:
                if " " in l:
                    p2 = l.split(" ")
                    points.append([float(p2[0]), float(p2[2])])

        alpha_shape = alphashape.alphashape(points, params[idx])

        x, y = alpha_shape.exterior.coords.xy
        num = len(x)
        out_list = []
        for i in range(num):
            out_list.append(str(x[i])+" "+str(y[i]))
            # print("clippoints["+str(i)+"].x =" + str(x[i])+";")
            # print("clippoints["+str(i)+"].y =" + str(y[i])+";")

        path_w = "../../resources/alpha_shapes/"+ files[idx] + ext
        with open(path_w, mode='w') as f:
            f.write(str(num)+"\n")
            f.write('\n'.join(out_list))
            print("write file:"+files[idx])
示例#11
0
def get_coor(img):
    (x,y),img=roi(img)
    median = cv2.GaussianBlur(image,(5,5),0)
    median = cv2.medianBlur(median,15)
    hsv = cv2.cvtColor(median, cv2.COLOR_BGR2HSV)
    lower_blue=np.array([91,111,68])
    upper_blue=np.array([115,255,255])
    mask=cv2.inRange(hsv,lower_blue,upper_blue)
    edges = cv2.Canny(mask,100,200)
    (contours,_) = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    #hull = cv2.convexHull(contours,returnPoints = False)
    #print(hull)
    arr=[]
    for contour in contours:
        (x,y,w,h) = cv2.boundingRect(contour)
        arr.append([x,y])
        arr.append([x+w,y])
        arr.append([x,y+h])
        arr.append([x+w,y+h])
    alpha = 0.4 * alphashape.optimizealpha(arr)
    hull = alphashape.alphashape(arr, alpha)
    hull_pts = hull.exterior.coords.xy
    arr=[]
    for i in range(len(hull_pts[0])):
        arr.append([int(hull_pts[0][i]),int(hull_pts[1][i])])
    results=[(np.array(z)+np.array([x,y])).tolist() for z in arr]
    return results
def export_cluster_contour(geojson_path, alpha=None):
    m = gpd.read_file(geojson_path)
    cluster_label = m.label.unique()
    if -1 in cluster_label:
        cluster_label = np.delete(cluster_label, np.where(cluster_label == -1))

    result = gpd.GeoDataFrame([])

    for i in tqdm.tqdm(cluster_label):
        print(i)
        points = m[m.label == i].geometry.centroid
        if len(points.unique()) < 4:
            # print('cluster: ' + str(i) + 'doesn\'t work')
            continue
        result = result.append(
            {
                'label': i,
                'geometry': alphashape.alphashape(points=points, alpha=alpha)
            },
            ignore_index=True)

    result.plot()
    plt.show()

    result.to_file(geojson_path[:-8] + "_cluster_contour.geojson",
                   driver='GeoJSON')
    def __getBoundary__(self):
        ''' 
        Sets object attributes: boundaryCurve, _sortIdx_
        - Internal function, should not be used in isolation outside core.py
        - Uses the alpha shape algorithm to get the boundary nodes - from alphashape library
        - boundaryCurve stores the points (in order) which make up the boundary, as complex numbers
        - _sortIdx_ is an internal attribute, index order to sort boundary cells, for connecting them correctly
        '''

        # Do alphashape import here, not needed anywhere else
        import alphashape

        # Get points into array format
        points = np.column_stack([self.coords.real, self.coords.imag])

        # Use alpha shape to get the bounding curve 
        # an alpha value of 0.1 performs well with nodes arranged in a circle or rectangle
        # Basically just a small value over 0 seems to generalise well to simple shapes without ignoring the points on the sides of rectangle - since alpha=0 returns the convex hull
        hull = alphashape.alphashape(points,alpha=0.1)

        # Extract the actual coordinates into a numpy array
        hull_pts = hull.boundary.coords.xy
        hull_pts = np.array([hull_pts[0],hull_pts[1]])

        # Put into complex format and assign into class attribute
        self.boundaryCurve = hull_pts[0] + 1j * hull_pts[1]

        # Get indices of these points within the full coords array
        self._sortIdx_ = [np.where(self.coords == point)[0][0] for point in self.boundaryCurve]
def _create_mask(binary_data, slices=0):
    result = np.zeros(binary_data[slices].shape)

    coord_x, coord_y = np.where(binary_data[slices] > 0)
    lst_pts = np.concatenate((coord_x[:, np.newaxis], coord_y[:, np.newaxis]),
                             axis=1)

    alpha_shape = alphashape.alphashape(lst_pts[::16], 0.1)

    if alpha_shape.type == 'MultiPolygon':
        for alpha in alpha_shape:
            if alpha.area > 20000:
                x, y = alpha.exterior.coords.xy
                rr, cc = polygon(np.asarray(x, dtype=np.int),
                                 np.asarray(y, dtype=np.int))
                result[rr, cc] = 1
    elif alpha_shape.type == 'GeometryCollection':
        pass

    else:
        x, y = alpha_shape.exterior.coords.xy
        rr, cc = polygon(np.asarray(x, dtype=np.int),
                         np.asarray(y, dtype=np.int))
        result[rr, cc] = 1
    return result
示例#15
0
def _testalpha(points: Union[List[Tuple[float]], np.ndarray], alpha: float):
    """
    Evaluates an alpha parameter.

    This helper function creates an alpha shape with the given points and alpha
    parameter.  It then checks that the produced shape is a Polygon and that it
    intersects all the input points.

    Args:
        points: data points
        alpha: alpha value

    Returns:
        bool: True if the resulting alpha shape is a single polygon that
            intersects all the input data points.
    """
    try:
        from alphashape import alphashape
    except ImportError:
        from .alphashape import alphashape
    polygon = alphashape(points, alpha)
    if isinstance(polygon, shapely.geometry.polygon.Polygon):
        if not isinstance(points, MultiPoint):
            points = MultiPoint(list(points))
        return all([polygon.intersects(point) for point in points])
    elif isinstance(polygon, trimesh.base.Trimesh):
        return len(polygon.faces) > 0 and all(
            trimesh.proximity.signed_distance(polygon, list(points)) >= 0)
    else:
        return False
示例#16
0
    def next_update(self, timestep, states):
        agents = states['agents']
        points = [agent['boundary']['location'] for agent in agents.values()]
        points = [tuple(point) for point in points if np.all(~np.isnan(point))]
        alpha_shape = alphashape.alphashape(set(points),
                                            self.parameters['alpha'])
        if isinstance(alpha_shape, Polygon):
            shapes = [alpha_shape]
        elif isinstance(alpha_shape, (Point, LineString)):
            # We need at least 3 cells to form a colony polygon
            shapes = []
        else:
            assert isinstance(alpha_shape, (MultiPolygon, GeometryCollection))
            shapes = list(alpha_shape)

        agent_colony_map = gen_agent_colony_map(agents, shapes)

        # Calculate colony surface areas
        areas = [shape.area for shape in shapes]

        # Calculate colony major and minor axes based on bounding
        # rectangles
        major_axes = []
        minor_axes = []
        for shape in shapes:
            if isinstance(shape, Polygon):
                major, minor = major_minor_axes(shape)
                major_axes.append(major)
                minor_axes.append(minor)
            else:
                major_axes.append(0)
                minor_axes.append(0)

        # Calculate colony circumference
        circumference = [shape.length for shape in shapes]

        # Calculate colony masses and cell surface areas
        mass = [0] * len(shapes)
        cell_area = [0] * len(shapes)
        for agent_id, agent_state in agents.items():
            if agent_id not in agent_colony_map:
                # We ignore agents not in any colony
                continue
            colony_index = agent_colony_map[agent_id]
            agent_mass = get_in(agent_state, ('boundary', 'mass'), 0)
            mass[colony_index] += agent_mass

        return {
            'colony_global': {
                'surface_area': areas,
                'major_axis': major_axes,
                'minor_axis': minor_axes,
                'circumference': circumference,
                'mass': mass,
            }
        }
示例#17
0
def return_concave_hull(points):
    # use alphashape library
    #points=[(0., 0.), (0., 1.), (1., 1.), (1., 0.),
    #      (0.5, 0.25), (0.5, 0.75), (0.25, 0.5), (0.75, 0.5)]
    #points = np.array([[10,10],[20,10],[10,20],[20,20]])
    #alpha = 0.50*alphashape.optimizealpha(points)
    hull = alphashape.alphashape(points, 0.05)  #tune this as needed
    hull_pts = hull.exterior.coords.xy
    pts = np.vstack((hull_pts[0], hull_pts[1])).T
    return pts
 def getConcaveHull(self):
     if self.dim == 3:
         raise ValueError(
             "3D point cloud concave hull calculation not provided.")
     if self.concave_hull is None:
         try:
             self.concave_hull = alphashape(self.getPoints(), 2)
         except QhullError:
             self.concave_hull = None
     return self.concave_hull
示例#19
0
def get_coor12(image):
    X, Y, Z = de_hole12(image)
    if de_hole1(image) is not None:
        Xk = roi(image)[0]
        arr_X = []
        arr_Y = []
        for z in Z:
            for x in X:
                if z[0] == x[0] or z[1] == z[1]:
                    if check(z, x):
                        arr_X.append(z)
        for z in Z:
            for x in Y:
                if z[0] == x[0] or z[1] == z[1]:
                    if check(z, x):
                        arr_Y.append(z)
        output = []
        arr = arr_X + arr_Y
        for x in arr:
            if x not in output:
                output.append(x)
        alpha = 0.3 * alphashape.optimizealpha(output)
        hull = alphashape.alphashape(output, alpha)
        hull_pts = hull.exterior.coords.xy
        arr = []
        for i in range(len(hull_pts[0])):
            arr.append([int(hull_pts[0][i]), int(hull_pts[1][i])])

        def check(coor1, coor2):
            a = abs(coor1[0] - coor2[0]) + abs(coor2[1] - coor1[1])
            if a > 10:
                return False
            return True

        hull_pts = hull.exterior.coords.xy
        arr1 = []
        for i in range(len(hull_pts[0])):
            arr1.append([int(hull_pts[0][i]), int(hull_pts[1][i])])
        print(arr1)
        t = {}
        for i in range(len(arr1) - 1):
            t[i] = [arr1[i + 1][0], arr1[i][1]]
        print(t)
        count = 1
        for i in range(len(t)):
            if t[i] is not arr1:
                for v in arr:
                    if check(t[i], v):
                        arr1.insert(count, t[i])
                        count = count + 1
                        print(t[i])
                        break
            count = count + 1
    return arr1
示例#20
0
    def get_octomap_alpha_shape(self, map_2d, alpha):
        '''
        获取某高度以上的轮廓多边形

        map_2d : 2d 的散点地图  类型: [(x,y),(x,y)...]
        alpha : 控制生成的边界  类型:任意常数

        return : 多个各个边界点  类型:[((x,y),(x,y)..),((x,y),(x,y)..)...]
        它的原理可以想象成一个半径为α 的圆在点集 s 外滚动,当α足够大时,
        这个圆就不会滚到点集内部,其滚动的痕迹就是这个点集的边界线。因此,当α
        值很小,则每个点都是边界;如果α 很大(α →∞ )时,则求出的边界线为
        点集 s 的凸包。
        '''

        points = list(map_2d)
        # 当获取到的点云数据大于2 时才能求他的边缘
        if len(points) > 2:
            # print (points)
            # 获取点云的边缘多边形

            time1 = time()
            try:
                alpha_shape = alphashape.alphashape(points, alpha)
            except Exception:
                print("异常")
                return self.bank_muiltpolygon

            time2 = time()

            print("alpha_shape_time1:  ", round((time2 - time1), 2))
            polygon_list = []
            if type(alpha_shape) == Polygon:
                polygon_list.append(alpha_shape)

            else:
                for polygon in alpha_shape:
                    polygon_list.append(polygon)

            for p in self.bank_muiltpolygon:
                polygon = Polygon(p)
                polygon_list.append(polygon)
            # 将多个多边形进行融合
            polygons = cascaded_union(polygon_list)
            # 曲线平滑处理
            polygons = polygons.simplify(0.6, preserve_topology=False)
            if type(polygons) == Polygon:
                self.bank_muiltpolygon = MultiPolygon([polygons])
            else:
                self.bank_muiltpolygon = polygons

            # print (self.bank_muiltpolygon)
            return self.bank_muiltpolygon
        else:
            return self.bank_muiltpolygon
示例#21
0
def _poly_hull(map_2d: np.ndarray, threshold: float, alpha: float) -> List[sg.Polygon]:
    points = np.argwhere(map_2d > threshold)
    try:
        polys = alphashape.alphashape(points, alpha)
    except sp.QhullError:
        return []
    if isinstance(polys, sg.MultiPolygon):
        return [p for p in polys]
    elif isinstance(polys, sg.Polygon):
        return [polys]
    else:
        return []
示例#22
0
def polygon_from_shapepoints(shapepoints, polygon, alpha=np.nan):
    """
    Create a polygon around a cloud of shapepoints
    :param shapepoints: shape points filename, including directory.
    :param polygon: target filename, including directory.
    :param alpha: coefficient to adjust; the lower it is, the more slim will be the polygon.
    :output: saves the polygon shapefile in the selected path
    """
    gdf = geopandas.read_file(shapepoints)

    # If the user doesnt select an alpha value, the alpha will be optimized automatically.
    if np.isfinite(alpha):
        try:
            poly = alphashape.alphashape(gdf, alpha)
        except FileNotFoundError as e:
            print(e)
    else:
        try:
            poly = alphashape.alphashape(gdf)
        except FileNotFoundError as e:
            print(e)
        else:
            poly.to_file(polygon)
示例#23
0
def create_concave_polygon(gdf):
    """[summary] Takes in a dataframe sub frame of an area and creates a
    polygon using alphashape, to create a concave_hull of the given area.
    Arguments:
        df {[geopandas]} -- [description]

        alphashape_Value {[int]} -- set to 2.3
                            [the granuality of the concave hull.]
    Returns:
        [shapely.geometry.polygon.Polygon] -- [a shapely polygon, alphashape]
    """
    #  set to 2.3 [the granuality of the concave hull.]
    polygon = alphashape.alphashape(gdf['Geometry'], 2.1)
    return polygon
示例#24
0
def join_polygons(polygons, loc=''):
    """construct concave hull (alpha shape) from input polygons"""
    # compoundp = unary_union(polygons)
    # jointp = compoundp.convex_hull
    LOG = getLogger('processor.OcropyResegment')
    if len(polygons) == 1:
        return polygons[0]
    # get equidistant list of points along hull
    # (otherwise alphashape will jump across the interior)
    points = [
        poly.exterior.interpolate(dist).coords[0]  # .xy
        for poly in polygons for dist in np.arange(0, poly.length, 5.0)
    ]
    #alpha = alphashape.optimizealpha(points) # too slow
    alpha = 0.05
    jointp = alphashape.alphashape(points, alpha)
    tries = 0
    # from descartes import PolygonPatch
    # import matplotlib.pyplot as plt
    while jointp.type in ['MultiPolygon', 'GeometryCollection']:
        # plt.figure()
        # plt.gca().scatter(*zip(*points))
        # for geom in jointp.geoms:
        #     plt.gca().add_patch(PolygonPatch(geom, alpha=0.2))
        # plt.show()
        alpha *= 0.7
        tries += 1
        if tries > 10:
            LOG.warning("cannot find alpha for concave hull on '%s'", loc)
            alpha = 0
        jointp = alphashape.alphashape(points, alpha)
    if jointp.minimum_clearance < 1.0:
        # follow-up calculations will necessarily be integer;
        # so anticipate rounding here and then ensure validity
        jointp = asPolygon(np.round(jointp.exterior.coords))
        jointp = make_valid(jointp)
    return jointp
示例#25
0
def find_shapes(img, n, pixel_thresh=ACTIVE_PIXEL_THRESH):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
    active_pixels = np.argwhere(np.flip(img_gray.T, axis=0) > pixel_thresh)

    # TODO if DBSCAN then may want to resample to lower resolution
    # and resolution of game may affect this later because of eps/min_samples
    try:
        clusters = DBSCAN(eps=5, min_samples=40,
                          metric='manhattan').fit(active_pixels)
    except ValueError:
        raise ValueError('Found 0 clouds in the image') from None

    labels = np.unique(clusters.labels_)

    clouds = [
        active_pixels[np.argwhere(clusters.labels_ == lbl).flatten()]
        for lbl in labels
    ]
    if len(clouds) < n:
        raise ValueError(f'Unable to find {n} clouds in the image')
    elif len(clouds) > n:
        print(f'WARNING: more than {n} clouds found in image')

    clouds = sorted(clouds, key=len, reverse=True)[:n]
    clouds = sorted(clouds, key=lambda c: c.min(axis=0)[1])
    # shapes = [alphashape.alphashape(pt_cloud, 1) for pt_cloud in clouds]
    shapes = [alphashape.alphashape(pt_cloud, 1) for pt_cloud in clouds]

    return shapes

    contours = [
        np.array(list(zip(*shape.exterior.coords.xy))) for shape in shapes
    ]

    contour_means = [contour.mean(axis=0) for contour in contours]
    contour_maxs = [contour.max(axis=0) for contour in contours]

    normalized_contours = [
        (contour - contour_mean) / (contour_max[0] - contour_mean[0])
        for contour, contour_mean, contour_max in zip(contours, contour_means,
                                                      contour_maxs)
    ]

    # cloud_means = [cloud.mean(axis=0) for cloud in clouds]
    # cloud_maxs = [cloud[:, 0].max() for cloud in clouds]

    # normalized_pts = [(cloud - cloud_mean) / (cloud_max - cloud_mean[0]) for cloud, cloud_mean, cloud_max in zip(clouds, cloud_means, cloud_maxs)]

    return normalized_contours
示例#26
0
def testAlphashape(loc,time,alpha,channel):
    lons = pd.read_csv('./../../data/extracts_{}/{}/{}{}_lons.csv'.format(loc,time,loc,time),header=None).to_numpy()
    lats = pd.read_csv('./../../data/extracts_{}/{}/{}{}_lats.csv'.format(loc,time,loc,time),header=None).to_numpy()
    data = pd.read_csv('./../../data/extracts_{}/{}/{}C07_{}_data.csv'.format(loc,time,loc,time),header=None).to_numpy()
    print(lons.shape)
    print(lats.shape)
    print(data.shape)
    indices = getIndexLevel(data,channel,"high")
    latsByPattern = lats[indices]
    lonsByPattern = lons[indices]
    points = np.dstack((lonsByPattern,latsByPattern))
    boundary = alphashape.alphashape(points[0],alpha)
    print(boundary)
    g = GeoSeries(boundary)
    g.plot(cmap='winter')
    plt.show()
示例#27
0
    def compute_iso(self,
                    points,
                    d_min=4,
                    line=True,
                    a_min=0,
                    a_max=0,
                    A=(0, 0)):

        alpha_shape = np.array(
            list(alphashape.alphashape(points, 0.43).exterior.coords))
        if line:
            angles = np.arctan2(alpha_shape[:, 1] - A[1],
                                alpha_shape[:, 0] - A[0])
            #if faut travailler... he oui mon gars

        return alpha_shape
示例#28
0
def add_alphashap(points, ax, alpha_value=None, alpha=0.3, fc=None, ec=None):
    """
    Add a alpha shape which corresponds to the ternary scatter plot
    :param points: A list of 3-tuples that (i, j, k) requires i + j + k = scale
    :param ax: the ax to plot the alpha shape, supposed to be same as the scatter plot
    :param alpha_value: float. default None which will calculate the optimize. If zero a Convex hill will be added
    :param alpha: float 0 to 1
    :param fc: fill color
    :param ec: edge color
    :return: None
    """
    t_points = to_t_points(points)
    if alpha_value is None:
        alpha_value = alphashape.optimizealpha(t_points)
    alpha_shape = alphashape.alphashape(t_points, alpha_value)
    ax.add_patch(PolygonPatch(alpha_shape, alpha=alpha, fc=fc, ec=ec))
示例#29
0
def get_alphashape(points, alpha=0.1):
    alpha_shape = alphashape.alphashape(points, alpha=alpha)
    border = []
    if type(alpha_shape).__name__ in ['Point', 'LineString']:
        border = points.copy()
    elif type(alpha_shape).__name__ == 'Polygon':
        border = np.array(alpha_shape.exterior.coords)
    elif type(alpha_shape).__name__ == 'MultiPolygon':
        border = np.array([
            point for polygon in alpha_shape
            for point in polygon.exterior.coords[:-1]
        ])
    # pdb.set_trace()
    border_indices = [
        np.where(np.all(points == v, axis=1))[0][0] for v in border
    ]
    return (border_indices, border)
def generateStream():
    times = []
    dataChannel = {}
    dataWeather = {}
    days = ['extracts_{}'.format(location)] #['8','9','10','11','12','13','14']
    points = {}
    for c in patterns.keys():
        points[c] = []
    categories = []
    boundaries = []
    levels = []
    # lats = lats.to_numpy()
    # lons = lons.to_numpy()
    # for w in weathers
    for subdir in days:
        print(subdir)
        for rootDay,subdirDays,fileDays in os.walk("{}/{}/".format(dataset,subdir)):
            subdirDays = sorted(subdirDays,key=sortTime)
            for subdirDay in subdirDays:
                print(subdirDay)
                for c in patterns.keys():
                    for level in ["low","normal","high"]:
                        try:
                            dataChannel[c] = pd.read_csv("{}/{}/{}/{}{}_{}_data.csv".format(dataset,subdir,subdirDay,location,c,subdirDay),header=None).to_numpy()
                            indexs = getIndexLevel(dataChannel[c],c,level) #np.where(dataChannel[c] > thresholds[c][patterns[c]])
                            if indexs[0].size == 0:
                              continue
                            latsByPattern = lats[indexs]
                            lonsByPattern = lons[indexs]
                            points = np.dstack((lonsByPattern,latsByPattern))
                            boundary = alphashape.alphashape(points[0],50.0)
                        except:
                            continue
                        times.append(subdirDay)
                        categories.append(c)
                        boundaries.append(boundary)
                        levels.append(level)
        df = pd.DataFrame({
            'time' : times,
            'category' : categories,
            'boundary' : boundaries,
            'value' : levels
        })
        gdf = gpd.GeoDataFrame(df,geometry='boundary')
        gdf.to_csv('{}/Satellite_Events_Stream_Standard_in_{}.csv'.format(thresh_dir,subdir),index=None)