【halcon深度学习】图像分割数据集格式的转换

news2024/10/7 12:23:49

前言

目前用于**图像分割的**数据集,我目前接触到的用的比较多的有:
1 PASCAL VOC
2 COCO
3 YOLO
4 Halcon自己的格式(其实就是Halcon字典类型)

当前我涉及到计算机视觉中的数据集格式有,PASCAL VOC、COCO 和 YOLO 用于不同的目标检测和图像分割任务。以下是这三种数据集格式的介绍:

1. PASCAL VOC 格式:

PASCAL VOC(Visual Object Classes)是一个广泛使用的目标检测和图像分割数据集,其标注格式以XML文件的形式提供。以下是一个PASCAL VOC格式的示例(针对单个物体):

<annotation>
	<folder>images</folder>
	<filename>example.jpg</filename>
	<source>
		<database>PASCAL VOC</database>
	</source>
	<size>
		<width>800</width>
		<height>600</height>
		<depth>3</depth>
	</size>
	<object>
		<name>cat</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>200</xmin>
			<ymin>150</ymin>
			<xmax>400</xmax>
			<ymax>450</ymax>
		</bndbox>
	</object>
</annotation>

2. COCO 格式:

COCO(Common Objects in Context)是一个用于目标检测、分割和关键点估计的大规模数据集,其标注格式以JSON文件的形式提供。以下是一个COCO格式的示例(针对单个物体):

{
	"info": {},
	"images": [
		{
			"id": 1,
			"file_name": "example.jpg",
			"width": 800,
			"height": 600,
			"depth": 3
		}
	],
	"annotations": [
		{
			"id": 1,
			"image_id": 1,
			"category_id": 1,
			"bbox": [200, 150, 200, 300],
			"area": 60000,
			"iscrowd": 0
		}
	],
	"categories": [
		{
			"id": 1,
			"name": "cat"
		}
	]
}

3. YOLO 格式:

YOLO(You Only Look Once)是一个目标检测算法,同时也有其特定的数据集格式。YOLO格式通常需要一个文本文件,其中每行描述了一张图像中的目标。以下是一个YOLO格式的示例(每行表示单个物体):

0 0.45 0.35 0.2 0.5

在此示例中,每行包含了类别索引和目标的归一化坐标信息(中心点坐标和宽高相对于图像尺寸的比例)。

请注意,这些示例仅为了演示目的,实际数据集文件可能包含更多图像和目标的标注信息。不同的数据集格式适用于不同的任务和算法,您在使用特定数据集时需要了解其相应的标注格式。

这几种格式,都是描述图片中的某个框框的位置,以及这个框框对应的类别。

背景

我现在手头有一个PASCAL VOC 格式的数据集,每张图片都有对应好的标记图片,我现在想用halcon去读取整个数据集。但是,halcon是有自己的标注工具的:MVTec Deep Learning Tool
有这个软件标注的图片,导出的数据集格式是:.hdict
那有没有办法,把 PASCAL VOC 直接转为 .hdict 格式呢?

PASCAL VOC 转 .hdict

PASCAL VOC 的格式类型,我们已经看到了,就是个XML解析这个XML不在话下,但是 .hdict这个文件是个二进制的文件,看不到其中的内容。
于是,我搜索全网,发现了一个 PASCAL VOC 转 .hdict 的一个halcon脚本,然后花了一块大洋买了下来,下载下来一看,问题不大,稍微改改果然能用:

*read_dict ('C:/Users/12820/Desktop/数据/分割.hdict', [], [], DictHandle)
* Image Acquisition 01: Code generated by Image Acquisition 01

*read_dl_dataset_from_coco
*read_dl


create_dict (NEWDictHandle1)
class_ids:=[0,1,2,3,4,5]
class_names:=['crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches']
image_dir:='images/'

set_dict_tuple (NEWDictHandle1, 'class_ids', class_ids)
set_dict_tuple (NEWDictHandle1, 'class_names', class_names)
set_dict_tuple (NEWDictHandle1, 'image_dir', image_dir)

list_files ('images/', ['files','follow_links','recursive'], ImageFiles)
tuple_regexp_select (ImageFiles, ['\\.(tif|tiff|gif|bmp|jpg|jpeg|jp2|png|pcx|pgm|ppm|pbm|xwd|ima|hobj)$','ignore_case'], ImageFiles)


