from xml.etree import ElementTree as ET
import os.path
import cv2 as cv
def chang_w_h(xml_path,img_path):
for filename in os.listdir(xml_path):
num = filename[:5] #获取编号
img = cv.imread(img_path + num + '.jpg')
h,w,d = img.shape #获取图片的w和h,注意w和h的顺序
et = ET.parse(xml_path + filename) # 解析文件
root = et.getroot()
# 一层一层获取
size = root.find('size')
width = size.find('width')
height = size.find('height')
print(width.text,height.text)
# 修改&保存
width.text = str(w)
height.text = str(h)
et.write(xml_path + filename) # 此处必须加名字,否则会报权限错
if __name__ == '__main__':
chang_w_h(xml_path='F:\BS_IMAGE\VOC2007_6\VOC2007\Annotations/',img_path='F:\BS_IMAGE\VOC2007_6\VOC2007\JPEGImages/')
给图片打标签遇到了w和h为0的情况,查资料是更改格式或者图片没有统一大小,因为已经标记完了不想重新标记,就写了脚本根据图片自动更改。不得不说,切片真的好用。