用python将xml文件转换为txt文件_Python把txt文件格式转换成VOC数据集的xml文件

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值