1. #split.py 文件 输入格式为images ,和标签txt文件,txt中的数据为坐标值共8个。
  2.  
  3. import os
  4. import numpy as np
  5. import math
  6. import cv2 as cv
  7. import imageio
  8.  
  9. #path = '/media/D/code/OCR/text-detection-ctpn/data/mlt_english+chinese/image'
  10. #path = '/home/chendali1/Gsj/text-detection-ctpn-master/prepare_training_data/image/image_1000/'
  11. path='/home/chendali1/Gsj/prepare_training_data/ICDAR/images_train/'
  12. #gt_path = '/home/chendali1/Gsj/text-detection-ctpn-master/prepare_training_data/label/labelDigit1000/'
  13. gt_path='/home/chendali1/Gsj/prepare_training_data/ICDAR/result_train/'
  14. out_path = 're_image'
  15. if not os.path.exists(out_path):
  16. os.makedirs(out_path)
  17. files = os.listdir(path)
  18. files.sort()
  19. #files=files[:100]
  20. for file in files:
  21. _, basename = os.path.split(file)
  22. if basename.lower().split('.')[-1] not in ['jpg', 'png']:
  23. continue
  24. stem, ext = os.path.splitext(basename)
  25.  
  26. #stem=stem0.split('_')[2]
  27.  
  28. gt_file = os.path.join(gt_path, stem+'.txt')
  29. img_path = os.path.join(path, file)
  30. print(img_path)
  31. #print(gt_file)
  32. img = cv.imread(img_path)
  33. if img is None:
  34. print('****************************')
  35. print('Image ' + img_path + ' may be a bad picture!')
  36. print('****************************')
  37. newname = os.path.join(path,stem+'.gif')
  38. os.rename(img_path,newname)
  39. img_path=newname
  40. print(img_path)
  41. print('Try read with imageio.')
  42. gif = imageio.mimread(img_path)
  43. if gif is None:
  44. print('****************************')
  45. print("Image " + img_path + " can't be read!")
  46. print('****************************')
  47.  
  48. print('Read success!')
  49. img = cv.cvtColor(gif[0], cv.COLOR_RGB2BGR)
  50.  
  51. img_size = img.shape
  52. im_size_min = np.min(img_size[0:2])
  53. im_size_max = np.max(img_size[0:2])
  54.  
  55. im_scale = float(600) / float(im_size_min)
  56. if np.round(im_scale * im_size_max) > 1200:
  57. im_scale = float(1200) / float(im_size_max)
  58. re_im = cv.resize(img, None, None, fx=im_scale, fy=im_scale, interpolation=cv.INTER_LINEAR)
  59. re_size = re_im.shape
  60. cv.imwrite(os.path.join(out_path, stem) + '.jpg', re_im)
  61.  
  62. with open(gt_file, 'r') as f:
  63. lines = f.readlines()
  64. for line in lines:
  65. splitted_line = line.strip().lower().split(',')
  66. pt_x = np.zeros((4, 1))
  67. pt_y = np.zeros((4, 1))
  68. pt_x[0, 0] = int(float(splitted_line[0]) / img_size[1] * re_size[1])
  69. pt_y[0, 0] = int(float(splitted_line[1]) / img_size[0] * re_size[0])
  70. pt_x[1, 0] = int(float(splitted_line[2]) / img_size[1] * re_size[1])
  71. pt_y[1, 0] = int(float(splitted_line[3]) / img_size[0] * re_size[0])
  72. pt_x[2, 0] = int(float(splitted_line[4]) / img_size[1] * re_size[1])
  73. pt_y[2, 0] = int(float(splitted_line[5]) / img_size[0] * re_size[0])
  74. pt_x[3, 0] = int(float(splitted_line[6]) / img_size[1] * re_size[1])
  75. pt_y[3, 0] = int(float(splitted_line[7]) / img_size[0] * re_size[0])
  76.  
  77. ind_x = np.argsort(pt_x, axis=0)
  78. pt_x = pt_x[ind_x]
  79. pt_y = pt_y[ind_x]
  80.  
  81. if pt_y[0] < pt_y[1]:
  82. pt1 = (pt_x[0], pt_y[0])
  83. pt3 = (pt_x[1], pt_y[1])
  84. else:
  85. pt1 = (pt_x[1], pt_y[1])
  86. pt3 = (pt_x[0], pt_y[0])
  87.  
  88. if pt_y[2] < pt_y[3]:
  89. pt2 = (pt_x[2], pt_y[2])
  90. pt4 = (pt_x[3], pt_y[3])
  91. else:
  92. pt2 = (pt_x[3], pt_y[3])
  93. pt4 = (pt_x[2], pt_y[2])
  94.  
  95. xmin = int(min(pt1[0], pt2[0]))
  96. ymin = int(min(pt1[1], pt2[1]))
  97. xmax = int(max(pt2[0], pt4[0]))
  98. ymax = int(max(pt3[1], pt4[1]))
  99.  
  100. if xmin < 0:
  101. xmin = 0
  102. if xmax > re_size[1] - 1:
  103. xmax = re_size[1] - 1
  104. if ymin < 0:
  105. ymin = 0
  106. if ymax > re_size[0] - 1:
  107. ymax = re_size[0] - 1
  108.  
  109. width = xmax - xmin
  110. height = ymax - ymin
  111.  
  112. # reimplement
  113. step = 16.0
  114. x_left = []
  115. x_right = []
  116. x_left.append(xmin)
  117. x_left_start = int(math.ceil(xmin / 16.0) * 16.0)
  118. if x_left_start == xmin:
  119. x_left_start = xmin + 16
  120. for i in np.arange(x_left_start, xmax, 16):
  121. x_left.append(i)
  122. x_left = np.array(x_left)
  123.  
  124. x_right.append(x_left_start - 1)
  125. for i in range(1, len(x_left) - 1):
  126. x_right.append(x_left[i] + 15)
  127. x_right.append(xmax)
  128. x_right = np.array(x_right)
  129.  
  130. idx = np.where(x_left == x_right)
  131. x_left = np.delete(x_left, idx, axis=0)
  132. x_right = np.delete(x_right, idx, axis=0)
  133.  
  134. if not os.path.exists('label_tmp'):
  135. os.makedirs('label_tmp')
  136. with open(os.path.join('label_tmp', stem) + '.txt', 'a') as f:
  137. #for i in range(len(x_left)):
  138. f.writelines("tianchi\t")
  139. f.writelines(str(int( pt_x[0, 0])))
  140. f.writelines("\t")
  141. f.writelines(str(int( pt_y[0, 0])))
  142. f.writelines("\t")
  143. f.writelines(str(int( pt_x[1, 0])))
  144. f.writelines("\t")
  145. f.writelines(str(int( pt_y[1, 0])))
  146. f.writelines("\t")
  147. f.writelines(str(int( pt_x[2, 0])))
  148. f.writelines("\t")
  149. f.writelines(str(int( pt_y[2, 0])))
  150. f.writelines("\t")
  151. f.writelines(str(int( pt_x[3, 0])))
  152. f.writelines("\t")
  153. f.writelines(str(int( pt_y[3, 0])))
  154. f.writelines("\n")
  1. #ToVoc.py 上述执行完后直接运行这个脚本文件完美生成VOC文件
  2. from xml.dom.minidom import Document
  3. import cv2
  4. import os
  5. import glob
  6. import shutil
  7. import numpy as np
  8.  
  9. def generate_xml(name, lines, img_size, class_sets, doncateothers=True):
  10. doc = Document()
  11.  
  12. def append_xml_node_attr(child, parent=None, text=None):
  13. ele = doc.createElement(child)
  14. if not text is None:
  15. text_node = doc.createTextNode(text)
  16. ele.appendChild(text_node)
  17. parent = doc if parent is None else parent
  18. parent.appendChild(ele)
  19. return ele
  20.  
  21. img_name = name + '.jpg'
  22. # create header
  23. annotation = append_xml_node_attr('annotation')
  24. append_xml_node_attr('folder', parent=annotation, text='tianchi')
  25. append_xml_node_attr('filename', parent=annotation, text=img_name)
  26. source = append_xml_node_attr('source', parent=annotation)
  27. append_xml_node_attr('database', parent=source, text='coco_text_database')
  28. append_xml_node_attr('annotation', parent=source, text='tianchi')
  29. append_xml_node_attr('image', parent=source, text='tianchi')
  30. append_xml_node_attr('flickrid', parent=source, text='')
  31. owner = append_xml_node_attr('owner', parent=annotation)
  32. append_xml_node_attr('name', parent=owner, text='ms')
  33. size = append_xml_node_attr('size', annotation)
  34. append_xml_node_attr('width', size, str(img_size[1]))
  35. append_xml_node_attr('height', size, str(img_size[0]))
  36. append_xml_node_attr('depth', size, str(img_size[2]))
  37. append_xml_node_attr('segmented', parent=annotation, text='')
  38.  
  39. # create objects
  40. objs = []
  41. for line in lines:
  42. splitted_line = line.strip().lower().split()
  43. cls = splitted_line[0].lower()
  44. if not doncateothers and cls not in class_sets:
  45. continue
  46. cls = 'dontcare' if cls not in class_sets else cls
  47. if cls == 'dontcare':
  48. continue
  49. obj = append_xml_node_attr('object', parent=annotation)
  50. occlusion = int(0)
  51. x1, y1, x2, y2 = int(float(splitted_line[1]) + 1), int(float(splitted_line[2]) + 1), \
  52. int(float(splitted_line[3]) + 1), int(float(splitted_line[4]) + 1)
  53. x0,y0,x1,y1,x2,y2,x3,y3 = int(float(splitted_line[1])+1),int(float(splitted_line[2])+1),\
  54. int(float(splitted_line[3])+1),int(float(splitted_line[4])+1),int(float(splitted_line[5])+1),\
  55. int(float(splitted_line[6])+1),int(float(splitted_line[7])+1),int(float(splitted_line[8])+1)
  56. truncation = float(0)
  57. difficult = 1 if _is_hard(cls, truncation, occlusion, x1, y1, x2, y2) else 0
  58. truncted = 0 if truncation < 0.5 else 1
  59.  
  60. append_xml_node_attr('name', parent=obj, text=cls)
  61. append_xml_node_attr('pose', parent=obj, text='none')
  62. append_xml_node_attr('truncated', parent=obj, text=str(truncted))
  63. append_xml_node_attr('difficult', parent=obj, text=str(int(difficult)))
  64. bb = append_xml_node_attr('bndbox', parent=obj)
  65. append_xml_node_attr('x0', parent=bb, text=str(int(x0)))
  66. append_xml_node_attr('y0', parent=bb, text=str(y0))
  67. append_xml_node_attr('x1', parent=bb, text=str(x1))
  68. append_xml_node_attr('y1', parent=bb, text=str(y1))
  69. append_xml_node_attr('x1', parent=bb, text=str(x2))
  70. append_xml_node_attr('y1', parent=bb, text=str(y2))
  71. append_xml_node_attr('x1', parent=bb, text=str(x3))
  72. append_xml_node_attr('y1', parent=bb, text=str(y3))
  73.  
  74. o = {'class': cls, 'box': np.asarray([x0, y0,x1,y1, x2, y2,x3,y3], dtype=float), \
  75. 'truncation': truncation, 'difficult': difficult, 'occlusion': occlusion}
  76. objs.append(o)
  77.  
  78. return doc, objs
  79.  
  80. def _is_hard(cls, truncation, occlusion, x1, y1, x2, y2):
  81. hard = False
  82. if y2 - y1 < 25 and occlusion >= 2:
  83. hard = True
  84. return hard
  85. if occlusion >= 3:
  86. hard = True
  87. return hard
  88. if truncation > 0.8:
  89. hard = True
  90. return hard
  91. return hard
  92.  
  93. def build_voc_dirs(outdir):
  94. mkdir = lambda dir: os.makedirs(dir) if not os.path.exists(dir) else None
  95. mkdir(outdir)
  96. mkdir(os.path.join(outdir, 'Annotations'))
  97. mkdir(os.path.join(outdir, 'ImageSets'))
  98. mkdir(os.path.join(outdir, 'ImageSets', 'Layout'))
  99. mkdir(os.path.join(outdir, 'ImageSets', 'Main'))
  100. mkdir(os.path.join(outdir, 'ImageSets', 'Segmentation'))
  101. mkdir(os.path.join(outdir, 'JPEGImages'))
  102. mkdir(os.path.join(outdir, 'SegmentationClass'))
  103. mkdir(os.path.join(outdir, 'SegmentationObject'))
  104. return os.path.join(outdir, 'Annotations'), os.path.join(outdir, 'JPEGImages'), os.path.join(outdir, 'ImageSets',
  105. 'Main')
  106.  
  107. if __name__ == '__main__':
  108. _outdir = 'TEXTVOC/VOC2007'
  109. _draw = bool(0)
  110. _dest_label_dir, _dest_img_dir, _dest_set_dir = build_voc_dirs(_outdir)
  111. _doncateothers = bool(1)
  112. for dset in ['train']:
  113. _labeldir = 'label_tmp'
  114. _imagedir = 're_image'
  115. class_sets = ('tianchi', 'dontcare')
  116. class_sets_dict = dict((k, i) for i, k in enumerate(class_sets))
  117. allclasses = {}
  118. fs = [open(os.path.join(_dest_set_dir, cls + '_' + dset + '.txt'), 'w') for cls in class_sets]
  119. ftrain = open(os.path.join(_dest_set_dir, dset + '.txt'), 'w')
  120.  
  121. files = glob.glob(os.path.join(_labeldir, '*.txt'))
  122. files.sort()
  123. for file in files:
  124. path, basename = os.path.split(file)
  125. stem, ext = os.path.splitext(basename)
  126. with open(file, 'r') as f:
  127. lines = f.readlines()
  128. img_file = os.path.join(_imagedir, stem + '.jpg')
  129.  
  130. print(img_file)
  131. img = cv2.imread(img_file)
  132. img_size = img.shape
  133.  
  134. doc, objs = generate_xml(stem, lines, img_size, class_sets=class_sets, doncateothers=_doncateothers)
  135.  
  136. cv2.imwrite(os.path.join(_dest_img_dir, stem + '.jpg'), img)
  137. xmlfile = os.path.join(_dest_label_dir, stem + '.xml')
  138. with open(xmlfile, 'w') as f:
  139. f.write(doc.toprettyxml(indent=' '))
  140.  
  141. ftrain.writelines(stem + '\n')
  142.  
  143. cls_in_image = set([o['class'] for o in objs])
  144.  
  145. for obj in objs:
  146. cls = obj['class']
  147. allclasses[cls] = 0 \
  148. if not cls in list(allclasses.keys()) else allclasses[cls] + 1
  149.  
  150. for cls in cls_in_image:
  151. if cls in class_sets:
  152. fs[class_sets_dict[cls]].writelines(stem + ' 1\n')
  153. for cls in class_sets:
  154. if cls not in cls_in_image:
  155. fs[class_sets_dict[cls]].writelines(stem + ' -1\n')
  156.  
  157. (f.close() for f in fs)
  158. ftrain.close()
  159.  
  160. print('~~~~~~~~~~~~~~~~~~~')
  161. print(allclasses)
  162. print('~~~~~~~~~~~~~~~~~~~')
  163. shutil.copyfile(os.path.join(_dest_set_dir, 'train.txt'), os.path.join(_dest_set_dir, 'val.txt'))
  164. shutil.copyfile(os.path.join(_dest_set_dir, 'train.txt'), os.path.join(_dest_set_dir, 'trainval.txt'))
  165. for cls in class_sets:
  166. shutil.copyfile(os.path.join(_dest_set_dir, cls + '_train.txt'),
  167. os.path.join(_dest_set_dir, cls + '_trainval.txt'))
  168. shutil.copyfile(os.path.join(_dest_set_dir, cls + '_train.txt'),
  169. os.path.join(_dest_set_dir, cls + '_val.txt'))

