CelebA数据库转换为VOC、YOLO格式

原文:https://blog.csdn.net/minstyrain/article/details/77888176

CelebA是香港中文大学发布的20多万的名人人脸数据库,被很多算法用来训练,取得了不错的效果,其主页为http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html

它提供了人脸包围框和5个关键点的标注,都放置在一个txt文件中,这和faster-rcnn、YOLO等的要求还是有一些差距的,因此需要做些变换才能使用。

下面这个脚本实现了讲CelebA自带标注转换为VOC和YOLO格式的功能.

 
  1. import cv2,h5py,os

  2. import numpy as np

  3. from xml.dom.minidom import Document

  4. import progressbar

  5. rootdir="../"

  6. imgdir=rootdir+"Img/img_celeba"

  7. landmarkpath=rootdir+"Anno/list_landmarks_celeba.txt"

  8. bboxpath=rootdir+"Anno/list_bbox_celeba.txt"

  9. vocannotationdir=rootdir+"/"+"Annotations"

  10. labelsdir=rootdir+"/"+"labels"

  11. convet2yoloformat=True

  12. convert2vocformat=True

  13. resized_dim=(48,48)

  14. datasetprefix="/home/yanhe/data/CelebA/images/"

  15. progress = progressbar.ProgressBar(widgets=[

  16. progressbar.Percentage(),

  17. ' (', progressbar.SimpleProgress(), ') ',

  18. ' (', progressbar.Timer(), ') ',

  19. ' (', progressbar.ETA(), ') ',])

  20. def drawbboxandlandmarks(img,bbox,landmark):

  21. cv2.rectangle(img,(bbox[0],bbox[1]),(bbox[0]+bbox[2],bbox[1]+bbox[3]),(0,255,0))

  22. for i in range(int(len(landmark)/2)):

  23. cv2.circle(img,(int(landmark[2*i]),int(landmark[2*i+1])),2,(0,0,255))

  24. def loadgt():

  25. imgpaths=[]

  26. landmarks=[]

  27. bboxes=[]

  28. with open(landmarkpath) as landmarkfile:

  29. lines=landmarkfile.readlines()

  30. lines=lines[2:]

  31. for line in lines:

  32. landmarkline=line.split()

  33. imgpath=landmarkline[0]

  34. imgpaths.append(imgpath)

  35. landmarkline=landmarkline[1:]

  36. landmark=[int(str) for str in landmarkline]

  37. landmarks.append(landmark)

  38. with open(bboxpath) as bboxfile:

  39. lines=bboxfile.readlines()

  40. lines=lines[2:]

  41. for line in lines:

  42. bboxline=line.split()

  43. imgpath=bboxline[0]

  44. bboxline=bboxline[1:]

  45. bbox=[int(bb) for bb in bboxline]

  46. bboxes.append(bbox)

  47. return imgpaths,bboxes,landmarks

  48. def generate_hdf5():

  49. imgpaths,bboxes,landmarks=loadgt()

  50. numofimg=len(imgpaths)

  51. faces=[]

  52. labels=[]

  53. #numofimg=2

  54. for i in range(numofimg):

  55. imgpath=imgdir+"/"+imgpaths[i]

  56. print(i)#,imgpath)

  57. bbox=bboxes[i]

  58. landmark=landmarks[i]

  59. img=cv2.imread(imgpath)

  60. if bbox[2]<=0 or bbox[3]<=0:

  61. continue

  62. face=img[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]]

  63. face=cv2.resize(face,resized_dim)

  64. faces.append(face)

  65. label=[]

  66. label.append(1)

  67. for i in range(len(bbox)):

  68. label.append(bbox[i])

  69. for i in range(len(landmark)):

  70. lm=landmark[i]

  71. if i%2==0:

  72. lm=(lm-bbox[0])*1.0/(bbox[2])

  73. else:

  74. lm=(lm-bbox[1])*1.0/(bbox[3])

  75. label.append(lm)

  76. labels.append(label)

  77. faces=np.asarray(faces)

  78. labels=np.asarray(labels)

  79. f=h5py.File('train.h5','w')

  80. f['data']=faces.astype(np.float32)

  81. f['labels']=labels.astype(np.float32)

  82. f.close()

  83. def viewginhdf5():

  84. f = h5py.File('train.h5','r')

  85. f.keys()

  86. faces=f['data'][:]

  87. labels=f['labels'][:]

  88. for i in range(len(faces)):

  89. print(i)

  90. face=faces[i].astype(np.uint8)

  91. label=labels[i]

  92. bbox=label[1:4]

  93. landmark=label[5:]

  94. for i in range(int(len(landmark)/2)):

  95. cv2.circle(face,(int(landmark[2*i]*resized_dim[0]),int(landmark[2*i+1]*resized_dim[1])),1,(0,0,255))

  96. cv2.imshow("img",face)

  97. cv2.waitKey()

  98. f.close()

  99. def showgt():

  100. landmarkfile=open(landmarkpath)

  101. bboxfile=open(bboxpath)

  102. numofimgs=int(landmarkfile.readline())

  103. _=landmarkfile.readline()

  104. _=bboxfile.readline()

  105. _=bboxfile.readline()

  106. index=0

  107. pbar = progress.start()

  108. if convet2yoloformat:

  109. if not os.path.exists(labelsdir):

  110. os.mkdir(labelsdir)

  111. if convert2vocformat:

  112. if not os.path.exists(vocannotationdir):

  113. os.mkdir(vocannotationdir)

  114. # while(index<numofimgs):

  115. for i in pbar(range(numofimgs)):

  116. #pbar.update(int((index/(numofimgs-1))*10000))

  117. landmarkline=landmarkfile.readline().split()

  118. filename=landmarkline[0]

  119. #sys.stdout.write("\r"+str(index)+":"+filename)

  120. #sys.stdout.flush()

  121. imgpath=imgdir+"/"+filename

  122. img=cv2.imread(imgpath)

  123. landmarkline=landmarkline[1:]

  124. landmark=[int(pt) for pt in landmarkline]

  125. bboxline=bboxfile.readline().split()

  126. imgpath2=imgdir+"/"+bboxline[0]

  127. bboxline=bboxline[1:]

  128. bbox=[int(bb) for bb in bboxline]

  129. drawbboxandlandmarks(img,bbox,landmark)

  130. if convet2yoloformat:

  131. height=img.shape[0]

  132. width=img.shape[1]

  133. txtpath=labelsdir+"/"+filename

  134. txtpath=txtpath[:-3]+"txt"

  135. ftxt=open(txtpath,'w')

  136. xcenter=(bbox[0]+bbox[2]*0.5)/width

  137. ycenter=(bbox[1]+bbox[3]*0.5)/height

  138. wr=bbox[2]*1.0/width

  139. hr=bbox[3]*1.0/height

  140. line="0 "+str(xcenter)+" "+str(ycenter)+" "+str(wr)+" "+str(hr)+"\n"

  141. ftxt.write(line)

  142. ftxt.close()

  143. if convert2vocformat:

  144. xmlpath=vocannotationdir+"/"+filename

  145. xmlpath=xmlpath[:-3]+"xml"

  146. doc = Document()

  147. annotation = doc.createElement('annotation')

  148. doc.appendChild(annotation)

  149. folder = doc.createElement('folder')

  150. folder_name = doc.createTextNode('CelebA')

  151. folder.appendChild(folder_name)

  152. annotation.appendChild(folder)

  153. filenamenode = doc.createElement('filename')

  154. filename_name = doc.createTextNode(filename)

  155. filenamenode.appendChild(filename_name)

  156. annotation.appendChild(filenamenode)

  157. source = doc.createElement('source')

  158. annotation.appendChild(source)

  159. database = doc.createElement('database')

  160. database.appendChild(doc.createTextNode('CelebA Database'))

  161. source.appendChild(database)

  162. annotation_s = doc.createElement('annotation')

  163. annotation_s.appendChild(doc.createTextNode('PASCAL VOC2007'))

  164. source.appendChild(annotation_s)

  165. image = doc.createElement('image')

  166. image.appendChild(doc.createTextNode('flickr'))

  167. source.appendChild(image)

  168. flickrid = doc.createElement('flickrid')

  169. flickrid.appendChild(doc.createTextNode('-1'))

  170. source.appendChild(flickrid)

  171. owner = doc.createElement('owner')

  172. annotation.appendChild(owner)

  173. flickrid_o = doc.createElement('flickrid')

  174. flickrid_o.appendChild(doc.createTextNode('tdr'))

  175. owner.appendChild(flickrid_o)

  176. name_o = doc.createElement('name')

  177. name_o.appendChild(doc.createTextNode('yanyu'))

  178. owner.appendChild(name_o)

  179. size = doc.createElement('size')

  180. annotation.appendChild(size)

  181. width = doc.createElement('width')

  182. width.appendChild(doc.createTextNode(str(img.shape[1])))

  183. height = doc.createElement('height')

  184. height.appendChild(doc.createTextNode(str(img.shape[0])))

  185. depth = doc.createElement('depth')

  186. depth.appendChild(doc.createTextNode(str(img.shape[2])))

  187. size.appendChild(width)

  188. size.appendChild(height)

  189. size.appendChild(depth)

  190. segmented = doc.createElement('segmented')

  191. segmented.appendChild(doc.createTextNode('0'))

  192. annotation.appendChild(segmented)

  193. for i in range(1):

  194. objects = doc.createElement('object')

  195. annotation.appendChild(objects)

  196. object_name = doc.createElement('name')

  197. object_name.appendChild(doc.createTextNode('face'))

  198. objects.appendChild(object_name)

  199. pose = doc.createElement('pose')

  200. pose.appendChild(doc.createTextNode('Unspecified'))

  201. objects.appendChild(pose)

  202. truncated = doc.createElement('truncated')

  203. truncated.appendChild(doc.createTextNode('1'))

  204. objects.appendChild(truncated)

  205. difficult = doc.createElement('difficult')

  206. difficult.appendChild(doc.createTextNode('0'))

  207. objects.appendChild(difficult)

  208. bndbox = doc.createElement('bndbox')

  209. objects.appendChild(bndbox)

  210. xmin = doc.createElement('xmin')

  211. xmin.appendChild(doc.createTextNode(str(bbox[0])))

  212. bndbox.appendChild(xmin)

  213. ymin = doc.createElement('ymin')

  214. ymin.appendChild(doc.createTextNode(str(bbox[1])))

  215. bndbox.appendChild(ymin)

  216. xmax = doc.createElement('xmax')

  217. xmax.appendChild(doc.createTextNode(str(bbox[0]+bbox[2])))

  218. bndbox.appendChild(xmax)

  219. ymax = doc.createElement('ymax')

  220. ymax.appendChild(doc.createTextNode(str(bbox[1]+bbox[3])))

  221. bndbox.appendChild(ymax)

  222. f=open(xmlpath,"w")

  223. f.write(doc.toprettyxml(indent = ''))

  224. f.close()

  225. cv2.imshow("img",img)

  226. cv2.waitKey(1)

  227. index=index+1

  228. pbar.finish()

  229. def generatetxt(trainratio=0.7,valratio=0.2,testratio=0.1):

  230. files=os.listdir(labelsdir)

  231. ftrain=open(rootdir+"/"+"train.txt","w")

  232. fval=open(rootdir+"/"+"val.txt","w")

  233. ftrainval=open(rootdir+"/"+"trainval.txt","w")

  234. ftest=open(rootdir+"/"+"test.txt","w")

  235. index=0

  236. for i in range(len(files)):

  237. filename=files[i]

  238. filename=datasetprefix+filename[:-3]+"jpg"+"\n"

  239. if i<trainratio*len(files):

  240. ftrain.write(filename)

  241. ftrainval.write(filename)

  242. elif i<(trainratio+valratio)*len(files):

  243. fval.write(filename)

  244. ftrainval.write(filename)

  245. elif i<(trainratio+valratio+testratio)*len(files):

  246. ftest.write(filename)

  247. ftrain.close()

  248. fval.close()

  249. ftrainval.close()

  250. ftest.close()

  251. def generatevocsets(trainratio=0.7,valratio=0.2,testratio=0.1):

  252. if not os.path.exists(rootdir+"/ImageSets"):

  253. os.mkdir(rootdir+"/ImageSets")

  254. if not os.path.exists(rootdir+"/ImageSets/Main"):

  255. os.mkdir(rootdir+"/ImageSets/Main")

  256. ftrain=open(rootdir+"/ImageSets/Main/train.txt",'w')

  257. fval=open(rootdir+"/ImageSets/Main/val.txt",'w')

  258. ftrainval=open(rootdir+"/ImageSets/Main/trainval.txt",'w')

  259. ftest=open(rootdir+"/ImageSets/Main/test.txt",'w')

  260. files=os.listdir(labelsdir)

  261. for i in range(len(files)):

  262. imgfilename=files[i][:-4]

  263. ftrainval.write(imgfilename+"\n")

  264. if i<int(len(files)*trainratio):

  265. ftrain.write(imgfilename+"\n")

  266. elif i<int(len(files)*(trainratio+valratio)):

  267. fval.write(imgfilename+"\n")

  268. else:

  269. ftest.write(imgfilename+"\n")

  270. ftrain.close()

  271. fval.close()

  272. ftrainval.close()

  273. ftest.close()

  274. if __name__=="__main__":

  275. showgt()

  276. generatevocsets()

  277. generatetxt()

  278. #generate_hdf5()

