将VIA标注图像产生的JSON文件转换为mask图

    由于在学习的时候,要用到自己标注的样本,需要对样本进行人工标注生成mask图,在使用VGG Image Annotator(VIA)时对样本进行标注(这里不得不说这个网站挺好用的,还不需要下载,操作也简单),标注好之后,保存结果为xx.json文件,需要自己手动将其转换为mask图像,网上找了很多转换代码都不能达到自己的要求,于是自己将其总结,并重新写了能实现目标的代码,下面直接附上代码。

import os
import json
import numpy as np
import skimage.draw
import cv2

image_folder = r"D:\ProgramData\Anaconda3\pythonProject_1\bottle\test\contamination" #样本所在文件夹
mask_folder = "./mask/" #mask图像保存文件夹
path_annotation_json = 'box2.json'#.json文件

annotations = json.load(open(path_annotation_json, 'r'))#加载.json文件
imgs = annotations["_via_img_metadata"]
annotations = list(annotations.values())
annotations_point = annotations[1]
annotations_point = list(annotations_point.values())
annotations_point = [a for a in annotations_point if a['regions']]

for i in range(len(annotations_point)):#遍历图像样本
    filename = annotations_point[i]['filename']
    image_path = os.path.join(image_folder, filename)
    image = cv2.imread(image_path)
    height, width = image.shape[:2]
    maskImage = np.zeros((height, width), dtype=np.uint8)

    for j in range(len(annotations_point[i]['regions'])):#存在多个标注区域时,需要遍历
        point = list(annotations_point[i]['regions'][j].values())[0]
        point_x = point['all_points_x']
        point_y = point['all_points_y']
        rr, cc = skimage.draw.polygon(point_y, point_x)

        maskImage[rr, cc] = 255 #生成mask黑白图
    savePath = mask_folder + filename

    cv2.imwrite(savePath, maskImage)#保存

示例

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值