X-AnyLabeling系列:多边形坐标点转掩码

多边形坐标点转掩码

代码参考: X-AnyLabeling中的.\X-AnyLabeling\ tools\polygon_mask_conversion.py。这里主要拆分出多边形坐标点转掩码,同时增加了参数和支持带有中文名的路径。多边形坐标点存储在json文件中,格式可参考X-AnyLabeling中给出的示例,下面也给出一个具体的简单示例。掩码转多边形坐标点部分可参考另外一篇博客:https://blog.csdn.net/familytaijun/article/details/141401587。

json格式示例

这里展示的仅仅是一个大致的格式,特别是points里面的值没有太多含义,请勿使用做测试。

{
  "version": "2.4.0",
  "flags": {},
  "shapes": [
    {
      "label": "test",
      "text": "",
      "points": [
        [
          599,
          208
        ],
        [
          584,
          209
        ],
        [
          552,
          219
        ],
        [
          547,
          222
        ],
        [
          530,
          227
        ],
        [
          516,
          233
        ],
      "shape_type": "polygon"
    }
  ],
  "imagePath": "1.jpg",
  "imageData": null,
  "imageHeight": 640,
  "imageWidth": 960
}

代码示例

import json
import numpy as np
import cv2

def poly_to_mask(json_path, dst_mask_path):
    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)
    polygons = []
    for shape in data["shapes"]:
        points = shape["points"]
        polygon = []
        for point in points:
            x, y = point
            polygon.append((x, y))
        polygons.append(polygon)

    image_height = data["imageHeight"]
    image_width = data["imageWidth"]
    mask = np.zeros((image_height, image_width), dtype=np.uint8)
    for polygon_points in polygons:
        np_polygon = np.array(polygon_points, np.int32)
        np_polygon = np_polygon.reshape((-1, 1, 2))
        cv2.fillPoly(mask, [np_polygon], color=255)

    cv2.imencode('.png', mask)[1].tofile(dst_mask_path)


if __name__ == '__main__':
    json_path = "./json/test.json"
    dst_mask_path = "./masks/test.png"

    poly_to_mask(json_path, dst_mask_path)

```
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值