Python skimage.measure.approximate_polygon() Examples

The following are 7 code examples of skimage.measure.approximate_polygon(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module skimage.measure , or try the search function .
Example #1
Source File: segmentation.py    From kraken with Apache License 2.0 7 votes vote down vote up
def vectorize_regions(im: np.ndarray, threshold: float = 0.5):
    """
    Vectorizes lines from a binarized array.

    Args:
        im (np.ndarray): Array of shape (H, W) with the first dimension
                         being a probability distribution over the region.
        threshold (float): Threshold for binarization

    Returns:
        [[x0, y0, ... xn, yn], [xm, ym, ..., xk, yk], ... ]
        A list of lists containing the region polygons.
    """
    bin = im > threshold
    contours = find_contours(bin, 0.5, fully_connected='high', positive_orientation='high')
    if len(contours) == 0:
        return contours
    approx_contours = []
    for contour in contours:
        approx_contours.append(approximate_polygon(contour[:,[1,0]], 1).astype('uint').tolist())
    return approx_contours 
Example #2
Source File: create_patches_all.py    From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 7 votes vote down vote up
def binary_mask_to_polygon(binary_mask, tolerance=0):
    """Converts a binary mask to COCO polygon representation
    Args:
        binary_mask: a 2D binary numpy array where '1's represent the object
        tolerance: Maximum distance from original points of polygon to approximated
            polygonal chain. If tolerance is 0, the original coordinate array is returned.
    """
    polygons = []
    # pad mask to close contours of shapes which start and end at an edge
    padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
    contours = measure.find_contours(padded_binary_mask, 0.5)
    contours = np.subtract(contours, 1)
    for contour in contours:
        contour = close_contour(contour)
        contour = measure.approximate_polygon(contour, tolerance)
        if len(contour) < 3:
            continue
        contour = np.flip(contour, axis=1)
        segmentation = contour.ravel().tolist()
        # after padding and subtracting 1 we may get -0.5 points in our segmentation
        segmentation = [0 if i < 0 else i for i in segmentation]
        polygons.append(segmentation)

    return polygons 
Example #3
Source File: prediction.py    From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 7 votes vote down vote up
def binary_mask_to_polygon(binary_mask, tolerance=0):
    """Converts a binary mask to COCO polygon representation
    Args:
        binary_mask: a 2D binary numpy array where '1's represent the object
        tolerance: Maximum distance from original points of polygon to approximated
            polygonal chain. If tolerance is 0, the original coordinate array is returned.
    """
    polygons = []
    # pad mask to close contours of shapes which start and end at an edge
    padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
    contours = measure.find_contours(padded_binary_mask, 0.5)
    contours = np.subtract(contours, 1)
    for contour in contours:
        contour = close_contour(contour)
        contour = measure.approximate_polygon(contour, tolerance)
        if len(contour) < 3:
            continue
        contour = np.flip(contour, axis=1)
        segmentation = contour
        # after padding and subtracting 1 we may get -0.5 points in our segmentation
        segmentation = [np.clip(i,0.0,i).tolist() for i in segmentation]
        polygons.append(segmentation)

    return polygons 
Example #4
Source File: segment.py    From sima with GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, roi):
        smoothed_polygons = []
        coords = roi.coords
        for polygon in coords:
            if polygon.shape[0] > self.min_verts:
                plane = polygon[0, -1]
                smoothed_coords = approximate_polygon(polygon[:, :2],
                                                      self.tolerance)
                smoothed_coords = np.hstack(
                    (smoothed_coords, plane * np.ones(
                        (smoothed_coords.shape[0], 1))))

                if smoothed_coords.shape[0] < self.min_verts:
                    smoothed_coords = polygon

            else:
                smoothed_coords = polygon

            smoothed_polygons += [smoothed_coords]

        return ROI(polygons=smoothed_polygons, im_shape=roi.im_shape) 
Example #5
Source File: pycococreatortools.py    From pycococreator with Apache License 2.0 5 votes vote down vote up
def binary_mask_to_polygon(binary_mask, tolerance=0):
    """Converts a binary mask to COCO polygon representation

    Args:
        binary_mask: a 2D binary numpy array where '1's represent the object
        tolerance: Maximum distance from original points of polygon to approximated
            polygonal chain. If tolerance is 0, the original coordinate array is returned.

    """
    polygons = []
    # pad mask to close contours of shapes which start and end at an edge
    padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
    contours = measure.find_contours(padded_binary_mask, 0.5)
    contours = np.subtract(contours, 1)
    for contour in contours:
        contour = close_contour(contour)
        contour = measure.approximate_polygon(contour, tolerance)
        if len(contour) < 3:
            continue
        contour = np.flip(contour, axis=1)
        segmentation = contour.ravel().tolist()
        # after padding and subtracting 1 we may get -0.5 points in our segmentation 
        segmentation = [0 if i < 0 else i for i in segmentation]
        polygons.append(segmentation)

    return polygons 
