当前位置:   article > 正文

遥感图像识别(标注)软件实现

遥感影像识别 c++
    遥感图像识别已经有很多成熟的模型和实现,这里我们选择yolov5_obb和dota数据集,以说明并实现一种思路:那就是先识别、再标注、再训练的过程。鉴于领域内数据往往比较封闭,对此类数据的标注实现难度较大,所以需要模型迁移。首先基于已经训练的成果,实现初步标绘;而后通过人在回路的修正,获得精确的结果,最后重新投入到数据训练过程中去。通过这种方式,获得专用数据模型,解决定制问题。
一、yolov5_obb简介
           普遍认为,计算机视觉图像识别四大基本任务,其中:
         
(a)图像分类(目标检测):一张图像中是否含某种物体
(b)物体定位(目标检测与目标识别):确定目标位置和所属类别。
(c)语义分割(目标分割和目标分类):对图像进行像素级分类,预测每个像素属于的类别,不区分个体;(所有的CUBE一个颜色)
(d)实例分割(目标分割和目标识别):定位图中每个物体,并进行像素级标注,区分不同个体;(CUBE都是不同颜色)
    遥感影像识别属于物体定位(object localization)范畴。一般区分2阶段和1阶段方法,其中yolo为典型实现。其中yolov5版本由于官方的持续支持和扩展,是比较成熟的版本。基于此实现的 yolov5_obb(YOLOv5_DOTA无人机/遥感旋转目标检测项目代码    hukaixuan19970627/yolov5_obb: yolov5 + csl_label)的推断,用于解决遥感数据集上倾斜目标的识别。作者实现了在 Dota数据集上yolov5m/yolov5s/yoov5n的150Epoch的推断结果,可供迁移模型使用。
    值得关注的是CSL旋转标注方法,参考资料《旋转目标检测方法解读(CSL, ECCV2020) 旋转目标检测方法解读(CSL, ECCV2020) - 知乎 (zhihu.com)
二、模型推断(c++实现)
    基于已经初步训练的结果,进一步实现标注结果展现。模型推断的实现是相对困难的,主要原因是因为在实现的过程中缺乏有效的调试工具。基于已经能够成功运行的代码去进行修改是问题有效的解决方法,其中hpc203对推断代码进行了改造,并且提供了大量案例。需要注意的是,yolov5_obb对yolov5的代码进行了改造,所以前面的相关操作都需要基于yolov5_obb实现。相关内容整理如下:
1、yolov5_Dota yolov5_Dota | Kaggle 这个是训练的工具,需要使用特定的torch版本,直接基于kaggle就可以运行。
2、https://gitee.com/jsxyhelu2020/yolov5_obb_static.git  这个是修改的代码:
3、从hpc203做出修改上来看,模型输出的结果,由4路转换为1路,可以借助netron进行观测。
转换前:
转换后:
4、hpc203对onnx文件转换生成的修改,进入models/yolo.py,进入到Detect类的forward函数里,插入代码
  1. if torch.onnx.is_in_onnx_export():
  2. for i in range(self.nl): # 分别对三个输出层处理
  3. x[i] = self.m[i](x[i]) # conv
  4. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  5. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  6. y = x[i].sigmoid()
  7. z.append(y.view(bs, -1, self.no))
  8. return torch.cat(z, 1)

在export.py里,自定义了一个导出onnx文件的函数,代码片段如下

  1. def my_export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
  2. print('anchors:', model.yaml['anchors'])
  3. # wtxt = open('class.names', 'w')
  4. #for name in model.names:
  5. # wtxt.write(name+'\n')
  6. # wtxt.close()
  7. # YOLOv5 ONNX export
  8. print(im.shape)
  9. if not dynamic:
  10. f = os.path.splitext(file)[0] + '.onnx'
  11. torch.onnx.export(model, im, f, verbose=False, opset_version=12, input_names=['images'], output_names=['output'])
  12. else:
  13. f = os.path.splitext(file)[0] + '_dynamic.onnx'
  14. torch.onnx.export(model, im, f, verbose=False, opset_version=12, input_names=['images'],
  15. output_names=['output'], dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
  16. 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
  17. })
  18. try:
  19. import cv2
  20. net = cv2.dnn.readNet(f)
  21. except:
  22. exit(f'export {f} failed')
  23. exit(f'export {f} sucess')

