目的:
python 读取xml格式的文件,截取数据部分使用matplotlib生成3D图像
调用库:
xml.dom.minidom matplotlib.pyplot Axes3D numpy
import xml.dom.minidom
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.style.use('ggplot')
import numpy as np
dom=xml.dom.minidom.parse(r'E:\2EX05F1M1C.xml')
rootNode = dom.documentElement
'''获取图像的长和宽'''
print('start read array')
LayerAreas = rootNode.getElementsByTagName("LayerAreas")
area=[]
for LayerArea in LayerAreas:
SelectAreas = LayerArea.getElementsByTagName("SelectedArea")
for SelectArea in SelectAreas:
Width=SelectArea.getElementsByTagName("Width")[0]
'''print(Width.nodeName,":",Width.childNodes[0].data)'''
area.append(Width.childNodes[0].data)
Height = SelectArea.getElementsByTagName("Height")[0]
'''print(Height.nodeName, ":", Height.childNodes[0].data)'''
area.append(Height.childNodes[0].data)
areaWidth=area[0]
areaHeight=area[1]
print('read array completely')
print("areaWidth=",areaWidth,"\nareaheight=",areaHeight)
'''获取图像的3D数据'''
print('start read 3D data')
data3ds=rootNode.getElementsByTagName("data3D")
Data_3D=[]
dataForPixel=[]
for data3d in data3ds:
dataForLineAll=data3d.getElementsByTagName("ArrayOfFloat")
for dataForLine in dataForLineAll:
dataForPixel = []
for i in range(int(areaWidth)):
flo = dataForLine.getElementsByTagName("float")[i]
dataForPixel.append(float(flo.childNodes[0].data))
Data_3D.append(dataForPixel)
del dataForPixel
print(type(Data_3D))
print('read 3Ddata completely')
z=np.array(Data_3D)
print(z.shape)
x = np.arange(0, int(z.shape[1]), 1)
y = np.arange(0, int(z.shape[0]), 1)
x, y = np.meshgrid(x, y)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=plt.cm.jet)
plt.show()