COCO資料集格式互換

aimhabo發表於2018-11-09

poly->compacted RLE:

    seg=np.array([312.29, 562.89, 402.25, 511.49, 400.96, 425.38, 398.39, 372.69, 388.11, 332.85, 318.71, 325.14, 295.58, 305.86, 269.88, 314.86, 258.31, 337.99, 217.19, 321.29, 182.49, 343.13, 141.37, 348.27, 132.37, 358.55, 159.36, 377.83, 116.95, 421.53, 167.07, 499.92, 232.61, 560.32, 300.72, 571.89])
    compactedRLE = maskutil.frPyObjects([seg], 768, 768)
    print(compactedRLE)

 

compacted(compressed) RLE->mask:

    mask = maskutil.decode(compactedRLE)
    mask=np.reshape(mask,(768,768))
    mask[:,:]=mask[:,:]*255
    print(mask)
    #mmcv.imshow(mask)

 

mask-> polygon / RLE:

def close_contour(contour):
    if not np.array_equal(contour[0], contour[-1]):
        contour = np.vstack((contour, contour[0]))
    return contour

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

def binary_mask_to_rle(binary_mask):
    rle = {`counts`: [], `size`: list(binary_mask.shape)}
    counts = rle.get(`counts`)
    for i, (value, elements) in enumerate(groupby(binary_mask.ravel(order=`F`))):
        if i == 0 and value == 1:
            counts.append(0)
        counts.append(len(list(elements)))
    return rle

 

def main():

    mask=np.array(
        [
            [0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 1, 0, 0, 1, 0],
            [0, 0, 1, 1, 1, 1, 1, 0],
            [0, 0, 1, 1, 1, 1, 1, 0],
            [0, 0, 1, 1, 1, 1, 1, 0],
            [0, 0, 1, 0, 0, 0, 1, 0],
            [0, 0, 1, 0, 0, 0, 1, 0],
            [0, 0, 0, 0, 0, 0, 0, 0]
        ]
    )
    print(mask)

    poly=binary_mask_to_polygon(mask)

    print(poly)

    rle=binary_mask_to_rle(mask)

    print(rle)

 

相關文章