学习过程中发现需要将xml文件中标注的区域坐标转换为txt格式,结合多方资料后进行记录,以免忘却。
clc;
clear;
xmlpath='路径';%xml文件所在的路径
mkdir 路径;%创建新的输出文件夹
Output_path1='路径';
xmldir=dir(strcat(xmlpath,'*.xml'));%将xml文件读取到结构体中
xml_num=length(xmldir);
% 第一行的数据进行转换
xmlname=xmldir(1).name;
xmldoc0=xmlread(strcat(xmlpath,xmlname));%读取xml文件
fdsarray0= xmldoc0.getElementsByTagName('bndbox');
xmin=fdsarray0.item(0).getElementsByTagName('xmin');
a1=str2double(xmin.item(0).getFirstChild.getData);
ymin=fdsarray0.item(0).getElementsByTagName('ymin');
b1=str2double(ymin.item(0).getFirstChild.getData);
xmax=fdsarray0.item(0).getElementsByTagName('xmax');
c1=str2double(xmax.item(0).getFirstChild.getData);
ymax=fdsarray0.item(0).getElementsByTagName('ymax');
d1=str2double(ymax.item(0).getFirstChild.getData);%得到xml文件中标注的坐标
x1=a1;y1=d1;x2=a1;y2=b1;x3=c1;y3=b1;x4=c1;y4=d1;
label_location=[x1 y1 x2 y2 x3 y3 x4 y4];
fid1=fopen('newlabel.txt','Wt');%以写的方式打开文档,(若不存在文件,则进行创建操作)
fprintf(fid1,'%.4f\t',label_location);%小数点后保留两位存储数据
fprintf(fid1,'\n');%换行
fclose(fid1);
for j=2:1:xml_num
xmlname=xmldir(j).name;
xmldoc=xmlread(strcat(xmlpath,xmlname));%读取xml文件
fdsarray = xmldoc.getElementsByTagName('bndbox');
xmin=fdsarray.item(0).getElementsByTagName('xmin');
a1=str2double(xmin.item(0).getFirstChild.getData);
ymin=fdsarray.item(0).getElementsByTagName('ymin');
b1=str2double(ymin.item(0).getFirstChild.getData);
xmax=fdsarray.item(0).getElementsByTagName('xmax');
c1=str2double(xmax.item(0).getFirstChild.getData);
ymax=fdsarray.item(0).getElementsByTagName('ymax');
d1=str2double(ymax.item(0).getFirstChild.getData);%得到xml文件中标注的坐标
x1=a1;y1=d1;x2=a1;y2=b1;x3=c1;y3=b1;x4=c1;y4=d1;
label_location=[x1 y1 x2 y2 x3 y3 x4 y4];
fid1=fopen('newlabel.txt','at');%以续写的方式打开文档
fprintf(fid1,'%.4f\t',label_location);
fprintf(fid1,'\n');
fclose(fid1);
end