资源简介

labelme标注数据集到COCO格式数据集转化,用于官方版Mask-Rcnn训练

资源截图

代码片段和文件信息

# -*- coding:utf-8 -*-
# !/usr/bin/env python

import argparse
import json
import matplotlib.pyplot as plt
import skimage.io as io
import cv2
from labelme import utils
import numpy as np
import glob
import PIL.Image
from shapely.geometry import Polygon

class labelme2coco(object):
    def __init__(selflabelme_json=[]save_json_path=‘./new.json‘):
        ‘‘‘
        :param labelme_json: 所有labelme的json文件路径组成的列表
        :param save_json_path: json保存位置
        ‘‘‘
        self.labelme_json=labelme_json
        self.save_json_path=save_json_path
        self.images=[]
        self.categories=[]
        self.annotations=[]
        # self.data_coco = {}
        self.label=[]
        self.annID=1
        self.height=0
        self.width=0

        self.save_json()

    def data_transfer(self):
        for numjson_file in enumerate(self.labelme_json):
            with open(json_file‘r‘) as fp:
                data = json.load(fp)  # 加载json文件
                self.images.append(self.image(datanum))
                for shapes in data[‘shapes‘]:
                    #label=shapes[‘label‘].split(‘_‘)
                    label=shapes[‘label‘][:-1]
                    print(shapes[‘label‘])
                    print(label)
                    if label not in self.label:
                        self.categories.append(self.categorie(label))
                        self.label.append(label)
                    points=shapes[‘points‘]
                    self.annotations.append(self.annotation(pointslabelnum))
                    self.annID+=1
        print(self.label)

    def image(selfdatanum):
        image={}
        img = utils.img_b64_to_array(data[‘imageData‘])  # 解析原图片数据
        # img=io.imread(data[‘imagePath‘]) # 通过图片路径打开图片
        # img = cv2.imread(data[‘imagePath‘] 0)
        height width = img.shape[:2]
        img = None
        image[‘height‘]=height
        image[‘width‘] = width
        image[‘id‘]=num+1
        image[‘file_name‘] = data[‘imagePath‘].split(‘/‘)[-1]

        self.height=height
        self.width=width

        return image

    def categorie(selflabel):
        categorie={}
        categorie[‘supercategory‘] = label
        categorie[‘id‘]=len(self.label)+1 # 0 默认为背景
        categorie[‘name‘] = label
        return categorie

    def annotation(selfpointslabelnum):
        annotation={}
        annotation[‘segmentation‘]=[list(np.asarray(points).flatten())]
        poly = Polygon(points)
        area_ = round(poly.area6)
        annotation[‘area‘] = area_
        annotation[‘iscrowd‘] = 0
        annotation[‘imag

评论

共有 条评论