CelebA数据库转换为VOC、YOLO格式相关推荐

  1. 将VOC格式标注文件转换为Yolo格式

    这篇文章主要参考博客中的代码,对原博客VOC格式数据集转yolo格式代码进行一定修改.添加注释,此外还在后面添加了我自己写的一段关于对转换后的图片和标注文件进行整理的脚本代码. 关于数据集在Yolo格 ...

  2. 将Yolo格式标注文件转换为VOC格式

    这篇文章主要参考博客Yolo标准数据集格式转Voc数据集中的代码,对原博客代码进行一定修改.添加注释,此外还在后面添加了我自己写的一段关于对转换后的标注文件进行整理的脚本代码. Yolo标注的格式与V ...

  3. 把LabelImg标注的YOLO格式标签转化为VOC格式标签 和 把VOC格式标签转化为YOLO格式标签

    把LabelImg标注的YOLO格式标签转化为VOC格式标签 和 把VOC格式标签转化为YOLO格式标签 文章目录: 1 用LabelImgvoc和yolo标注标签格式说明 1.1 LabelImg标 ...

  4. VOC格式xml标签与YOLO格式txt标签相互转换

    转自:LabelImg标注的VOC格式xml标签与YOLO格式txt标签相互转换_wangmj_hdu的博客-CSDN博客 1.VOC标签格式说明 VOC数据格式,会直接把每张图片标注的标签信息保存到 ...

  5. labelimg标注的VOC格式标签xml文件和yolo格式标签txt文件相互转换

    目录 1 labelimg标注VOC格式和yolo格式介绍 1.1 voc格式 1.2 yolo数据格式介绍 2 voc格式数据和yolo格式数据相互转换 2.1 voc转yolo代码 2.2 yol ...

  6. 将widerface标注转换为VOC格式

    验证工具代码: https://github.com/wondervictor/WiderFace-Evaluation 将widerface标注转换为VOC格式 原文:https://blog.cs ...

  7. voc数据集格式转换为coco数据集格式+修改xml格式文件

    voc数据集格式转换为coco格式+修改xml格式文件中部分内容 voc数据集格式→coco数据集格式 修改xml格式文件中部分内容 voc数据集格式→coco数据集格式 下面这份代码只需修改文件所在 ...

  8. 将fddb标注转换为VOC格式标注

    fddb是用来评估人脸检测性能事实上的标准,它给出了10折验证椭圆格式的标注,这和faster-rcnn以及SSD等的要求是不一样的,因此需要转换为VOC格式. 难点在于如何得到椭圆的外接矩形,我采用 ...

  9. 彻底搞懂VOC/YOLO标注格式《补充》

    引言:在深度学习中,标注格式占据了半壁江山,没有这些标注,深度学习就是盲人摸象(只针对有监督学习哦!!!),就像是深度学习网络的先验知识,或者说是'考试时,老师画的重点'.在很长一段时间处于迷茫状态, ...