list_files ('labels/', ['files','follow_links','recursive'], xmladdress)
samples:=[]
for Index := 0 to |ImageFiles| - 1 by 1
    read_image (Image, ImageFiles[Index])
    
    
    
    
    
   open_file (xmladdress[Index], 'input', FileHandle)
   IsEof := false
   bbox_row1:=[]  
   bbox_col1:=[]  
   bbox_row2:=[]  
   bbox_col2:=[]  
   bbox_label_id:=[]
   while (not(IsEof))
       fread_line (FileHandle, XmlElement, IsEof)
       if (IsEof)
           break
       endif
       tuple_split (XmlElement, '<''>', Substrings)
       create_dict (image)
       if (Substrings[1]=='folder')
           floder:= Substrings[2] 
       endif  
       if (Substrings[1]=='filename')
           filename:= Substrings[2] 
       endif    
       *class_names:=['crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches']
       if (Substrings[1]=='name')
           if (Substrings[2]== class_names[0] )
               bbox_label_id:=[bbox_label_id,0]
           elseif (Substrings[2]==class_names[1])
               bbox_label_id:=[bbox_label_id,1]
           elseif (Substrings[2]==class_names[2])
               bbox_label_id:=[bbox_label_id,2]
           elseif (Substrings[2]==class_names[3])
                    bbox_label_id:=[bbox_label_id,3]
           elseif (Substrings[2]==class_names[4])
               bbox_label_id:=[bbox_label_id,4]
           elseif (Substrings[2]==class_names[5])
               bbox_label_id:=[bbox_label_id,5]
           endif
      endif
      
      if (Substrings[1]=='xmin')
          bbox_col1:= [bbox_col1,Substrings[2]]
          tuple_number (bbox_col1, bbox_col1)
   
      endif  
      if (Substrings[1]=='ymin')
          bbox_row1:= [bbox_row1,Substrings[2] ]
          tuple_number (bbox_row1, bbox_row1)
      endif  
      if (Substrings[1]=='xmax')
          bbox_col2:=[bbox_col2, Substrings[2] ]
          tuple_number (bbox_col2, bbox_col2)
      endif  
      if (Substrings[1]=='ymax')
          bbox_row2:=[bbox_row2, Substrings[2] ]
          tuple_number (bbox_row2, bbox_row2)
      endif  


    endwhile
    
    
   * gen_rectangle1 (Rectangle,bbox_row1 , bbox_col1,bbox_row2 , bbox_col2)
   
  set_dict_tuple (image, 'image_id', Index+1)
  set_dict_tuple (image, 'image_file_name', floder+'/'+filename)
  set_dict_tuple (image, 'bbox_label_id', bbox_label_id)
  set_dict_tuple (image, 'bbox_row1', bbox_row1)
  set_dict_tuple (image, 'bbox_col1', bbox_col1)
  set_dict_tuple (image, 'bbox_row2', bbox_row2)
  set_dict_tuple (image, 'bbox_col2', bbox_col2)
 samples:=[samples,image]
    
    *stop()  
endfor

set_dict_tuple (NEWDictHandle1, 'samples', samples)
 
write_dict (NEWDictHandle1, '数据test.hdict', [], [])

看到最后一句:write_dict 才意识到,原来所谓的.hdict文件就是halcon里的字典格式啊!
虽然,这个脚本文件可以用,但是1800条数据转换下来,花费了将近半个小时,这能忍?
还有就是PASCAL VOC标注文件有点地方图片名称没带后缀导致,导入后图片无法在
Deep Learning Tool 中显示!所以,搞清楚原理之后,我还是自己写个工具才更省心啊:

