labelme json转mpii 格式转换

Lableme2mpii

import numpy as np
import json
import glob
import random

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)




class tompii(object):
    def __init__(self, jsonfile, save_path):
        self.annotations = []
        self.jsonfile=jsonfile
        self.save_path=save_path
        self.cnt=0
    def check(self,data):
        if len(data['shapes']) % 17 !=0:
            return False
        for i in range(len(data['shapes'])):
            if i % 17 ==0 and data['shapes'][i]['label']!='obj':
                return False
            if i % 17 != 0 and data['shapes'][i]['label'] not in ['0','1','2']:
                return False
        return True
    def get_cattle_width(self,obj):
        return obj['points'][1][0] - obj['points'][0][0]
    def get_cattle_height(self,obj):
        return obj['points'][1][1] - obj['points'][0][1]
    def get_objpos(self,obj):
        return [round((obj['points'][0][0]+obj['points'][1][0]/2),3),round((obj['points'][0][1]+obj['points'][1][1]/2),3)]

    def labelme_to_mpii(self):
        annid = 0
        for num, json_file in enumerate(self.jsonfile):

            annotation={}
            data = open(json_file, "r")
            data = json.load(data)
            if self.check(data) != True:
                print(json_file)
                continue
            self.cnt+=1

            annotation['img_paths']=json_file.split('\\')[1].split('.')[0]+".jpg"

            cattleNum = len(data['shapes']) // 17
            for main in range(cattleNum):
                cattle_width=round(self.get_cattle_width(data['shapes'][17*main]),3)
                cattle_height=round(self.get_cattle_height(data['shapes'][17*main]),3)
                scale_provided=round(data['imageWidth']/cattle_width,3)
                annotation['objpos']=self.get_objpos(data['shapes'][17*main])
                annotation['validation']=0.0


                shapes = data["shapes"]
                joint_self=[]
                for i in range(17*main+1,17*main+17):
                    point=[round(shapes[i]['points'][0][0],3),round(shapes[i]['points'][0][1],3),eval(shapes[i]['label'])]

                    joint_self.append(point)
                annotation['joint_self']=joint_self
                annotation['scale_provided']=scale_provided
                if cattleNum==1:
                    numOtherCattle=0.0
                    objpos_other=None
                    joint_others=None
                    scale_provided_other=None
                    annotation['numOtherCattle']=numOtherCattle
                    annotation['objpos_other']=objpos_other
                    annotation['joint_others']=joint_others
                    annotation['scale_provided_other']=scale_provided_other
                else:
                    nuuOtherCattle=cattleNum-1
                    objpos_other=[]
                    joint_others=[]
                    scale_provided_other=[]
                    for i in range(cattleNum):
                        if i == main:
                            continue
                        cattle_width = round(self.get_cattle_width(data['shapes'][i*17]), 3)
                        cattle_height = round(self.get_cattle_height(data['shapes'][i*17]), 3)
                        scale_provided_other.append(round(data['imageWidth'] / cattle_width,3))
                        objpos_other.append(self.get_objpos(data['shapes'][i*17]))
                        joint_other=[]
                        for j in range(1,17):
                            point = [round(shapes[i*17+j]['points'][0][0], 3), round(shapes[i*17+j]['points'][0][1], 3),
                                     eval(shapes[i*17+j]['label'])]

                            joint_other.append(point)
                        joint_others.append(joint_other)
                    annotation['numOtherCattle'] = numOtherCattle
                    annotation['objpos_other'] = objpos_other
                    annotation['joint_others'] = joint_others
                    annotation['scale_provided_other'] = scale_provided_other
            self.annotations.append(annotation)
        random.shuffle(self.annotations)
        length=len(self.annotations)
        for i in self.annotations[-int(length*0.2):-1]:
            i['validation']=1.0
        print(self.annotations[-int(length*0.2):-1])
    def save_json(self):
        self.labelme_to_mpii()
        mpii_annotations = self.annotations
        # 保存json文件
        json.dump(mpii_annotations, open(self.save_path, 'w'), indent=4, cls=MyEncoder)  # indent=4 更加美观显示


import glob

labelme_json = glob.glob('json/*.json')
c = tompii(labelme_json, 'new_annotations.json')
c.save_json()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

轩辕青山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值