VOC数据集生成代码使用说明的更多相关文章

  1. 【Detection】物体识别-制作PASCAL VOC数据集

    PASCAL VOC数据集 PASCAL VOC为图像识别和分类提供了一整套标准化的优秀的数据集,从2005年到2012年每年都会举行一场图像识别challenge 默认为20类物体 1 数据集结构 ...

  2. 搭建 MobileNet-SSD 开发环境并使用 VOC 数据集训练 TensorFlow 模型

    原文地址:搭建 MobileNet-SSD 开发环境并使用 VOC 数据集训练 TensorFlow 模型 0x00 环境 OS: Ubuntu 1810 x64 Anaconda: 4.6.12 P ...

  3. 在Ubuntu内制作自己的VOC数据集

    一.VOC数据集的简介 PASCAL VOC为图像的识别和分类提供了一整套标准化的优秀数据集,基本上就是目标检测数据集的模板.现在有VOC2007,VOC2012.主要有20个类.而现在主要的模型评估 ...

  4. 【工具引入】uiautomatorviewer 查找元素后自动生成代码

    缘起 公司部门调整PC部门和无线部门合并,原本负责主站PC端自动化的同事需要马上上手安卓,IOS自动化.对于初次接触移动端的测试者来说,跨度还是有点大的.加之人员有些变动,不得不搞个工具降低学习成本, ...

  5. PASCAL VOC数据集分析(转)

    PASCAL VOC数据集分析 PASCAL VOC为图像识别和分类提供了一整套标准化的优秀的数据集,从2005年到2012年每年都会举行一场图像识别challenge. 本文主要分析PASCAL V ...

  6. 自动化工具制作PASCAL VOC 数据集

    自动化工具制作PASCAL VOC 数据集   1. VOC的格式 VOC主要有三个重要的文件夹:Annotations.ImageSets和JPEGImages JPEGImages 文件夹 该文件 ...

  7. Eclipse 使用mybatis generator插件自动生成代码

    Eclipse 使用mybatis generator插件自动生成代码 标签: mybatis 2016-12-07 15:10 5247人阅读 评论(0) 收藏 举报 .embody{ paddin ...

  8. 目标检测:keras-yolo3之制作VOC数据集训练指南

    制作VOC数据集指南 Github:https://github.com/hyhouyong/keras-yolo3 LabelImg标注工具(windows环境下):https://github.c ...

  9. VOC数据集 目标检测

    最近在做与目标检测模型相关的工作,很多都要求VOC格式的数据集. PASCAL VOC挑战赛 (The PASCAL Visual Object Classes )是一个世界级的计算机视觉挑战赛, P ...

随机推荐

  1. python编程 之 json包

    1,json是什么? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写. 我的理解就是:json是一种统一的格式化的文件,比如,一个jso ...

  2. ovs常用操作

    1.添加网桥:ovs-vsctl add-br 交换机名 2.删除网桥:ovs-vsctl del-br 交换机名 3.添加端口:ovs-vsctl add-port 交换机名 端口名(网卡名) 4. ...

  3. Error "Client wants topic A to have B, but our version has C. Dropping connection."

    ROS problem 出现这个问题的原因是话题上的消息类型和订阅节点指定的消息类型不匹配.

  4. CF1110D Jongmah

    题目地址:CF1110D Jongmah 约定:称形如 \([a-1,a,a+1]\) 这样的三元组为关于 \(a\) 的顺子,形如 \([a,a,a]\) 这样的三元组为关于 \(a\) 的对子. ...

  5. Python3-操作系统发展史

    操作系统发展史 手工操作 —— 穿孔卡片 批处理 —— 磁带存储 多道程序系统 操作系统的作用 手工操作 —— 穿孔卡片 1946年第一台计算机诞生--20世纪50年代中期,计算机工作还在采用手工操作 ...

  6. qunee 开发清新、高效的拓扑图组件 http://www.qunee.com/

    qunee  开发清新.高效的拓扑图组件  http://www.qunee.com/ RoadFlow:  http://www.cqroad.cn/ 村暖花开

  7. DHCP Server (推荐使用Windows)

    一些小的服务 windows做的比linux好 DHCP服务概述: 名称:DHCP (Dynamic Host Configuration Protocol --动态主机配置协议) 功能:是一个局域网 ...

  8. CANopen--实现双电机速度同步

    图1 将上图图中左边的电机和右边的电机进行速度同步,右边的电机同步左边的电机速度.这里需要知道Copley的驱动中的速度环的输入输出情况.如下图所示,速度环限制器接收速度命令信号,经限制后,产生一限制 ...

  9. 模拟电路学习之NMOS开关电路1

  10. elasticsearch中的java.io.IOException: 远程主机强迫关闭了一个现有的连接

    [2018-07-31T14:29:41,289][WARN ][o.e.x.s.t.n.SecurityNetty4HttpServerTransport] [9rTGh-y] caught exc ...