labelme 切割标注之后 mask
时间: 2025-07-04 14:02:27 浏览: 10
### Labelme 中切割标注后生成 Mask 文件的方法
在完成图像的切割标注之后,可以通过 `json_to_dataset.py` 脚本将 JSON 文件转换成数据集,其中包括生成对应的 mask 文件。mask 是用于表示对象轮廓或区域的二值化图像,在计算机视觉任务中非常重要。
为了确保 mask 的正确性和可用性,需要注意两点:
- mask 图像是 8-bit 格式的,而原始图像是 24-bit 彩色图像[^2]。
- 正确配置输入到神经网络中的图片格式对于模型的有效训练至关重要。
以下是 Python 实现代码示例,展示如何利用 labelme 工具包读取标注好的 JSON 文件并创建相应的 mask 文件:
```python
import os.path as osp
import imgviz
from labelme.utils import draw_label
from labelme.logger import logger
from labelme import utils
def main(json_file, out_dir):
data = utils.json.load(open(json_file))
if "imageData" not in data:
imagePath = osp.join(osp.dirname(json_file), data["imagePath"])
imageData = utils.img_b64_to_arr(data['imageData'])
lbl, _ = utils.shapes_to_label(
image_shape=(data['imageHeight'], data['imageWidth']),
shapes=data['shapes'],
label_name_to_value={"_background_": 0}
)
label_names = ["_background_"]
for shape in sorted(data["shapes"], key=lambda x: x["label"]):
label_name = shape["label"]
if label_name in label_names:
continue
label_names.append(label_name)
lbl_viz = draw_label(lbl, img=None, label_names=label_names)
# Save masks and visualizations to the output directory.
PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
for lbl_name in label_names:
f.write(lbl_name + '\n')
if __name__ == '__main__':
json_input = '/path/to/input/json'
output_directory = '/path/to/output/directory'
main(json_input, output_directory)
```
此脚本会遍历给定目录下的所有 `.json` 文件,并为每张带有标注信息的图片生成三个文件:原图 (`img.png`)、标签掩码 (`label.png`) 和带颜色映射的可视化版本 (`label_viz.png`)。此外还会有一个文本文件记录各个类别的名称(`label_names.txt`)。
阅读全文
相关推荐

