在官方定义的export_onnx函数里插入调用这个函数,代码截图如下:

 

  1. python export.py --weights=yolov5s.pt --include=onnx --imgsz=640
  2. python export.py --weights=yolov5s6.pt --include=onnx --imgsz=1280

就能成功生成.onnx文件,并且opencv的dnn模块能读取onnx文件做推理。这两处修改都是浅表的修改,对输入输出层这块进行了一些修改,但是确实是起到了相应的作用。

三、识别(标注)软件设计
由于需要较多交互操作,选择Csharp编写界面,基于GOCW,通过clr的方式调用opencv,这些是比较成熟的方法。GOCW的相关内容可以参考Github。在实现的过程中,对软件界面进行了进一步的细化实现,
这些按钮分别对应功能如下:
打开:打开数据图片 截屏:通过屏幕截图获得 运行推断:调用识别算法 获得标注:获得标注的数据。这一点在下一小节中具体说明 保存:保存结果 比对:标注前和标注后进行比对 返回:返回标注前状态。
软件具体操作过程可以参考视频。
四、数据标注
在现有实现的数据预识别基础上,需对识别结果进行进一步标注和修正。我曾经思考是否需要自己开发相关功能,但是很快打消了这个思路。
实现格式转换,借助已有工具来实现,应该是更合理的方法。经过调研,发现roLabelImg 是专用的旋转标注工具:
它的数据格式是这样的:
  1. <annotation verified="yes">
  2. <folder>hsrc</folder>
  3. <filename>100000001</filename>
  4. <path>/Users/haoyou/Library/Mobile Documents/com~apple~CloudDocs/OneDrive/hsrc/100000001.bmp</path>
  5. <source>
  6. <database>Unknown</database>
  7. </source>
  8. <size>
  9. <width>1166</width>
  10. <height>753</height>
  11. <depth>3</depth>
  12. </size>
  13. <segmented>0</segmented>
  14. <object>
  15. <type>bndbox</type>
  16. <name>ship</name>
  17. <pose>Unspecified</pose>
  18. <truncated>0</truncated>
  19. <difficult>0</difficult>
  20. <bndbox>
  21. <xmin>178</xmin>
  22. <ymin>246</ymin>
  23. <xmax>974</xmax>
  24. <ymax>504</ymax>
  25. </bndbox>
  26. </object>
  27. <object>
  28. <type>robndbox</type>
  29. <name>ship</name>
  30. <pose>Unspecified</pose>
  31. <truncated>0</truncated>
  32. <difficult>0</difficult>
  33. <robndbox>
  34. <cx>580.7887</cx>
  35. <cy>343.2913</cy>
  36. <w>775.0449</w>
  37. <h>170.2159</h>
  38. <angle>2.889813</angle>
  39. </robndbox>
  40. </object>
  41. </annotation>
 
