通过mat文件修改xml文件
import xml.etree.ElementTree as ET
import os, cv2
import xml.dom.minidom
import pandas as pd
import scipy
from scipy import io
import numpy as np
Mat_File = "D:\毕设文件\训练数据\Position"
Xml_File = "D:\毕设文件\训练数据\Xml"
Mat_List = []
Xml_List = []
for root, dirs, files in os.walk(Mat_File,topdown=True):
Mat_List = files
for root, dirs, files in os.walk(Xml_File,topdown=True):
Xml_List = files
for i in range(3003):
#print(Mat_List[i])
#print(Xml_List[i])
features_struct = scipy.io.loadmat(os.path.join(Mat_File,Mat_List[i]))
features = features_struct['a']#这里的a是mat文件里的位置信息结构,不知道哪个的话可以print(features_struct)看看哪个里面是位置信息
dfdata = pd.DataFrame(features)
# dfdata.to_csv(datapath1, index=False)
Xmin = np.array(dfdata).tolist()[0][0]#提取mat文件中的四个位置
Ymin = np.array(dfdata).tolist()[0][1]
Xmax = np.array(dfdata).tolist()[0][2]
Ymax = np.array(dfdata).tolist()[0][3]
xml_file = os.path.join(Xml_File,Xml_List[i])
dom = xml.dom.minidom.parse(xml_file)
root = dom.documentElement
#tree = ET.parse(xml_file)
#booklist = tree.documentElement
#root = tree.getroot()
#imgfile = '1.png'
#im = cv2.imread(imgfile)
xmin = root.getElementsByTagName("xmin")#获取四个tag
ymin = root.getElementsByTagName("ymin")
xmax = root.getElementsByTagName("xmax")
ymax = root.getElementsByTagName("ymax")
xmin[0].firstChild.data = int(Xmin)#将提取到的四个位置写入Xml中
ymin[0].firstChild.data = int(Ymin)
xmax[0].firstChild.data = int(Xmax)
ymax[0].firstChild.data = int(Ymax)
with open( xml_file,'w') as fh:
dom.writexml(fh)
以下是我的xml文件
<?xml version="1.0"?>
-<annotation>
<folder>VOC2007</folder>
<filename>1-A-029.png</filename>
-<source>
<database>My Database</database>
<annotation>VOC2007</annotation>
<image>flickr</image>
<flickrid>NULL</flickrid>
</source>
-<owner>
<flickrid>NULL</flickrid>
<name>xiaoxianyu</name>
</owner>
-<size>
<width>512</width>
<height>512</height>
<depth>1</depth>
</size>
<segmented>0</segmented>
-<object>
<name>PCN</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
-<bndbox>
<xmin>337</xmin>
<ymin>256</ymin>
<xmax>359</xmax>
<ymax>290</ymax>
</bndbox>
</object>
</annotation>