【实例分割】转换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查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

java向微信服务号发送消息的完整步骤实例

《java向微信服务号发送消息的完整步骤实例》:本文主要介绍java向微信服务号发送消息的相关资料,包括申请测试号获取appID/appsecret、关注公众号获取openID、配置消息模板及代码... 目录步骤1. 申请测试系统2. 公众号账号信息3. 关注测试号二维码4. 消息模板接口5. Java测试

Mysql常见的SQL语句格式及实用技巧

《Mysql常见的SQL语句格式及实用技巧》本文系统梳理MySQL常见SQL语句格式,涵盖数据库与表的创建、删除、修改、查询操作,以及记录增删改查和多表关联等高级查询,同时提供索引优化、事务处理、临时... 目录一、常用语法汇总二、示例1.数据库操作2.表操作3.记录操作 4.高级查询三、实用技巧一、常用语

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘问题

《解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘问题》:本文主要介绍解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4... 目录未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘打开pom.XM

利用Python脚本实现批量将图片转换为WebP格式

《利用Python脚本实现批量将图片转换为WebP格式》Python语言的简洁语法和库支持使其成为图像处理的理想选择,本文将介绍如何利用Python实现批量将图片转换为WebP格式的脚本,WebP作为... 目录简介1. python在图像处理中的应用2. WebP格式的原理和优势2.1 WebP格式与传统

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.