VIA标注格式转Labelme标注格式

最近做计算机视觉相关工作,采用VIA工具进行标注,现在需要将其转为Labelme格式。

python 复制代码
import json
import cv2
import os
import numpy as np

'''
0 正常
1 异常
2 有
3 无
'''

# 读取json文件
with open('01725bff-0fc6-4017-ad33-830df526438a.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    
attribute = data['attribute']
file = data['file']
metadata = data['metadata']

label_data = {}

for key, value in metadata.items():
    file_id = key.split('_')[0]
    fname = file[file_id]['fname']
    if fname not in label_data.keys():
        label_data[fname] = []
    xy_class = value['xy'][0]
    xy_coords = value['xy'][1:]
    av = value['av']['1']
    if av == "0":
        av = 2
    if av == "1":
        av = 3
    if av == "2":
        av = 0
    if av == "3":
        av = 1  
    if xy_class == 7:
        label_data[fname].append((xy_coords, av))
        
# 以上是获取via标注的数据,下面是转换为labelme格式的json文件

with open('template.json', 'r', encoding='utf-8') as f:
    template = json.load(f)
template['shapes'] = []

for f_n, d in label_data.items():
    f_n = f_n.replace('http://192.168.122.111:8099/images/bo_pian', '.')
    # f_w = open(f_n.replace('.jpg', '.txt'), 'w', encoding='utf-8')
    json_w = f_n.replace('.jpg', '.json')
    f_name = os.path.basename(f_n)
    template['imagePath'] = f_name
    img = cv2.imread(f_n)
    # 获取图片的宽高
    height, width, _ = img.shape
    template['imageHeight'] = height
    template['imageWidth'] = width
    shapes = []
    for coords, av in d:
        shape = {
            "label": str(av),
            "text": "",
            "points": np.array(coords).reshape(-1, 2).tolist(),
            "group_id": None,
            "shape_type": "polygon",
            "flags": {}
        }
        shapes.append(shape)
    template['shapes'] = shapes
    # 将json数据写入文件
    with open(json_w, 'w', encoding='utf-8') as f:
        json.dump(template, f, ensure_ascii=False, indent=4)
        

    
相关推荐
全栈练习生10 小时前
AI Agent 沙箱
python·ai
SEO_juper11 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户83562907805112 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
for_ever_love__13 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
用户83562907805113 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
weixin_4617694013 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
2601_9669496513 小时前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
全栈弄潮儿14 小时前
Python实战第1期:Python环境搭建与第一个程序
python
心易行者14 小时前
Agent应用+API端点商业化进阶实战:从单体智能体到可付费调用的API全流程
运维·服务器·人工智能·python·apache
weixin1997010801614 小时前
《1688图片空间API踩坑:img.upload 与 album.* 的防盗链与CDN缓存问题》(附Python源码)
开发语言·python·缓存