importtimeimportosfrom PIL importImageimportcv2
out0='''<?xml version="1.0" encoding="utf-8"?>
None
%(name)s
None
None
None
None
None
None
0
%(width)d
%(height)d
3
'''out1= '''
%(class)s
Unspecified
0
0
%(xmin)d
%(ymin)d
%(xmax)d
%(ymax)d
'''out2= ''''''
#names = ["CD"]
deftranslate(lists):
source={}
label={}for jpg inlists:if os.path.splitext(jpg)[1] == '.jpg':#img=cv2.imread(jpg)
#h,w,_=img.shape[:]
image=cv2.imread(jpg)
h,w,_=image.shape#h=320#w=320
fxml= jpg.replace('JPEGImages','Annotations')
fxml= fxml.replace('.jpg','.xml')
fxml= open(fxml, 'w');
imgfile= jpg.split('/')[-1]
source['name'] =imgfile
source['width'] =w
source['height'] =h
fxml.write(out0%source)
txt= jpg.replace('.jpg','.txt')
txt= txt.replace('JPEGImages','labels')
with open(txt,'r') as f:
lines= [i.replace('\n','') for i inf.readlines()]for box inlines:
box= box.split(',')
label['class'] =box[0]#_x = int(float(box[1])*w)#_y = int(float(box[2])*h)#_w = int(float(box[3])*w)#_h = int(float(box[4])*h)
_x= int(float(box[1]))
_y= int(float(box[2]))
_w= int(float(box[3]))
_h= int(float(box[4]))
label['xmin'] =max(_x,0)
label['ymin'] =max(_y,0)
label['xmax'] = min(int(_x+_w),w-1)
label['ymax'] = min(int(_y+_h),h-1)#if label['xmin']>=w or label['ymin']>=h or label['xmax']>=w or label['ymax']>=h:
#continue
#if label['xmin']<0 or label['ymin']<0 or label['xmax']<0 or label['ymax']<0:
#continue
fxml.write(out1%label)
fxml.write(out2)if __name__ == '__main__':
with open('all_label_name.txt','r') as f:
lines= [i.replace('\n','') for i inf.readlines()]
translate(lines)