对python修改xml文件的节点值方法详解


Posted in Python onDecember 24, 2018

这是我的xml文件结构

<?xml version='1.0' encoding='utf-8'?>
<annotation>
 <folder>JPEGImages</folder>
 <filename>train_2018-05-08_1000.jpg</filename>
 <path>D:\all_data\2018-05-08\JPEGImages\train_2018-05-08_1000.jpg</path>
 <source>
 <database>Unknown</database>
 </source>
 <size>
 <width>4032</width>
 <height>3024</height>
 <depth>3</depth>
 </size>
 <segmented>0</segmented>
 <object>
 <name>yl-ylhzdhmbbz-gz-hm-280g</name>
 <pose>Unspecified</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
 <bndbox>
  <xmin>1863</xmin>
  <ymin>355</ymin>
  <xmax>2512</xmax>
  <ymax>902</ymax>
 </bndbox>
 </object>
 <object>
 <name>hy-hybfbgz-hz-xcw-200ml</name>
 <pose>Unspecified</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
 <bndbox>
  <xmin>1076</xmin>
  <ymin>1602</ymin>
  <xmax>1648</xmax>
  <ymax>2105</ymax>
 </bndbox>
 </object>
 <object>
 <name>ys-zzyspyz-gz-yw-245ml</name>
 <pose>Unspecified</pose>
 <truncated>1</truncated>
 <difficult>0</difficult>
 <bndbox>
  <xmin>2017</xmin>
  <ymin>2475</ymin>
  <xmax>2681</xmax>
  <ymax>3024</ymax>
 </bndbox>
 </object>
 <object>
 <name>mn-zgl-hz-cmw-250ml</name>
 <pose>Unspecified</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
 <bndbox>
  <xmin>1849</xmin>
  <ymin>1207</ymin>
  <xmax>2242</xmax>
  <ymax>2047</ymax>
 </bndbox>
 </object>
 <object>
 <name>qc-qckf-pz-shnt-268ml</name>
 <pose>Unspecified</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
 <bndbox>
  <xmin>480</xmin>
  <ymin>1213</ymin>
  <xmax>1308</xmax>
  <ymax>1544</ymax>
 </bndbox>
 </object>
 <object>
 <name>wt-wtcyl-gz-nm-310ml</name>
 <pose>Unspecified</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
 <bndbox>
  <xmin>867</xmin>
  <ymin>488</ymin>
  <xmax>1527</xmax>
  <ymax>938</ymax>
 </bndbox>
 </object>

</annotation>

现在想实现的是修改图像的size和目标

__author__ = 'Sam'
 
import cv2
import xml.etree.ElementTree as ET
import os
import sys
import lxml
import shutil
 
#user input files path
path="E:/test_folder"
image_path = path + "/Annotations/" #image path with .jpg ending
label_path = path + "/JPEGImages/" #label path with .xml ending
min_size=800
 
def search_jpg_xml(image_dir,label_dir):
  #find out all of sepecified file
  image_ext='.jpg'
  img=[fn for fn in os.listdir(image_dir) if fn.endswith(image_ext)]
  label_ext='.xml'
  label=[fn for fn in os.listdir(label_dir) if fn.endswith(label_ext)]
  return img, label
 
def copyfile():
  if "Annotations_temp" in os.listdir(path):
    shutil.rmtree(path+"/Annotations_temp")
  if "JPEGImages_temp" in os.listdir(path):
    shutil.rmtree(path+"/JPEGImages_temp")
  save_annotation_path=path+"/Annotations_temp/"
  save_jpg_path=path+"/JPEGImages_temp/"
  shutil.copytree(path + "/Annotations",save_annotation_path)
  shutil.copytree(path + "/JPEGImages", save_jpg_path)
  return save_jpg_path ,save_annotation_path
 
def write_xml_jpg(jpg_path,annotation_path):
  img,label=search_jpg_xml(jpg_path,annotation_path)
  sorted(img)
  sorted(label)
  print(img)
  print(label)
  if "Annotations_1" not in os.listdir(path):
    os.mkdir(path+"/Annotations_1")
  if "JPEGImages_1" not in os.listdir(path):
    os.mkdir(path+"/JPEGImages_1")
  new_image_path=path+"/JPEGImages_1/"
  new_annotation_path=path+"/Annotations_1/"
  for index,file in enumerate(label):
    cur_img = cv2.imread(jpg_path+img[index])
    width=cur_img.shape[1]
    height=cur_img.shape[0]
    if width<height:
      new_width=min_size
      new_height=int(min_size*height/width)
      w_ratio=new_width/width
      h_ratio=new_height/height
    elif width>height:
      new_width=int(min_size*width/height)
      new_height=min_size
      w_ratio=new_width/width
      h_ratio=new_height/height
    elif width==height:
      new_width=min_size
      new_height=min_size
      w_ratio=new_width/width
      h_ratio=new_height/height
    cur_img = cv2.resize(cur_img, (new_width, new_height))
    cv2.imwrite(new_image_path+img[index],cur_img)
    cur_xml = ET.parse(annotation_path+file)
    root = cur_xml.getroot()
    for node in root:
      if node.tag=='size':
        node[0].text=str(new_width)
        node[1].text=str(new_height)
      elif node.tag=='object':
         xmin=int(node[4][0].text)#bbox position
         ymin=int(node[4][1].text)
         xmax=int(node[4][2].text)
         ymax=int(node[4][3].text)
         node[4][0].text=str(int(xmin*w_ratio))
         node[4][1].text=str(int(ymin*h_ratio))
         node[4][2].text=str(int(xmax*w_ratio))
         node[4][3].text=str(int(ymax*h_ratio))
    cur_xml.write(new_annotation_path+file)
  shutil.rmtree(path+"/JPEGImages_temp")
  shutil.rmtree(path+"/Annotations_temp")
 
 
