Python generates VOC format label examples

The commonly used target detection models are basically the tags in the PASCAL VOC format that are read. The following code is used to generate the code in the VOC format, which can be modified as needed:

from lxml import etree, objectify

def gen_txt(filename, h, w, c):
 E = objectify.ElementMaker(annotate=False)
 anno_tree = E.annotation(
 E.folder('VOC_OPEN_IMAGE'),
 E.filename(filename),
 E.source(
  E.database('The VOC2007 Database'),
  E.annotation('PASCAL VOC2007'),
  E.image('flickr'),
  E.flickrid("341012865")),
 E.size(
  E.width(w),
  E.height(h),
  E.depth(c)),
 E.segmented(0),
 E.object(
  E.name('1'),
  E.pose('left'),
  E.truncated('1'),
  E.difficult('0'),
  E.bndbox(
  E.xmin('0'),
  E.ymin('0'),
  E.xmax('0'),
  E.ymax('0'))),)
 etree.ElementTree(anno_tree).write('ann/'+filename[:-4]+".xml", pretty_print=True)

Supplementary knowledge: python performs statistics on PASCAL VOC annotation data

Used to count the categories in the training data and the number of all targets:

# coding:utf-8import xml.etree.cElementTree as ET
import os
from collections import Counter
import shutil
 
# Counter({'towCounter({'tower': 3074, 'windpower': 2014, 'thermalpower': 689, 'hydropower': 261, 'transformer':225})
# total_num:6263
 
def count(pathdir,despath):
 category =[]
 path = pathdir +'/XML/'for index,xml inenumerate(os.listdir(path)):
 # print(str(index)+' xml: '+ xml)
 root = ET.parse(os.path.join(path, xml))
 objects = root.findall('object')
 
 # ================== select images which has a special object=============for obj in objects:
 obj_label = obj.find('name').text
 if obj_label =='transformer':print(xml)
 imgfile = pathdir +'JPEG/'+ xml.replace('xml','jpg')
 img_despath = despath + xml.replace('xml','jpg')
 # if not os.path.exists(img_despath):
 shutil.copyfile(imgfile, img_despath)
 
 # ================== select images which has a special object=============
 
 category +=[ob.find('name').text for ob in objects]print(Counter(category))
 total_num =sum([value for key, value inCounter(category).items()])print('total_num:',total_num)if __name__ =='__main__':
 # pathdirs =list(set(os.listdir('./'))^set(['tools','count.py']))
 # print(pathdirs)
 # for pathdir in pathdirs:
 pathdir ='/summer/Desktop/power_traindata/'
 despath ='/transformer/'count(pathdir,despath)

The above example of tags generated by Python in VOC format is all the content shared by the editor. I hope to give you a reference.

Recommended Posts

Python generates VOC format label examples
Python reads .nii format image examples
Python access to npy format data examples
100 small Python examples
Python generates connotative pictures