多边形坐标点转掩码
代码参考: 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)
```