【实例分割】转换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

相关文章

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

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.