您的位置:首页 > 编程语言 > MATLAB

利用matlab对xml文件进行批量处理

2016-11-22 21:02 253 查看
本文为原创作品,未经本人同意,禁止转载,禁止用于商业用途!本人对博客使用拥有最终解释权
欢迎关注我的博客:http://blog.csdn.net/hit2015spring和http://www.cnblogs.com/xujianqing/
本文主要是要利用matlab编写一个M文件,这个M文件的主要功能:对一个文件夹下面的多个XML文件进行信息的提取,然后利用所要得到的信息进行计算,最后生成对应文件名的文本文件。

先上一下XML文件:

 

<?xml version="1.0" ?>
<annotation>
<folder>che</folder>
<filename>a90180.jpg</filename>
<source>
<database>Unknown</database>
</source>
<size>
<width>641</width>
<height>512</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>1</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>307</xmin>
<ymin>225</ymin>
<xmax>342</xmax>
<ymax>290</ymax>
</bndbox>
</object>
</annotation>


针对于这个XML文件,提取里面的xmin ,ymin,xmax,ymax四个节点的值,计算出长宽。并把,上面的坐标和长和宽写到和xml文件名一致的文本文件中。

上代码:

 

clc
clear all

maindir = 'C:\Users\yezi\Desktop'; %%存放文件的上一级目录,即该文件夹的上一级,文件位于C:\Users\yezi\Desktop\3下面
subdir =  dir( maindir );   % 先确定子文件夹
for i = 1 : length( subdir )

if( isequal( subdir( i ).name, '.' ) ||isequal( subdir( i ).name, '..' ) ||  ~subdir( i ).isdir )  ; % 如果不是目录跳过
continue;
end
subdirpath = fullfile( maindir, subdir( i ).name, '*.xml' );
images = dir( subdirpath );   % 在这个子文件夹下找后缀为jpg的文件
% 遍历每张图片
for j = 1 : length( images )
imagepath = fullfile( maindir, subdir( i ).name, images( j ).name  )
% % %          imgdata = imread( imagepath );   % 这里进行你的读取操作
xmlDoc=xmlread(imagepath); %读入xml文件

% name = 'a80240';
str1 = '1 '

%% extract the FDs
FDsArray = xmlDoc.getElementsByTagName('bndbox');  %   将所有PerHuman节点放入数组FDsArray
k=0;
%  for i = 1 : FDsArray.getLength
thisItem = FDsArray.item(0);  %
%FDsAttributes = char(thisItem.getAttributes.item(0).getValue)   % 提取FDs节点的属性,如果没有属性或不需要提取,可以注释掉。这里,FDsAttributes =  opencv-matrix
childNode = thisItem.getFirstChild ;

while ~isempty(childNode)  % 遍历PerHuman的所有子节点,也就是遍历 标注程序保存下来的各个数据点 节点

if  childNode.getNodeType == childNode.ELEMENT_NODE ;    % 检查当前节点没有子节点,  childNode.ELEMENT_NODE 定义为没有子节点。
k=1+k;
childNodeNm = char(childNode.getTagName)   ;     % 当前节点的名字
childNodedata = char(childNode.getFirstChild.getData)    % 当前节点的内容
%           marks=choosenode(childNodeNm);
m(k) = str2num(childNodedata);

end  % End IF

childNode = childNode.getNextSibling;     % 切换到下一个节点
end  % End WHILE
x = m(3)-m(1);
y = m(4)-m(2);
%   strrep 进行字符串替换,区分大小写
%   strrep(str1,str2,str3)
%      它把str1中所有的str2字串用str3来替换
newname = strrep(images( j ).name,'.xml','.txt')%%重命名

fid=fopen(newname,'wt');   %在当前目录下创建一个文件写入数据
fprintf(fid,str1);
fprintf(fid,'%d',m(1));
fprintf(fid,' ');
fprintf(fid,'%d',m(2));
fprintf(fid,' ');
fprintf(fid,'%d',x);
fprintf(fid,' ');
fprintf(fid,'%d',y);
fclose(fid);
end
end


最后附上参考的文章链接

 文件批量处理

对xml进行操作

感谢作者分享!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: