C#本地将labelme数据集转换为机器视觉yolo数据集格式

C#本地,将labelme数据集转换为机器视觉yolo数据集格式

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.RegularExpressions;
using System.Text.Unicode;
using System.Threading.Tasks;
using System.Windows.Ink;
using System.Windows.Media.Media3D;namespace WpfAppYolo11_test1
{/// <summary>/// 将labelme数据集转换为yolo数据集格式/// </summary>public class LabelmeToYoloDataSetUtils{Dictionary<string, short> labels = new Dictionary<string, short>();/// <summary>/// 转换后保存目录/// </summary>const string outDir = "D:\\yoloTrainDataSet";const int saveLength = 10;/// <summary>/// labelme转yolo格式数据,要转换的目录/// </summary>/// <param name="inputDir"></param>/// 2025-3-4 00:45:38,public void FileConvert(string inputDir){//labels.Clear();var files = System.IO.Directory.GetFiles(inputDir, "*.json");if (files == null || files.Length == 0){return;}//获取目录中文件夹,以数字升序命名最新的训练文件夹var folders = Directory.GetDirectories(outDir);int lastNum = 1;if (folders != null && folders.Length > 0){List<DirectoryInfo> dirList = new List<DirectoryInfo>();foreach (var item in folders){DirectoryInfo directoryInfo = new DirectoryInfo(item);dirList.Add(directoryInfo);}var lastDir = dirList.OrderByDescending(g => g.CreationTime).FirstOrDefault();//获取文件夹后缀var lastNumStr = Regex.Match(lastDir.Name, "\\d*$").Value;lastNum = Convert.ToInt32(lastNumStr) + 1;}//此次训练保存的文件夹string newTrainDir = "train" + lastNum;//string dirNew = "train" + Guid.NewGuid().ToString("n");string dirNew = outDir + "\\" + newTrainDir + "\\train";//处理json文件foreach (var item in files){//处理单个json文件SingleFileConvert(item, dirNew);}//挑选训练图片前两个图片作为验证集//创建val文件夹string val = Path.Combine(outDir, newTrainDir, "val");                      var files21 = System.IO.Directory.GetFiles(inputDir, "*.jpg");var files22 = System.IO.Directory.GetFiles(inputDir, "*.png");var fileContainer = files21.Union(files22).ToList();var first1 = fileContainer[0];var first2 = fileContainer[1];//将训练图片全部复制到train中var trainImgNew = Path.Combine(dirNew, "images");if (!Directory.Exists(trainImgNew)){Directory.CreateDirectory(trainImgNew);}foreach (var itemImg in fileContainer){string fileNew2  = Path.Combine(trainImgNew, Path.GetFileName(itemImg));File.Copy(itemImg, fileNew2);}//只有2个样本时,将训练的文件夹作为验证if (files.Length <= 2){val = dirNew;goto Val_done;}if (!Directory.Exists(val)){Directory.CreateDirectory(val);}//图片文件夹string valImage = Path.Combine(val, "images");if (!Directory.Exists(valImage)){Directory.CreateDirectory(valImage);}string file1Name = Path.GetFileName(first1);string file2Name = Path.GetFileName(first2);string img1 = Path.Combine(valImage, file1Name);File.Copy(first1, img1);string img2 = Path.Combine(valImage, file2Name);File.Copy(first2, img2);//坐标数据string vallabels = Path.Combine(val, "labels");if (!Directory.Exists(vallabels)){Directory.CreateDirectory(vallabels);}//找到train目录中的坐标数据string vallabels2 = Path.Combine(dirNew, "labels");string txt1 = Path.GetFileNameWithoutExtension(file1Name) + ".txt";string txt2 = Path.GetFileNameWithoutExtension(file2Name) + ".txt";string fileLabel1 = Path.Combine(vallabels2, txt1);string fileLabel2 = Path.Combine(vallabels2, txt2);if (File.Exists(fileLabel1)){string fileLabelTxt1 = Path.Combine(vallabels, txt1);File.Copy(fileLabel1, fileLabelTxt1);}if (File.Exists(fileLabel2)){string fileLabelTxt2 = Path.Combine(vallabels, txt2);File.Copy(fileLabel2, fileLabelTxt2);}Val_done://生成data.yamlstring dir = dirNew;//Path.Combine(outDir, newTrainDir);dir = dir.Replace("\\", "/");val = val.Replace("\\", "/");StringBuilder sb = new StringBuilder();sb.AppendLine("train: " + dir);sb.AppendLine("val: " + val);sb.AppendLine("test: " + val);sb.AppendLine("");sb.AppendLine("nc: " + labels.Count);//设置编码支持中文string labelName = System.Text.Json.JsonSerializer.Serialize(labels.Keys,new System.Text.Json.JsonSerializerOptions(){Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)});labelName = labelName.Replace("\"", "'");//替换双引号为单引号sb.AppendLine("names: " + labelName);//保存//var arr = inputDir.Split("\\");//var lastDir = arr.Last();//string newDir = inputDir.TrimEnd(lastDir.ToArray());//string filePath = Path.Combine(newDir, "yoloTrainDataSet", "data.yaml");string yamlDir = outDir + "\\" + newTrainDir;string filePath = Path.Combine(yamlDir, "data.yaml");System.IO.File.WriteAllText(filePath, sb.ToString());}/// <summary>/// 单个json文件转换/// </summary>public void SingleFileConvert(string file, string inputDir){string json = System.IO.File.ReadAllText(file);var data2 = System.Text.Json.JsonSerializer.Deserialize<LabelMeView>(json);if (data2 == null || data2.shapes == null || data2.shapes.Count == 0){return;}StringBuilder stringBuilder = new StringBuilder();//读取每个形状foreach (var item in data2.shapes){//忽略没名称的形状if (string.IsNullOrEmpty(item.label)){continue;}labels.TryAdd(item.label, 1);double x1 = 0, x2 = 0, y1 = 0, y2 = 0;if (item.shape_type == "rectangle"){x1 = item.points[0][0];y1 = item.points[0][1];x2 = item.points[1][0];y2 = item.points[1][1];}else if (item.shape_type == "polygon"){x1 = item.points.Select(g => g[0]).Min();y1 = item.points.Select(g => g[1]).Min();x2 = item.points.Select(g => g[0]).Max();y2 = item.points.Select(g => g[1]).Max();}//中心点double x_center = (x1 + x2) / (double)2 / data2.imageWidth;double y_center = (y1 + y2) / (double)2 / data2.imageHeight;double width = Math.Abs((x2 - x1) / data2.imageWidth);double height = Math.Abs((y2 - y1) / data2.imageHeight);//获取对象idint classId = labels.Keys.ToList().IndexOf(item.label);stringBuilder.AppendLine($"{classId} {x_center} {y_center} {width} {height}");}//保存txt文件//var arr = inputDir.Split("\\");//var lastDir = arr.Last();//string newDir = inputDir.TrimEnd(lastDir.ToArray());// string dir = System.IO.Path.Combine( outDir, "labels");string dir = System.IO.Path.Combine(inputDir, "labels");if (!System.IO.Directory.Exists(dir)){System.IO.Directory.CreateDirectory(dir);}//string fileName = Path.GetFileName(file) + "_" + Guid.NewGuid().ToString("n") + ".txt";string fileName = Path.GetFileNameWithoutExtension(file) + ".txt";string filePath = System.IO.Path.Combine(dir, fileName);File.WriteAllText(filePath, stringBuilder.ToString());}}public class LabelMeView{public string version { get; set; }public List<ShapeView> shapes { get; set; }public string imagePath { get; set; }/// <summary>/// 图片高度,px/// </summary>public int imageHeight { get; set; }/// <summary>/// 图片宽度,px/// </summary>public int imageWidth { get; set; }}public class ShapeView{/// <summary>/// 对象说明,标签/// </summary>public string label { get; set; }/// <summary>/// 形状描述;rectangle;polygon/// </summary>public string shape_type { get; set; }public object flags { get; set; }/// <summary>/// 坐标点/// </summary>public List<double[]> points { get; set; }public string version { get; set; }}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/36565.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode hot100(五)

11. 盛最多水的容器 给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同构成的容器可以容纳最多的水。 返回容器可以储存的最大水量。 说明&#xff1a;你…

echarts+Vue2 自动轮播饼图

1、首先下载echarts&#xff0c;并且全局引入echarts 方法&#xff1a;从 npm 安装 npm install echarts 在 main.js 文件中全局引入 然后创建一个vue文件&#xff0c;名字随便起&#xff0c;比如 pieChart.vue&#xff0c;话不多说&#xff0c;直接上才艺&#xff1a;&…

自学软硬件第755 docker容器虚拟化技术

见字如面&#xff0c; 这里是AIGC创意人_竹相左边&#xff0c; 正在通过AI自学软硬件工程师&#xff0c;目标手搓可回收火箭玩具。 我很喜欢 《流浪地球 2》中 &#xff0c;马兆&#xff1a;没有硬件支撑&#xff0c;你破解个屁。 写作背景 今天在剪视频&#xff0c;然后看…

单片机自学总结

自从工作以来&#xff0c;一直努力耕耘单片机&#xff0c;至今&#xff0c;颇有收获。从51单片机&#xff0c;PIC单片机&#xff0c;直到STM32&#xff0c;以及RTOS和Linux&#xff0c;几乎天天在搞:51单片机&#xff0c;STM8S207单片机&#xff0c;PY32F003单片机&#xff0c;…

模拟String基本函数/深浅拷贝/柔性数组

1.首先我们先关注一下ASCII&#xff1a; 记住常用每一个字符对应的ascii码值&#xff01; 2.string函数的相关操作函数代码&#xff1a; 大多数小疑问都已经写在注释里面&#xff01; #pragma once #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<a…

论文分享:PL-ALF框架实现无人机低纹理环境自主飞行

在室内仓库、地下隧道等低纹理复杂场景中&#xff0c;无人机依赖视觉传感器进行自主飞行时&#xff0c;往往会遇到定位精度低、路径规划不稳定等难题。针对这一问题&#xff0c;重庆邮电大学计算机学院雷大江教授团队在IEEE Trans期刊上提出了一种新型自主飞行框架&#xff1a;…

文档搜索引擎

实现的搜索功能 首先获取很多的网页,然后根据用户输入的查询词,在这些网页中进行查找 用户输入查询词之后,如何让查询词和当前的网站进行匹配? 首先获取很多网页(爬虫->一个http客户端,发送http请求获取http响应结果(就是网站))(批量化的获取很多的页面), 再根据用户输入…

自然语言处理入门4——RNN

一般来说&#xff0c;提到自然语言处理&#xff0c;我们都会涉及到循环神经网络&#xff08;RNN&#xff09;&#xff0c;这是因为自然语言可以被看作是一个时间序列&#xff0c;这个时间序列中的元素是一个个的token。传统的前馈神经网络结构简单&#xff0c;但是不能很好的处…

C++学习之QT实现取证小软件首页

实现效果 #include "mainwindow.h" #include "ui_mainwindow.h" #include <QToolButton> #include <QLabel> #include <QMessageBox> #include <QDebug> #include <QHBoxLayout> #include <QTableView> #incl…

AI 数字人短视频数字人分身系统源码开发难点都有哪些?

AI 数字人分身系统源代码开发涉及多个领域的复杂技术&#xff0c;其难点主要体现在以下几个方面&#xff1a; 逼真的数字人建模 精确的人体扫描与重建&#xff1a;要创建高度逼真的数字人分身&#xff0c;首先需要对真实人体进行精确扫描&#xff0c;获取准确的人体外形、肌肉…

适合用户快速开发项目的PHP框架有哪些?

有时候用户赶时间&#xff0c;并想快速在有限的时间里&#xff0c;筑起自己的项目&#xff0c;对于适合用户快速开发项目的PHP框架有哪些推荐呢&#xff1f;下面一起来了解一下。 1. Laravel Laravel 是一个功能强大且语法优雅的PHP框架&#xff0c;提供了丰富的功能和工具&a…

物联网为什么用MQTT不用 HTTP 或 UDP?

先来两个代码对比&#xff0c;上传温度数据给服务器。 MQTT代码示例 // MQTT 客户端连接到 MQTT 服务器 mqttClient.connect("mqtt://broker.server.com:8883", clientId) // 订阅特定主题 mqttClient.subscribe("sensor/data", qos1) // …

进程间通信(1)——管道

1. 进程间通信简介 进程间通信&#xff08;Inter-Process Communication&#xff0c;IPC&#xff09;是指不同进程之间交换数据的机制。由于进程具有独立的地址空间&#xff0c;它们无法直接访问彼此的数据&#xff0c;因此需要IPC机制来实现信息共享、数据传递或同步操作。 …

台达PLC转太网转换的教程案例(台达DVP系列)

产品介绍 台达DVP-PLC自投身工业自动化市场以来&#xff0c;始终致力于创新发展&#xff0c;不断推陈出新。其产品紧密贴合市场需求与行业工艺&#xff0c;凭借卓越性能与丰富功能&#xff0c;深受用户青睐。不仅推出了高效的程序与编辑工具&#xff0c;显著提升了主机执行速度…

ArcGIS10. 8简介与安装,附下载地址

目录 ArcGIS10.8 1. 概述 2. 组成与功能 3. 10.8 特性 下载链接 安装步骤 1. 安装准备 2. 具体步骤 3.补丁 其他版本安装 ArcGIS10.8 1. 概述 ArcGIS 10.8 是由美国 Esri 公司精心研发的一款功能强大的地理信息系统&#xff08;GIS&#xff09;平台。其核心功能在于…

R语言高效数据处理-自定义格式EXCEL数据输出

注&#xff1a;以下代码均为实际数据处理中的笔记摘录&#xff0c;所以很零散&#xff0c; 将就看吧&#xff0c;这一篇只是代表着我还在&#xff0c;所以可能用处不大&#xff0c;这一段时间都很煎熬&#xff01; 在实际数据处理中为了提升效率&#xff0c;将Excel报表交付给…

从零构建大语言模型全栈开发指南:第一部分:数学与理论基础-1.1.2核心数学基础:线性代数、概率论与梯度优化

&#x1f449; 点击关注不迷路 &#x1f449; 点击关注不迷路 &#x1f449; 点击关注不迷路 文章大纲 1.1.2 核心数学基础&#xff1a;线性代数、概率论与梯度优化1. 线性代数&#xff1a;大语言模型的“骨架”1.1 核心概念与应用场景表1&#xff1a;线性代数核心运算与模型应…

科研项目验收管理系统

摘 要 使用旧方法对科研项目信息进行系统化管理已经不再让人们信赖了&#xff0c;把现在的网络信息技术运用在科研项目信息的管理上面可以解决许多信息管理上面的难题&#xff0c;比如处理数据时间很长&#xff0c;数据存在错误不能及时纠正等问题。这次开发的科研项目验收管…

游戏成瘾与学习动力激发策略研究——了解存在主义心理学(通俗版)

存在主义心理学是20世纪中叶兴起的重要心理学流派,融合了哲学存在主义思想,强调人的主观体验、自由选择与责任承担,旨在帮助个体在不确定的世界中创造意义。 研究人如何在不确定的世界中活出意义的心理学,核心思想可以概括为以下四点: 存在主义心理学的主要内容 “存在先于…

Dropshare for Mac v6.1 文件共享工具 支持M、Intel芯片

Dropshare 是 Mac 用来上传图片、视频、截图和各种文件的工具。这款软件利用了SCP over SSH传输协议来将 Mac 本机的文件快速上传到自设的远程服务器。 应用介绍 Dropshare 是 Mac 用来上传图片、视频、截图和各种文件的工具。这款软件利用了SCP over SSH传输协议来将 Mac 本…