Pandas DataFrame转换为XML时添加图像尺寸字段的报错与输出异常咨询
核心错误定位
- 函数传参逻辑错误:
func定义时预期接收单行Series作为row入参,实际调用时传入整个DataFrame对象,遍历到整数索引0时触发KeyError: 0。 - XML结构拼接错误:未按层级构建节点,直接将列表类型的shape内容追加到字符串队列,导致文件内容异常;缺失最外层
<annotations>根节点,图像尺寸字段位置错误。 - 写文件逻辑疏漏:未对XML做格式化处理,直接写结构化对象,导致外部打开时无正常结构展示。
修正实现代码
import xml.etree.ElementTree as ET # 保持原有图像尺寸取值逻辑 width = image_x.shape[0] height = image_x.shape[1] depth = image_x.shape[2] # 创建XML根节点 root = ET.Element("annotations") # 写入图像尺寸节点 size_node = ET.SubElement(root, "size") ET.SubElement(size_node, "width").text = str(width) ET.SubElement(size_node, "height").text = str(height) ET.SubElement(size_node, "depth").text = str(depth) # 遍历DataFrame逐行生成检测框节点 for _, row in df.iterrows(): item_node = ET.SubElement(root, "item") ET.SubElement(item_node, "xmin").text = str(row["xmin"]) ET.SubElement(item_node, "ymin").text = str(row["ymin"]) ET.SubElement(item_node, "xmax").text = str(row["xmax"]) ET.SubElement(item_node, "ymax").text = str(row["ymax"]) # 自动添加XML缩进,解决外部打开无格式问题 ET.indent(root, space=" ", level=0) # 执行文件写入,和原有writexml逻辑完全兼容 tree = ET.ElementTree(root) with open("output.xml", "wb") as file_handle: tree.write(file_handle, encoding="utf-8", xml_declaration=False)
生成效果
输出的XML完全匹配预期结构:
<annotations> <size> <width>185</width> <height>186</height> <depth>3</depth> </size> <item> <xmin>30</xmin> <ymin>1</ymin> <xmax>67</xmax> <ymax>44</ymax> </item> <item> <xmin>39</xmin> <ymin>136</ymin> <xmax>73</xmax> <ymax>176</ymax> </item> </annotations>
内容的提问来源于stack exchange,提问作者Binx
相关产品推荐
相关产品推荐

