• mask: rle, polygon


    RLE 编码

    RLE(Run-Length Encoding)是一种简单而有效的无损数据压缩和编码方法。它的基本思想是将连续相同的数据值序列用一个值和其连续出现的次数来表示,从而减少数据的存储或传输量。

    图像分割领域(如 COCO 数据集中),RLE 通常被用来表示二进制掩码。二进制掩码是由 0 和 1 组成的矩阵,其中 0 表示背景,1 表示前景(或某个特定的物体)。使用 RLE 编码可以有效地表示连续的相同值序列。

    RLE 编码的基本思想是按照连续的相同值(通常是 0 或 1)计算它们的重复次数,然后将这个值和重复次数以一定的格式编码。具体格式可以有多种,但在 COCO 数据集中,RLE 通常是以一系列数字的形式表示的,每两个数字表示一个重复次数和对应的值。

    coco api 中 的 encode 将binary mask 转为 rle。decode将 rle 转换为 binary mask.
    mmdetction 中的maskrcnn 预测输出的 segmentation 也是 rle格式.

    将 polygon 转换为 rle

    def polygon_to_rle(polygon, image_height, image_width):
        # 创建一个 Shapely 多边形对象
        poly = Polygon(polygon)
        
        # 获取多边形的轮廓
        exterior = list(poly.exterior.coords)
        
        # 创建 COCO 格式的分割掩码
        segmentation = [int(coord) for xy in exterior for coord in xy]
        
        # 将分割掩码编码为 RLE
        rle_encoded = mask_utils.frPyObjects([segmentation], image_height, image_width)
        
        return rle_encoded
    
    # 示例使用
    polygon = [[10, 10], [50, 10], [50, 50], [10, 50]]  # 一个简单的正方形
    image_height, image_width = 100, 100  # 图像的高度和宽度,根据实际情况设置
    
    rle_encoded = polygon_to_rle(polygon, image_height, image_width)
    print(rle_encoded)
    binary_mask = mask_utils.decode(rle_encoded)
    plt.imshow(binary_mask)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    将 polygon 转换为 mask

    import cv2
    def poly2mask(points, width, height):
        mask = np.zeros((width, height), dtype=np.int32)
        obj = np.array([points], dtype=np.int32)
        cv2.fillPoly(mask, obj, 1)
        return mask
    
    polygon= [[10, 10], [50, 10], [50, 50], [10, 50]]
    
    mask = poly2mask(polygon, 100, 100)
    
    plt.imshow(mask)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    【C#】字符串拼接相关
    软件架构风格
    tokio多任务绑定cpu(绑核)
    内存取证系列5
    Excel的Index+MATCH组合使用方法
    MySQL进阶4,常见函数
    【专栏】核心篇06| Redis 存储高可用背后的模式
    计算机网络-运输层详解(持续更新中)
    猜数字游戏
    GET和POST请求的区别
  • 原文地址:https://blog.csdn.net/weixin_41783424/article/details/134427431