那么需要当前的Csharp识别(标注)工具能够生成该格式的数据,使用XmlWriter结合文本处理的方法进行进一步融合,最终结果虽然不高效,但是稳定可控的。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Xml;
  6. using System.Xml.Serialization;
  7. namespace ConsoleApp1
  8. {
  9. [XmlRoot("annotation")]
  10. public class AnnotationHead
  11. {
  12. public string folder;
  13. public string filename;
  14. public string path;
  15. public Source source;
  16. public Size size;
  17. public string segmented;
  18. }
  19. public class Size
  20. {
  21. public string width;
  22. public string height;
  23. public string depth;
  24. }
  25. public class Source
  26. {
  27. public string database;
  28. }
  29. [XmlRoot("object")]
  30. public class @object
  31. {
  32. public string type;
  33. public string name;
  34. public string pose;
  35. public string truncated;
  36. public string difficult;
  37. public robndClass robndbox;
  38. }
  39. public class robndClass
  40. {
  41. public float cx;
  42. public float cy;
  43. public float w;
  44. public float h;
  45. public float angle;
  46. }
  47. public class Test
  48. {
  49. public static void Main()
  50. {
  51. //输出规则
  52. XmlWriterSettings settings = new XmlWriterSettings();
  53. settings.Indent = true;
  54. settings.IndentChars = " ";
  55. settings.NewLineChars = "\r\n";
  56. settings.Encoding = Encoding.UTF8;
  57. settings.OmitXmlDeclaration = true; // 不生成声明头
  58. XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  59. namespaces.Add(string.Empty, string.Empty);
  60. //输出对象
  61. FileStream stream = new FileStream("part1.xml", FileMode.Create);
  62. /Part1///
  63. AnnotationHead an = new AnnotationHead();
  64. an.folder = "sandbox";
  65. an.filename = "2022-10-29 15-19-25";
  66. an.path = "F:/sandbox/2022-10-29 15-19-25.png";
  67. Source source = new Source();
  68. source.database = "Unknown";
  69. an.source = source;
  70. Size size = new Size();
  71. size.width = "1873";
  72. size.height = "935";
  73. size.depth = "3";
  74. an.size = size;
  75. an.segmented = "0";
  76. //实施输出
  77. XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
  78. XmlSerializer serializer = new XmlSerializer(typeof(AnnotationHead));
  79. serializer.Serialize(xmlWriter, an, namespaces);
  80. //目标销毁
  81. xmlWriter.Close();
  82. stream.Close();
  83. /Part2///
  84. stream = new FileStream("part2.xml", FileMode.Create);
  85. //定义方法
  86. robndClass il = new robndClass();
  87. il.cx = (float)1484.1;
  88. il.cy = (float)521.7274;
  89. il.w = (float)40.1731;
  90. il.h = (float)194.3416;
  91. il.angle = (float)0.18;
  92. @object o = new @object();
  93. o.type = "robndbox";
  94. o.name = "ship";
  95. o.pose = "Unspecified";
  96. o.truncated = "0";
  97. o.difficult = "0";
  98. o.robndbox = il;
  99. List<@object> objectList = new List<@object>();
  100. objectList.Add(o);
  101. objectList.Add(o);
  102. objectList.Add(o);
  103. serializer = new XmlSerializer(typeof(List<@object>));
  104. XmlWriter xmlWriter2 = XmlWriter.Create(stream, settings);
  105. serializer.Serialize(xmlWriter2, objectList, namespaces);
  106. xmlWriter2.Close();
  107. stream.Close();
  108. ///merge//
  109. StreamReader sr = new StreamReader("part1.xml");
  110. string strPart1 = sr.ReadToEnd();
  111. strPart1 = strPart1.Substring(0, strPart1.Length - 13);
  112. sr.Close();
  113. sr = new StreamReader("part2.xml");
  114. string strPart2 = sr.ReadToEnd();
  115. strPart2 = strPart2.Substring(15, strPart2.Length - 31);
  116. sr.Close();
  117. string strOut = strPart1 + strPart2 + "</annotation>";
  118. ////输出///
  119. using (StreamWriter sw = new StreamWriter("result.xml"))
  120. {
  121. sw.Write(strOut);
  122. }
  123. }
  124. }
  125. }

