【实例分割】转换YOLO格式标注至COCO格式JSON

2024-04-15 15:28

本文主要是介绍【实例分割】转换YOLO格式标注至COCO格式JSON,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

yolo2coco代码:

import json
import glob
import os
import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from PIL import Image, ImageDraw, ImageFont
import numpy as npdef calculate_polygon_area(polygon):x = polygon[:, 0]y = polygon[:, 1]return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))def calculate_bounding_box(polygon):x_min = np.min(polygon[:, 0])y_min = np.min(polygon[:, 1])x_max = np.max(polygon[:, 0])y_max = np.max(polygon[:, 1])width = x_max - x_minheight = y_max - y_minreturn [x_min, y_min, width, height]def text_to_json_segmentation(in_labels, in_images, out_json):"""Convert instance segmentation dataset from text files generated by the function 'json_to_text_segmentation'(for YOLO) to a JSON file (for MMdet). This can be applied for Level 0/1/2 (must modify the last code):param in_labels: input folder containing the label text files:param in_images: input folder containing the image files (just for getting the image size):param out_json: output JSON file"""# Initialize the output JSON filedata = dict()data['annotations'] = []data['images'] = []# Initial the number of annotationsnum_annotations = 1  # index starts from 1# Process the text filestxt_files = glob.glob(in_labels + '/*.txt')for k in range(len(txt_files)):# Read the image to get image width and heightimg = Image.open(in_images + '/' + os.path.basename(txt_files[k]).replace('txt', 'jpg'))image_width, image_height = img.size# Creates annotation items of the image and append them to the listwith open(txt_files[k]) as f:for line in f:# Get annotation information of each line in the text fileline = [float(x) for x in line.strip().split()]class_id = int(line[0]) + 1  # index starts from 1coordinates = line[1:]polygon = np.array(coordinates).reshape(-1, 2)polygon[:, 0] = polygon[:, 0] * image_widthpolygon[:, 1] = polygon[:, 1] * image_heightarea = calculate_polygon_area(polygon)bbox = calculate_bounding_box(polygon)# Create a new annotation itemann_item = dict()ann_item['segmentation'] = [polygon.flatten().tolist()]ann_item['area'] = areaann_item['iscrowd'] = 0ann_item['image_id'] = k + 1  # index starts from 1ann_item['bbox'] = bboxann_item['category_id'] = class_idann_item['id'] = num_annotationsdata['annotations'].append(ann_item)num_annotations += 1# Create a new image item and append it to the listimg_item = dict()img_item['id'] = k + 1  # index starts from 1img_item['file_name'] = os.path.basename(txt_files[k]).replace('txt', 'jpg')img_item['height'] = image_heightimg_item['width'] = image_widthdata['images'].append(img_item)print(os.path.basename(txt_files[k]) + ' done')data['categories'] = [{'supercategory': 'class1', 'id': 1, 'name': 'class1'}]# Write the dictionary to a JSON fileprint('Writing the data to a JSON file')with open(out_json, 'w') as f:# json.dump(data, f, cls=NpEncoder)# f.write(json.dumps(data, cls=NpEncoder, indent=4))f.write(json.dumps(data, default=int, indent=4))if __name__ == '__main__':# Convert the segmentation text files to JSON text_to_json_segmentation(in_labels='labels/test',in_images='images/test',out_json='instances_test2017.json')

这篇关于【实例分割】转换YOLO格式标注至COCO格式JSON的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

使用Java读取本地文件并转换为MultipartFile对象的方法

《使用Java读取本地文件并转换为MultipartFile对象的方法》在许多JavaWeb应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非... 目录1. 基本需求2. 自定义 MultipartFile 类3. 实现代码4. 代码解析5. 自定

Java Stream流以及常用方法操作实例

《JavaStream流以及常用方法操作实例》Stream是对Java中集合的一种增强方式,使用它可以将集合的处理过程变得更加简洁、高效和易读,:本文主要介绍JavaStream流以及常用方法... 目录一、Stream流是什么?二、stream的操作2.1、stream流创建2.2、stream的使用2.

springboot项目中集成shiro+jwt完整实例代码

《springboot项目中集成shiro+jwt完整实例代码》本文详细介绍如何在项目中集成Shiro和JWT,实现用户登录校验、token携带及接口权限管理,涉及自定义Realm、ModularRe... 目录简介目的需要的jar集成过程1.配置shiro2.创建自定义Realm2.1 LoginReal

Python跨文件实例化、跨文件调用及导入库示例代码

《Python跨文件实例化、跨文件调用及导入库示例代码》在Python开发过程中,经常会遇到需要在一个工程中调用另一个工程的Python文件的情况,:本文主要介绍Python跨文件实例化、跨文件调... 目录1. 核心对比表格(完整汇总)1.1 自定义模块跨文件调用汇总表1.2 第三方库使用汇总表1.3 导

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Python实现PDF按页分割的技术指南

《Python实现PDF按页分割的技术指南》PDF文件处理是日常工作中的常见需求,特别是当我们需要将大型PDF文档拆分为多个部分时,下面我们就来看看如何使用Python创建一个灵活的PDF分割工具吧... 目录需求分析技术方案工具选择安装依赖完整代码实现使用说明基本用法示例命令输出示例技术亮点实际应用场景扩

MySQL多实例管理如何在一台主机上运行多个mysql

《MySQL多实例管理如何在一台主机上运行多个mysql》文章详解了在Linux主机上通过二进制方式安装MySQL多实例的步骤,涵盖端口配置、数据目录准备、初始化与启动流程,以及排错方法,适用于构建读... 目录一、什么是mysql多实例二、二进制方式安装MySQL1.获取二进制代码包2.安装基础依赖3.清

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

详解MySQL中JSON数据类型用法及与传统JSON字符串对比

《详解MySQL中JSON数据类型用法及与传统JSON字符串对比》MySQL从5.7版本开始引入了JSON数据类型,专门用于存储JSON格式的数据,本文将为大家简单介绍一下MySQL中JSON数据类型... 目录前言基本用法jsON数据类型 vs 传统JSON字符串1. 存储方式2. 查询方式对比3. 索引