HTuple NEWDict;
HOperatorSet.CreateDict(out NEWDict);

 List<int> class_ids = new List<int> { 0, 1, 2, 3, 4, 5 };
 List<string> class_names = new List<string> { "crazing", "inclusion", "patches", "pitted_surface", "rolled-in_scale", "scratches" };
 string image_dir = "F:\\temp\\数据集格式转换测试\\images";

 //图片字典
 HTuple hv_image = new HTuple();
 HTuple hv_samples = new HTuple();

 HTuple hv_class_ids = new HTuple(class_ids.ToArray());
 HTuple hv_class_names = new HTuple(class_names.ToArray());
 HTuple hv_image_dir = new HTuple(image_dir);

 HOperatorSet.SetDictTuple(NEWDict, "class_ids", hv_class_ids);
 HOperatorSet.SetDictTuple(NEWDict, "class_names", hv_class_names);
 HOperatorSet.SetDictTuple(NEWDict, "image_dir", hv_image_dir);


 string[] imageFiles = Directory.GetFiles(image_dir, "*.*", SearchOption.AllDirectories);

 List<Dictionary<string, object>> samples = new List<Dictionary<string, object>>();

 int index = 0;
 string extension = "";
 foreach (string imagePath in imageFiles)
 {
     HOperatorSet.CreateDict(out hv_image);

     string xmlPath = "D:/DATASET/yolo/NEU-DET/ANNOTATIONS/" + Path.GetFileNameWithoutExtension(imagePath) + ".xml";

     XDocument xdoc;
     using (StreamReader reader = new StreamReader(xmlPath))
     {
         string xmlContent = reader.ReadToEnd();
         xdoc = XDocument.Parse(xmlContent);
         
         // 现在可以使用xdoc进行XML解析操作
     }

     XElement xroot = xdoc.Root;//根节点
     List<int> bbox_label_ids = new List<int>();
     List<int> bbox_col1 = new List<int>();
     List<int> bbox_row1 = new List<int>();
     List<int> bbox_col2 = new List<int>();
     List<int> bbox_row2 = new List<int>();

     //----folder
     var folder = xroot.Element("folder").Value;

     //----filename
     var filename = xroot.Element("filename").Value;
     if(Path.GetExtension(filename) != "")
     {
         extension = Path.GetExtension(filename);
     }
     else
     {
         if (extension != "")
         {
             filename += extension;
         }
     }


     //----获取object节点(一个xml中可能会有多个)
     var objectNodes = xroot.Descendants("object");

     foreach (var objectNode in objectNodes)
     {
         //bndbox节点,包含xmin,ymin,xmax,ymax
         XElement bndboxNode = objectNode.Element("bndbox");
         XElement xminNode = bndboxNode.Element("xmin");
         XElement yminNode = bndboxNode.Element("ymin");
         XElement xmaxNode = bndboxNode.Element("xmax");
         XElement ymaxNode = bndboxNode.Element("ymax");

         // 解析坐标值并添加到相应列表
         bbox_col1.Add(int.Parse(xminNode.Value));
         bbox_row1.Add(int.Parse(yminNode.Value));
         bbox_col2.Add(int.Parse(xmaxNode.Value));
         bbox_row2.Add(int.Parse(ymaxNode.Value));

         // 获取类别名称对应的编号,并添加到相应列表
         string className = objectNode.Element("name").Value;
         int id = class_names.IndexOf(className);
         bbox_label_ids.Add(id);                                
     }


     HOperatorSet.SetDictTuple(hv_image, "image_id", index + 1);
     HOperatorSet.SetDictTuple(hv_image, "image_file_name", (folder + "/") + filename);
     HOperatorSet.SetDictTuple(hv_image, "bbox_label_id", bbox_label_ids.ToArray());
     HOperatorSet.SetDictTuple(hv_image, "bbox_row1", bbox_row1.ToArray());
     HOperatorSet.SetDictTuple(hv_image, "bbox_col1", bbox_col1.ToArray());
     HOperatorSet.SetDictTuple(hv_image, "bbox_row2", bbox_row2.ToArray());
     HOperatorSet.SetDictTuple(hv_image, "bbox_col2", bbox_col2.ToArray());


     // hv_image添加到samples
     using (HDevDisposeHelper dh = new HDevDisposeHelper())
     {                
         HTuple ExpTmpLocalVar_samples = hv_samples.TupleConcat(hv_image);
         hv_samples.Dispose();
         hv_samples = ExpTmpLocalVar_samples;                    
     }

     index++;
 }

 HOperatorSet.SetDictTuple(NEWDict, "samples", hv_samples);
 HOperatorSet.WriteDict(NEWDict, "数据Csharp.hdict", new HTuple(), new HTuple());
 MessageBox.Show("转换完成");

这次使用XDocument方式解析,弹指间,转换就完成了!再次用Deep Learning Tool打开转换好的Csharp.hdict,这次就成功了
在这里插入图片描述

读取.hdict 格式的数据集

有了.hdict 这个格式的数据集,怎么用呢?

*读取数据集!!!这个就是深度学习工具标记的字典
read_dict (“xxxxx.hdict”, [], [], DLDataset)
应为它就是一个字典,所以直接使用read_dict就能读取数据集了!

还有,halcon除了自家的数据集之外,其实可以直接读取coco数据集:
read_dl_dataset_from_coco (FileExists, [], [], DLDataset1)
是不是很方便!

具体如何训练数据这些内容,后续持续输出,我们下一篇文件见!

附录