if __name__ == "__main__":
  jpg_path,annotation_path=copyfile()
  write_xml_jpg(jpg_path,annotation_path)

最关键语句是:

node[4][3].text=str(int(ymax*h_ratio)),注意xml节点的操作是字符型!!!

以上这篇对python修改xml文件的节点值方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
浅谈Python的垃圾回收机制
Dec 17 Python
浅谈编码,解码,乱码的问题
Dec 30 Python
MAC中PyCharm设置python3解释器
Dec 15 Python
简单实现python数独游戏
Mar 30 Python
Python通过调用有道翻译api实现翻译功能示例
Jul 19 Python
10分钟教你用Python实现微信自动回复功能
Nov 28 Python
Python Pexpect库的简单使用方法
Jan 29 Python
用python爬取历史天气数据的方法示例
Dec 30 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
Mar 24 Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
Jul 14 Python
python flask框架快速入门
May 14 Python
python 闭包函数详细介绍
Apr 19 Python
用Python读取几十万行文本数据
Dec 24 #Python
python实现flappy bird小游戏
Dec 24 #Python
python实现Flappy Bird源码
Dec 24 #Python
python3安装speech语音模块的方法
Dec 24 #Python
对Python 语音识别框架详解
Dec 24 #Python
python抓取网页内容并进行语音播报的方法
Dec 24 #Python
解决pyttsx3无法封装的问题
Dec 24 #Python
You might like
基于Snoopy的PHP近似完美获取网站编码的代码
2011/10/23 PHP
PHP批量检测并去除文件BOM头代码实例
2014/05/08 PHP
微信开发之网页授权获取用户信息(二)
2016/01/08 PHP
删除PHP数组中头部、尾部、任意元素的实现代码
2017/04/10 PHP
PHP实现微信申请退款功能
2018/10/01 PHP
通过jquery toggleClass()属性制作文章段落更改背景颜色
2018/05/21 jQuery
Vue2.0 实现移动端图片上传功能
2018/05/30 Javascript
vue 组件中添加样式不生效的解决方法
2018/07/06 Javascript
jQuery中ajax请求后台返回json数据并渲染HTML的方法
2018/08/08 jQuery
mockjs+vue页面直接展示数据的方法
2018/12/19 Javascript
Vue实战教程之仿肯德基宅急送App
2019/07/19 Javascript
JS实现数据动态渲染的竖向步骤条
2020/06/24 Javascript
JavaScript实现世界各地时间显示
2020/09/07 Javascript
js实现详情页放大镜效果
2020/10/28 Javascript
[54:30]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
python生成IP段的方法
2015/07/07 Python
TF-IDF与余弦相似性的应用(一) 自动提取关键词
2017/12/21 Python
Python实现识别手写数字 简易图片存储管理系统
2018/01/29 Python
Python cookbook(数据结构与算法)同时对数据做转换和换算处理操作示例
2018/03/23 Python
Python读取指定日期邮件的实例
2019/02/01 Python
pybind11在Windows下的使用教程
2019/07/04 Python
Python 中使用 PyMySQL模块操作数据库的方法
2019/11/10 Python
使用keras和tensorflow保存为可部署的pb格式
2020/05/25 Python
浅析python实现动态规划背包问题
2020/12/31 Python
python 基于UDP协议套接字通信的实现
2021/01/22 Python
几个CSS3的flex弹性盒模型布局的简单例子演示
2016/05/12 HTML / CSS
洲际酒店集团大中华区:IHG中国
2016/08/17 全球购物
美国美妆网站:B-Glowing
2016/10/12 全球购物
碧欧泉Biotherm加拿大官方网站:法国高端护肤品牌
2019/10/18 全球购物
保卫科工作岗位职责
2014/03/01 职场文书
全国优秀辅导员事迹材料
2014/05/14 职场文书
巾帼文明岗汇报材料
2014/12/24 职场文书
实习协议书
2015/01/27 职场文书
spring cloud 配置中心native配置方式
2021/09/25 Java/Android
Redis sentinel哨兵集群的实现步骤
2022/07/15 Redis
Java代码规范与质量检测插件SonarLint的使用
2022/08/05 Java/Android