最新文章

  1. java 常见几种发送http请求案例
  2. mysql多源复制脚本_Mysql多源复制
  3. 维吉尼亚c语言编码原理,维吉尼亚密码的C语言实现.doc
  4. 理解TCP为什么需要进行三次握手(白话)(转载)
  5. 3.3-3.9 周记
  6. 给大家介绍一个好用的数据分析框架
  7. IIS里FTP多用户设置,终于不用Serv-U了,很方便,个人用够用了
  8. linux 22端口被墙,Linode被墙SSH无法连接通过Lish连接方法
  9. finder怎么才能找到library
  10. CSS动画实现滚动播放
  11. Flutter监听网络变化
  12. dbf文件转excel_Excel批量转PDF,关键一步不能忘
  13. 如何根据MAC地址获取设备厂商
  14. Win8.1激活方法
  15. 嵌入式软件开发必备知识体系
  16. 计算机音乐谱子 追光者,精选追光者简谱
  17. Linux系统10个开源漏洞检测工具
  18. 全国高级项目经理人数知多少?(数据统计截止2013年6月22日)
  19. 微信小程序授权文件放到域名根目录下
  20. 论文阅读:Reasoning about Object Affordances in a Knowledge Base Representation

热门文章

  1. Centos7.2部署各类服务
  2. Java学习之数据类型
  3. squid rebuild 阶段swap.state 持续增大耗尽磁盘
  4. 算法 - 折半查找(C#)
  5. api接口参数加密_解决API接口开发安全性的四种方案
  6. ios开发 ajax hook,IOS中的网络拦截总结
  7. 世园会开幕式上的机器人_【在国际智能制造大会暨智能机器人大会开幕式上的致辞】世界智能机器人大会...
  8. java win8 mac地址_Windows8系统下MAC地址修改方法图文教程
  9. 虽然得了第三名,但依然很快乐...
  10. 皮一皮:这剧透的太厉害了...