labelme数据转coco instance segmentation

2024-02-13 08:08

本文主要是介绍labelme数据转coco instance segmentation,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转数据参考:https://www.freesion.com/article/1518170289/
需要安装pycocotools, 参考这里:https://blog.csdn.net/summermaoz/article/details/115969308?spm=1001.2014.3001.5501

可能需要根据自己的标注情况做一点点修改 labelme2coco.py

#!/usr/bin/env pythonimport argparse
import collections
import datetime
import glob
import json
import os
import os.path as osp
import sys
import numpy as np
import PIL.Image
import labelmetry:import pycocotools.mask
except ImportError:print('Please install pycocotools:\n\n    pip install pycocotools\n')sys.exit(1)def main():parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)parser.add_argument('--input_dir', help='input annotated directory')parser.add_argument('--output_dir', help='output dataset directory')parser.add_argument('--filename', help='output filename')parser.add_argument('--labels', help='labels file', required=True)args = parser.parse_args()if osp.exists(args.output_dir):print('Output directory already exists:', args.output_dir)# sys.exit(1)# if not os.path.exists()else:os.makedirs(args.output_dir)os.makedirs(osp.join(args.output_dir, 'JPEGImages'))print('Creating dataset:', args.output_dir)now = datetime.datetime.now()data = dict(info=dict(description=None,url=None,version=None,year=now.year,contributor=None,date_created=now.strftime('%Y-%m-%d %H:%M:%S.%f'),),licenses=[dict(url=None,id=0,name=None,)],images=[# license, url, file_name, height, width, date_captured, id],type='instances',annotations=[# segmentation, area, iscrowd, image_id, bbox, category_id, id],categories=[# supercategory, id, name],)class_name_to_id = {}for i, line in enumerate(open(args.labels).readlines()):class_id = i - 1  # starts with -1class_name = line.strip()if class_id == -1:assert class_name == '__ignore__'continueclass_name_to_id[class_name] = class_iddata['categories'].append(dict(supercategory=None,id=class_id,name=class_name,))out_ann_file = osp.join(args.output_dir,  args.filename+'.json')label_files = glob.glob(osp.join(args.input_dir, '*.json'))for image_id, label_file in enumerate(label_files):print('Generating dataset from:', label_file)with open(label_file) as f:label_data = json.load(f)base = osp.splitext(osp.basename(label_file))[0]out_img_file = osp.join(args.output_dir, 'JPEGImages', base + '.jpg')path = label_data['imagePath']img_file = osp.join(osp.dirname(label_file), path).replace('png', 'jpg')img = np.asarray(PIL.Image.open(img_file))	PIL.Image.fromarray(img).save(out_img_file)data['images'].append(dict(license=0,url=None,file_name=osp.relpath(out_img_file, osp.dirname(out_ann_file)),height=img.shape[0],width=img.shape[1],date_captured=None,id=image_id,))masks = {}                                     # for areasegmentations = collections.defaultdict(list)  # for segmentationfor shape in label_data['shapes']:points = shape['points']label = shape['label']shape_type = shape.get('shape_type', None)mask = labelme.utils.shape_to_mask(img.shape[:2], points, shape_type)if label in masks:masks[label] = masks[label] | maskelse:masks[label] = maskpoints = np.asarray(points).flatten().tolist()segmentations[label].append(points)for label, mask in masks.items():cls_name = label[:10]if cls_name not in class_name_to_id:continuecls_id = class_name_to_id[cls_name]mask = np.asfortranarray(mask.astype(np.uint8))mask = pycocotools.mask.encode(mask)area = float(pycocotools.mask.area(mask))bbox = pycocotools.mask.toBbox(mask).flatten().tolist()data['annotations'].append(dict(id=len(data['annotations']),image_id=image_id,category_id=cls_id,segmentation=segmentations[label],area=area,bbox=bbox,iscrowd=0,))print('data:', data)with open(out_ann_file, 'w') as f:json.dump(data, f)if __name__ == '__main__':main()

这篇关于labelme数据转coco instance segmentation的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/704975

相关文章

MySQL数据目录迁移的完整过程

《MySQL数据目录迁移的完整过程》文章详细介绍了将MySQL数据目录迁移到新硬盘的整个过程,包括新硬盘挂载、创建新的数据目录、迁移数据(推荐使用两遍rsync方案)、修改MySQL配置文件和重启验证... 目录1,新硬盘挂载(如果有的话)2,创建新的 mysql 数据目录3,迁移 MySQL 数据(推荐两

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

MySQL快速复制一张表的四种核心方法(包括表结构和数据)

《MySQL快速复制一张表的四种核心方法(包括表结构和数据)》本文详细介绍了四种复制MySQL表(结构+数据)的方法,并对每种方法进行了对比分析,适用于不同场景和数据量的复制需求,特别是针对超大表(1... 目录一、mysql 复制表(结构+数据)的 4 种核心方法(面试结构化回答)方法 1:CREATE

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

MySQL中的DELETE删除数据及注意事项

《MySQL中的DELETE删除数据及注意事项》MySQL的DELETE语句是数据库操作中不可或缺的一部分,通过合理使用索引、批量删除、避免全表删除、使用TRUNCATE、使用ORDERBY和LIMI... 目录1. 基本语法单表删除2. 高级用法使用子查询删除删除多表3. 性能优化策略使用索引批量删除避免

MySQL 数据库进阶之SQL 数据操作与子查询操作大全

《MySQL数据库进阶之SQL数据操作与子查询操作大全》本文详细介绍了SQL中的子查询、数据添加(INSERT)、数据修改(UPDATE)和数据删除(DELETE、TRUNCATE、DROP)操作... 目录一、子查询:嵌套在查询中的查询1.1 子查询的基本语法1.2 子查询的实战示例二、数据添加:INSE

Linux服务器数据盘移除并重新挂载的全过程

《Linux服务器数据盘移除并重新挂载的全过程》:本文主要介绍在Linux服务器上移除并重新挂载数据盘的整个过程,分为三大步:卸载文件系统、分离磁盘和重新挂载,每一步都有详细的步骤和注意事项,确保... 目录引言第一步:卸载文件系统第二步:分离磁盘第三步:重新挂载引言在 linux 服务器上移除并重新挂p

使用MyBatis TypeHandler实现数据加密与解密的具体方案

《使用MyBatisTypeHandler实现数据加密与解密的具体方案》在我们日常的开发工作中,经常会遇到一些敏感数据需要存储,比如用户的手机号、身份证号、银行卡号等,为了保障数据安全,我们通常会对... 目录1. 核心概念:什么是 TypeHandler?2. 实战场景3. 代码实现步骤步骤 1:定义 E

使用C#导出Excel数据并保存多种格式的完整示例

《使用C#导出Excel数据并保存多种格式的完整示例》在现代企业信息化管理中,Excel已经成为最常用的数据存储和分析工具,从员工信息表、销售数据报表到财务分析表,几乎所有部门都离不开Excel,本文... 目录引言1. 安装 Spire.XLS2. 创建工作簿和填充数据3. 保存为不同格式4. 效果展示5

Python多任务爬虫实现爬取图片和GDP数据

《Python多任务爬虫实现爬取图片和GDP数据》本文主要介绍了基于FastAPI开发Web站点的方法,包括搭建Web服务器、处理图片资源、实现多任务爬虫和数据可视化,同时,还简要介绍了Python爬... 目录一. 基于FastAPI之Web站点开发1. 基于FastAPI搭建Web服务器2. Web服务