进一步重构和融合:
    
  1. public static void Main()
  2. {
  3. AnnotationHead an = new AnnotationHead();
  4. an.folder = "sandbox";
  5. an.filename = "2022-10-29 15-19-25";
  6. an.path = "F:/sandbox/2022-10-29 15-19-25.png";
  7. Source source = new Source();
  8. source.database = "Unknown";
  9. an.source = source;
  10. Size size = new Size();
  11. size.width = "18443";
  12. size.height = "935";
  13. size.depth = "3";
  14. an.size = size;
  15. an.segmented = "0";
  16. robndClass il = new robndClass();
  17. il.cx = (float)1484.1;
  18. il.cy = (float)521.7274;
  19. il.w = (float)40.1731;
  20. il.h = (float)194.3416;
  21. il.angle = (float)0.18;
  22. @object o = new @object();
  23. o.type = "robndbox";
  24. o.name = "ship";
  25. o.pose = "Unspecified";
  26. o.truncated = "0";
  27. o.difficult = "0";
  28. o.robndbox = il;
  29. List<@object> objectList = new List<@object>();
  30. objectList.Add(o);
  31. objectList.Add(o);
  32. objectList.Add(o);
  33. objectList.Add(o);
  34. objectList.Add(o);
  35. AnnotationClass ac = new AnnotationClass(an,objectList,"r2.xml");
  36. ac.action();
  37. }
  38. }
  39. using System;
  40. using System.Collections.Generic;
  41. using System.Linq;
  42. using System.Text;
  43. using System.Xml;
  44. using System.IO;
  45. using System.Xml.Serialization;
  46. namespace ConsoleApp1
  47. {
  48. [XmlRoot("annotation")]
  49. public class AnnotationHead
  50. {
  51. public string folder;
  52. public string filename;
  53. public string path;
  54. public Source source;
  55. public Size size;
  56. public string segmented;
  57. }
  58. public class Size
  59. {
  60. public string width;
  61. public string height;
  62. public string depth;
  63. }
  64. public class Source
  65. {
  66. public string database;
  67. }
  68. [XmlRoot("object")]
  69. public class @object
  70. {
  71. public string type;
  72. public string name;
  73. public string pose;
  74. public string truncated;
  75. public string difficult;
  76. public robndClass robndbox;
  77. }
  78. public class robndClass
  79. {
  80. public float cx;
  81. public float cy;
  82. public float w;
  83. public float h;
  84. public float angle;
  85. }
  86. class AnnotationClass
  87. {
  88. private string strOutName;//输出文件名称
  89. private AnnotationHead an;
  90. private List<@object> objectList;
  91. //构造函数
  92. public AnnotationClass(AnnotationHead annotatonHead, List<@object> olist, string strName = "result.xml")
  93. {
  94. an = annotatonHead;
  95. strOutName = strName;
  96. objectList = olist;
  97. }
  98. public void action()
  99. {
  100. //输出规则
  101. XmlWriterSettings settings = new XmlWriterSettings();
  102. settings.Indent = true;
  103. settings.IndentChars = " ";
  104. settings.NewLineChars = "\r\n";
  105. settings.Encoding = Encoding.UTF8;
  106. settings.OmitXmlDeclaration = true; // 不生成声明头
  107. XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  108. namespaces.Add(string.Empty, string.Empty);
  109. //输出对象
  110. FileStream stream = new FileStream("part1.xml", FileMode.Create);
  111. /Part1///
  112. //实施输出
  113. XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
  114. XmlSerializer serializer = new XmlSerializer(typeof(AnnotationHead));
  115. serializer.Serialize(xmlWriter, an, namespaces);
  116. //目标销毁
  117. xmlWriter.Close();
  118. stream.Close();
  119. /Part2///
  120. stream = new FileStream("part2.xml", FileMode.Create);
  121. //定义方法
  122. serializer = new XmlSerializer(typeof(List<@object>));
  123. XmlWriter xmlWriter2 = XmlWriter.Create(stream, settings);
  124. serializer.Serialize(xmlWriter2, objectList, namespaces);
  125. xmlWriter2.Close();
  126. stream.Close();
  127. ///merge//
  128. StreamReader sr = new StreamReader("part1.xml");
  129. string strPart1 = sr.ReadToEnd();
  130. strPart1 = strPart1.Substring(0, strPart1.Length - 13);
  131. sr.Close();
  132. sr = new StreamReader("part2.xml");
  133. string strPart2 = sr.ReadToEnd();
  134. strPart2 = strPart2.Substring(15, strPart2.Length - 31);
  135. sr.Close();
  136. string strOut = strPart1 + strPart2 + "</annotation>";
  137. ////输出///
  138. using (StreamWriter sw = new StreamWriter(strOutName))
  139. {
  140. sw.Write(strOut);
  141. }
  142. }
  143. }
  144. }
这里值得注意的一点是,CSL和OpenCV中角度转换的对应关系应该是:

经过修改后,显示的结果也是准确的:
在全部图片上显示的效果为: 
五、结果转换
标注的roImageLabel格式的数据,最后要转换为yolov5_obb的格式,并且导入到Dota数据集中。这块由于实际项目还未涉及,整编一些现有的资料,已经存在相关的工具:
BboxToolkit is a light codebase collecting some practical functions for the special-shape detection, such as oriented detection. The whole project is written by python, which can run in different platform without compliation. We use this project to support the oriented detection benchmark OBBDetection.

下载安装好后,配置BboxToolkit/tools路径下的split_configs/dota1_0/ss_train.json文件。根据需求更改参数。更改BboxToolkit/BboxToolkit/datasets/misc.py文件中的dota1_0中的类别

现在有xywhθ标注的数据集,要转换成dota标注的格式

