修改xml成正方形,保存

Posted crazybird123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了修改xml成正方形,保存相关的知识,希望对你有一定的参考价值。

import os
import xml.etree.ElementTree as ET
import cv2


origin_ann_dir = D:/Data/MyAnnoData/vmwareData/Annotations/
new_ann_dir = D:/Data/MyAnnoData/vmwareData/save/Annotations/
new_img_dir = D:/Data/MyAnnoData/vmwareData/save/JPEGImages/
image_dir = D:/Data/MyAnnoData/vmwareData/JPEGImages/

#for dirpaths, dirnames, filenames in os.walk(origin_ann_dir):
#    for filename in filenames:  #xml文件名
file = open("D:/Data/MyAnnoData/vmwareData/0.txt")
for filename in file:
    filename = filename.strip("
")
#    if os.path.isfile(r‘%s%s‘ % (origin_ann_dir, filename)):
#        origin_ann_path = os.path.join(r‘%s%s‘ % (origin_ann_dir, filename))
#        new_ann_path = os.path.join(r‘%s%s‘ % (new_ann_dir, filename))

    origin_ann_path = origin_ann_dir + filename
    new_ann_path = new_ann_dir + filename
    tree = ET.parse(origin_ann_path)
    root = tree.getroot()

    for image_size in root.findall(size):
        imgwidth = int(image_size.find(width).text)     #读取图像宽度
        imgheight = int(image_size.find(height).text)   #读取图像高度

        image_size.find(width).text = str(imgwidth)
        image_size.find(height).text = str(imgheight)

    image_name =filename.split(.xml)
    imgpath = image_dir + image_name[0] + .jpg
    img = cv2.imread(imgpath)
    if not img.data:
        break

    maxl = max(imgheight, imgwidth)  #图片size是maxl*maxl
    paddingleft = (maxl - imgwidth) >> 1
    paddingright = (maxl - imgwidth) >> 1
    paddingbottom = (maxl - imgheight) >> 1
    paddingtop = (maxl - imgheight) >> 1
    saveimg = cv2.copyMakeBorder(img, paddingtop, paddingbottom, paddingleft, paddingright, cv2.BORDER_CONSTANT,value=0)
    cv2.imwrite(new_img_dir  + image_name[0] + .jpg, saveimg)

    for image_size in root.findall(size):
        image_size.find(width).text = str(maxl)
        image_size.find(height).text = str(maxl)


    for object in root.findall(object):
        name = str(object.find(name).text) #标注对象名
        v_bndbox = object.find(bndbox)   #目标框位置
        x1 = int(v_bndbox.find(xmin).text)
        y1 = int(v_bndbox.find(ymin).text)
        x2 = int(v_bndbox.find(xmax).text)
        y2 = int(v_bndbox.find(ymax).text)

        x11 = x1 + paddingleft
        y11 = y1 + paddingtop
        x22 = x11 + (x2-x1+1)
        y22 = y11 + (y2-y1+1)

        v_bndbox.find(xmin).text = str(x11)
        v_bndbox.find(ymin).text = str(y11)
        v_bndbox.find(xmax).text = str(x22)
        v_bndbox.find(ymax).text = str(y22)

    print(filename)
    tree.write(new_ann_path)

 

以上是关于修改xml成正方形,保存的主要内容,如果未能解决你的问题,请参考以下文章

python PIL如何才能把图片修改成正方形或者任意尺寸而不产生挤压

检索数据未出现在 ListView 的片段中

麻烦请问一下,android如何修改xml文件中节点的值,并保存进去,谢谢

Sublime Text自定制代码片段(Code Snippets)

在使用ViewPager时尝试从其父活动修改片段时出现空指针异常

VIM 代码片段插件 ultisnips 使用教程