Example #6
Source File: CocoUtility.py    From BlenderProc with GNU General Public License v3.0 5 votes vote down vote up
def binary_mask_to_polygon(binary_mask, tolerance=0):
        """Converts a binary mask to COCO polygon representation

         :param binary_mask: a 2D binary numpy array where '1's represent the object
         :param tolerance: Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned.
        """
        polygons = []
        # pad mask to close contours of shapes which start and end at an edge
        padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
        contours = np.array(measure.find_contours(padded_binary_mask, 0.5))
        # Reverse padding
        contours = contours - 1
        for contour in contours:
            # Make sure contour is closed
            contour = CocoUtility.close_contour(contour)
            # Approximate contour by polygon
            polygon = measure.approximate_polygon(contour, tolerance)
            # Skip invalid polygons
            if len(polygon) < 3:
                continue
            # Flip xy to yx point representation
            polygon = np.flip(polygon, axis=1)
            # Flatten
            polygon = polygon.ravel()
            # after padding and subtracting 1 we may get -0.5 points in our segmentation
            polygon[polygon < 0] = 0
            polygons.append(polygon.tolist())

        return polygons 
Example #7
Source File: segmentation.py    From kraken with Apache License 2.0 4 votes vote down vote up
def _interpolate_lines(clusters, elongation_offset, extent, st_map, end_map):
    """
    Interpolates the baseline clusters and sets the correct line direction.
    """
    logger.debug('Reticulating splines')
    lines = []
    extent = geom.Polygon([(0, 0), (extent[1]-1, 0), (extent[1]-1, extent[0]-1), (0, extent[0]-1), (0, 0)])
    f_st_map = maximum_filter(st_map, size=20)
    f_end_map = maximum_filter(end_map, size=20)
    for cluster in clusters[1:]:
        # find start-end point
        points = [point for edge in cluster for point in edge]
        dists = squareform(pdist(points))
        i, j = np.unravel_index(dists.argmax(), dists.shape)
        # build adjacency matrix for shortest path algo
        adj_mat = np.full_like(dists, np.inf)
        for l, r in cluster:
            idx_l = points.index(l)
            idx_r = points.index(r)
            adj_mat[idx_l, idx_r] = dists[idx_l, idx_r]
        # shortest path
        _, pr = shortest_path(adj_mat, directed=False, return_predecessors=True, indices=i)
        k = j
        line = [points[j]]
        while pr[k] != -9999:
            k = pr[k]
            line.append(points[k])
        # smooth line
        line = np.array(line[::-1])
        line = approximate_polygon(line[:,[1,0]], 1)
        lr_dir = line[0] - line[1]
        lr_dir = (lr_dir.T  / np.sqrt(np.sum(lr_dir**2,axis=-1))) * elongation_offset/2
        line[0] = line[0] + lr_dir
        rr_dir = line[-1] - line[-2]
        rr_dir = (rr_dir.T  / np.sqrt(np.sum(rr_dir**2,axis=-1))) * elongation_offset/2
        line[-1] = line[-1] + rr_dir
        ins = geom.LineString(line).intersection(extent)
        if ins.type == 'MultiLineString':
            ins = linemerge(ins)
            # skip lines that don't merge cleanly
            if ins.type != 'LineString':
                continue
        line = np.array(ins, dtype='uint')
        l_end = tuple(line[0])[::-1]
        r_end = tuple(line[-1])[::-1]
        if f_st_map[l_end] - f_end_map[l_end] > 0.2 and f_st_map[r_end] - f_end_map[r_end] < -0.2:
            pass
        elif f_st_map[l_end] - f_end_map[l_end] < -0.2 and f_st_map[r_end] - f_end_map[r_end] > 0.2:
            line = line[::-1]
        else:
            logger.debug('Insufficient marker confidences in output. Defaulting to upright line.')
            if line[0][0] > line[-1][0]:
                line = line[::-1]
        lines.append(line.tolist())
    return lines