附送一个PASCAL VOC 转 YOLO的 python脚本!

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import glob


classes = ["crazing", "inclusion", "patches", "pitted_surface", "rolled-in_scale", "scratches"]

def convert(size, box):
    dw = 1./size[0]
    dh = 1./size[1]
    x = (box[0] + box[1])/2.0
    y = (box[2] + box[3])/2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)

def convert_annotation(image_name):
    in_file = open('./ANNOTATIONS/'+image_name[:-3]+'xml')
    out_file = open('./LABELS/'+image_name[:-3]+'txt','w')
    tree=ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        cls = obj.find('name').text
        if cls not in classes:
            print(cls)
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
        bb = convert((w,h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')

wd = getcwd()

if __name__ == '__main__':
    for image_path in glob.glob("./IMAGES/*.jpg"):
        image_name = image_path.split('\\')[-1]
        #print(image_path)
        convert_annotation(image_name)

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

天气插件和antv图表组件库的使用

目录 天气插件 antv组件库 特性 数据映射 data xField yField 图形样式 point state 图表组件 label tooltip 图表交互 添加交互 天气插件 网站:天气预报代码_天气预报插件_免费天气预报代码(插件)调用——天气网 (tianqi.com) 挑选想要的样式&#xff0c;点击 …

暴力递归转动态规划(一)

前两篇帖子介绍了暴力递归的过程&#xff0c;总的来说就是利用自然智慧不断的尝试。这篇文章则会介绍如何将暴力递归转成动态规划。 斐波那契数列 斐波那契数列一定都不陌生&#xff0c;规定第一列的值是1&#xff0c;第二列的值是2的话&#xff0c;那第七列的值就是13&#x…

2023Win11安装Oracle19c教程

2023Win11安装Oracle19c教程 一、下载安装二、安装三、配置四、navicat连接oracle 一、下载安装 进入官网&#xff0c;选择产品-Oracle DataBase&#xff0c;点击进入下载界面 点击跳转下载 选择19c进行下载 选择windows64位版本下载 登录账号后开始下载&#xff0c;等待下载…

1.3.1背包模型(一)

01背包 划分依据&#xff1a;依靠“最后一步”来划分 完全背包 多重背包 完全背包&#xff1a;求所有前缀的最大值 多重背包&#xff1a;求滑动窗口内的最大值 1.多重背包问题 III 有 N N N种物品和一个容量是 V V V的背包。 第 i i i种物品最多有 s i s_{i} si​件&…

激活函数总结(二十二):激活函数补充(Soft Exponential、ParametricLinear)

激活函数总结&#xff08;二十二&#xff09;&#xff1a;激活函数补充 1 引言2 激活函数2.1 Soft Exponential激活函数2.2 ParametricLinear激活函数 3. 总结 1 引言 在前面的文章中已经介绍了介绍了一系列激活函数 (Sigmoid、Tanh、ReLU、Leaky ReLU、PReLU、Swish、ELU、SE…

机器人制作开源方案 | 桌面级机械臂--仿真设计

1. Ros概述 ROS是一个适用于机器人编程的框架&#xff0c;这个框架把原本松散的零部件耦合在了一起&#xff0c;为它们提供了通信架构。ROS虽然叫做操作系统&#xff0c;但并非Windows、Mac那样通常意义的操作系统&#xff0c;它只是连接了操作系统和你开发的ROS应用程序&#…

AODV代码实现详解——原理与源码分析(一)

首先来几个标准参考&#xff1a; RFC 3561 RFC 3561 中文翻译 一个博客 挺好的另一个博客 事件&#xff1f; 字段长度&#xff1f; 事件驱动 各种定时器 状态转移图&#xff1f; AODV协议 基本概念 AODV&#xff08;Ad hoc On-Demand Distance Vector&#xff09;是一种基于…

Flutter问题记录 - Unable to find bundled Java version

新版本的Android Studio真的移除了JRE&#xff0c;jre目录找不到&#xff0c;怪不得报错了&#xff0c;不过多了一个jbr目录&#xff0c;找了个以前的Android Studio版本对比 搜了一下jbr&#xff08;JetBrains Runtime&#xff09;&#xff0c;原来IDEA老早就开始用了&#xf…

Redis 7 教程 数据持久化

总体 RDB 介绍 RDB 持久化以指定的时间间隔执行数据集的时间点快照 。 把某一时刻的数据和状态以文件的形式写到磁盘上,即使出现故障宕机,快照文件也不会丢失,数据的可靠性得到保证。快照文件就是RDB(Redis DataBase)文件(dump.rdb) 作用 在指定的时间间隔内将内存中的数…

财务数据分析怎么做?看看奥威BI数据可视化工具的解法

从以往的BI智能数据可视化分析项目来看&#xff0c;要想快刀砍乱麻地做好财务数据分析&#xff0c;为企业运营决策提供更加直观深入的数据支持&#xff0c;那就需要为财务数据分析做好数据导入、建模、报表制作、展示等多方面的准备。奥威BI数据可视化工具为此特意打造了一套标…

C#实战:基于腾讯OCR技术实现企业证书识别和数据提取实践

一、OCR技术介绍 在当今数字化时代&#xff0c;OCR&#xff08;Optical Character Recognition&#xff09;识别技术正发挥着越来越重要的作用。OCR技术通过将图像中的文字转化为可编辑的文本形式&#xff0c;实现了对大量纸质文档的数字化处理和信息提取。常见的有企业资质证…

【uniapp】 实现公共弹窗的封装以及调用

图例&#xff1a;红框区域为 “ 内容区域 ” 一、组件 <!-- 弹窗组件 --> <template> <view class"add_popup" v-if"person.isShowPopup"><view class"popup_cont" :style"{width:props.width&&props.width&…

【VLDB 2023】基于预测的云资源弹性伸缩框架MagicScaler,实现“高QoS,低成本”双丰收

开篇 近日&#xff0c;由阿里云计算平台大数据基础工程技术团队主导&#xff0c;与计算平台MaxCompute团队、华东师范大学数据科学与工程学院、达摩院合作&#xff0c;基于预测的云计算平台资源弹性伸缩框架论文《MagicScaler: Uncertainty-aware, Predictive Autoscaling 》被…

解锁市场进入成功:GTM 策略和即用型示例

在最初的几年里&#xff0c;创办一家初创公司可能会充满挑战。根据美国小企业管理局的数据&#xff0c;大约三分之二的新成立企业存活了两年&#xff0c;几乎一半的企业存活了五年以上。导致创业失败的因素有市场需求缺失、资金短缺、团队不合适、成本问题等。由此&#xff0c;…

Flutter可执行屏幕动画的AnimateView

1.让动画使用起来就像使用widget。 2.可自定义动画。 3.内置平移动画。 演示&#xff1a; 代码: import dart:math; import package:flutter/cupertino.dart;class AnimateView extends StatefulWidget {///子Widgetfinal Widget child;///动画自定义final IAnimate? anim…

什么,一条指令直接黑了数据库!

什么&#xff0c;一条指令直接黑了数据库&#xff01; shigen最近研究了一下一款渗透工具sqlMap。它一款流行的开源工具&#xff0c;用于自动化SQL注入攻击和渗透测试。它专门设计用于检测和利用Web应用程序中的SQL注入漏洞。SQLMap具有丰富的功能集&#xff0c;可自动检测和利…

工厂方法模式的概述和使用

目录 一、工厂方法模式概述1. 定义2. 使用动机 二、工厂方法模式结构1. 模式结构2. 时序图 三、工厂方法模式的使用实例四、工厂方法模式的优缺点五、工厂方法模式在Java中应用 原文链接 一、工厂方法模式概述 1. 定义 工厂方法模式(Factory Method Pattern)又称为工厂模式&…

高通面临难题,Oryon核心存在问题,高通8cx Gen 4芯片将推迟发布

"高通公司面临难题&#xff0c;可能会导致骁龙8cx Gen 4的发布时间推迟"&#xff0c;关于骁龙8cx Gen 4处理器&#xff0c;还有一些其他值得关注的特点和功能。首先&#xff0c;据悉&#xff0c;骁龙8cx Gen 4采用了高通自家研发的Oryon核心架构&#xff0c;这是一项…

春秋云镜 Brute4Road

flag1 fscan扫描发现&#xff0c;6379开放ftp可以匿名登录 这里直接尝试了去打redis但是只有主从复制能成功&#xff08;这里应该是靶场有设置吧&#xff0c;对6379操作过后再次操作就会显示端口拒绝访问直接重置就可以了&#xff09; 之后用脚本一把梭哈即可获得shell #更改…

C++ list模拟实现

list模拟实现代码&#xff1a; namespace djx {template<class T>struct list_node{T _data;list_node<T>* _prev;list_node<T>* _next;list_node(const T& x T()):_data(x),_prev(nullptr),_next(nullptr){}};template<class T,class Ref,class Pt…