对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正则分组的应用
Nov 10 Python
python翻译软件实现代码(使用google api完成)
Nov 26 Python
Django rest framework实现分页的示例
May 24 Python
Python标准库使用OrderedDict类的实例讲解
Feb 14 Python
详解用python实现基本的学生管理系统(文件存储版)(python3)
Apr 25 Python
django数据关系一对多、多对多模型、自关联的建立
Jul 24 Python
Python 过滤错误log并导出的实例
Dec 26 Python
Python unittest工作原理和使用过程解析
Feb 24 Python
使用Python第三方库pygame写个贪吃蛇小游戏
Mar 06 Python
python求numpy中array按列非零元素的平均值案例
Jun 08 Python
深入了解NumPy 高级索引
Jul 24 Python
matplotlib如何设置坐标轴刻度的个数及标签的方法总结
Jun 11 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
PHP 如何向 MySQL 发送数据
2006/10/09 PHP
php float不四舍五入截取浮点型字符串方法总结
2013/10/28 PHP
PHP中如何实现常用邮箱的基本判断
2014/01/07 PHP
php去除字符串换行符示例分享
2014/02/13 PHP
thinkphp的c方法使用示例
2014/02/24 PHP
PHP实现检测客户端是否使用代理服务器及其匿名级别
2015/01/07 PHP
laravel 中某一字段自增、自减的例子
2019/10/11 PHP
niceTitle 基于jquery的超链接提示插件
2010/05/31 Javascript
JS声明变量背后的编译原理剖析
2012/12/28 Javascript
js用typeof方法判断undefined类型
2014/07/15 Javascript
JavaScript字符串对象substring方法入门实例(用于截取字符串)
2014/10/17 Javascript
jQuery过滤选择器用法分析
2015/02/10 Javascript
JS中解决谷歌浏览器记住密码输入框颜色改变功能
2017/02/13 Javascript
Python中使用PDB库调试程序
2015/04/05 Python
Python使用scrapy抓取网站sitemap信息的方法
2015/04/08 Python
Python中SOAP项目的介绍及其在web开发中的应用
2015/04/14 Python
Python selenium文件上传方法汇总
2020/11/19 Python
Python实现Smtplib发送带有各种附件的邮件实例
2017/06/05 Python
python处理数据,存进hive表的方法
2018/07/04 Python
keras:model.compile损失函数的用法
2020/07/01 Python
python 如何引入协程和原理分析
2020/11/30 Python
CSS3+font字体文件实现圆形半透明菜单具体步骤(图解)
2013/06/03 HTML / CSS
香港迪士尼乐园酒店预订:Hong Kong Disneyland Hotels
2017/05/02 全球购物
爱奇艺VIP会员:大剧抢先看
2018/07/11 全球购物
NYX Professional Makeup官方网站:专业彩妆和美容产品
2019/10/29 全球购物
SEPHORA丝芙兰德国官方购物网站:化妆品、护肤品和香水
2020/01/21 全球购物
巧克力蛋糕店创业计划书
2014/01/14 职场文书
大课间活动实施方案
2014/03/06 职场文书
党校个人自我鉴定范文
2014/03/28 职场文书
小学生倡议书范文
2014/05/13 职场文书
广播节目策划方案
2014/05/23 职场文书
2014年医药代表工作总结
2014/11/22 职场文书
结婚保证书(卖身契)
2015/02/26 职场文书
质检员岗位职责范本
2015/04/07 职场文书
2019广播稿怎么写
2019/04/17 职场文书
nginx rewrite功能使用场景分析
2022/05/30 Servers