使用如下代码,路径需要自己修改:

  1. import math
  2. import shutil
  3. import os
  4. import numpy as np
  5. import xml.etree.ElementTree as et
  6. dataset_dir = r'D:\dataset\sar\RSDD\RSDD-SAR\JPEGImages'
  7. ana_dir = r'D:\dataset\sar\RSDD\RSDD-SAR\Annotations'
  8. save_dir = r'D:\dataset\sar\RSDD\dota'
  9. data_type = 'test'
  10. train_img_dir = r'D:\dataset\sar\RSDD\RSDD-SAR\ImageSets\test.txt'
  11. f1 = open(train_img_dir, 'r')
  12. train_img = f1.readlines()
  13. def rota(center_x1, center_y1, x, y, w, h, a): # 旋转中心点,旋转中心点,框的w,h,旋转角
  14. # a = (math.pi * a) / 180 # 角度转弧度
  15. x1, y1 = x - w / 2, y - h / 2 # 旋转前左上
  16. x2, y2 = x + w / 2, y - h / 2 # 旋转前右上
  17. x3, y3 = x + w / 2, y + h / 2 # 旋转前右下
  18. x4, y4 = x - w / 2, y + h / 2 # 旋转前左下
  19. px1 = (x1 - center_x1) * math.cos(a) - (y1 - center_y1) * math.sin(a) + center_x1 # 旋转后左上
  20. py1 = (x1 - center_x1) * math.sin(a) + (y1 - center_y1) * math.cos(a) + center_y1
  21. px2 = (x2 - center_x1) * math.cos(a) - (y2 - center_y1) * math.sin(a) + center_x1 # 旋转后右上
  22. py2 = (x2 - center_x1) * math.sin(a) + (y2 - center_y1) * math.cos(a) + center_y1
  23. px3 = (x3 - center_x1) * math.cos(a) - (y3 - center_y1) * math.sin(a) + center_x1 # 旋转后右下
  24. py3 = (x3 - center_x1) * math.sin(a) + (y3 - center_y1) * math.cos(a) + center_y1
  25. px4 = (x4 - center_x1) * math.cos(a) - (y4 - center_y1) * math.sin(a) + center_x1 # 旋转后左下
  26. py4 = (x4 - center_x1) * math.sin(a) + (y4 - center_y1) * math.cos(a) + center_y1
  27. return px1, py1, px2, py2, px3, py3, px4, py4 # 旋转后的四个点,左上,右上,右下,左下
  28. for img in train_img:
  29. shutil.copy(os.path.join(dataset_dir, img[:-1] + '.jpg'),
  30. os.path.join(save_dir, data_type, 'images', img[:-1] + '.jpg'))
  31. xml_file = open(os.path.join(ana_dir, img[:-1] + '.xml'), encoding='utf-8')
  32. tree = et.parse(xml_file)
  33. root = tree.getroot()
  34. with open(os.path.join(save_dir, data_type, 'labelTxt', img[:-1] + '.txt'), 'w') as f:
  35. f.write('imagesource:GoogleEarth\ngsd:NaN\n')
  36. for obj in root.iter('object'):
  37. cls = obj.find('name').text
  38. box = obj.find('robndbox')
  39. x_c = box.find('cx').text
  40. y_c = box.find('cy').text
  41. h = box.find('h').text
  42. w = box.find('w').text
  43. theta = box.find('angle').text
  44. box = list(map(np.float16, [x_c, y_c, h, w, theta]))
  45. box = rota(box[0], box[1], *box)
  46. box = list(map(int, box))
  47. box = list(map(str, box))
  48. f.write(' '.join(box))
  49. f.write(' ' + cls + ' 0\n')
六、矛盾困难
       未来项目真实使用的场景,其图像体量肯定和dota数据集是有差距的,这样预识别肯定是有难度和错误的。但是首先通过小批量标注实现部分识别结果,而后进行迭代的方法肯定是需要实现的。此外,我们可以考虑调用融合比如easydl的方法功能。最为关键的,是找到实际需要的应用场景,才能将这个流程打通,只有这样才能够获得有用的数据集。
总结项目,关键点如下:
1、yolov5_obb的c++推断编写;
2、识别结果在roimagelabel和yolov5格式之间相关转换;
3、csharp编写界面,c++调用OpenCV实现图像处理的融合。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/83694
推荐阅读
相关标签
  

闽ICP备14008679号