# coding: utf-8
from PIL import Image
import os.path
import glob
import xml.etree.ElementTree as ET
import time
import random
import string
start = time.time()
# 指明被遍历的文件夹
rootdir = r'D:\\picture\\指针仪表拍图\\half_pointer\\JPEGImages\\'
for parent, dirnames, filenames in os.walk(rootdir): # 遍历每一张图片
for filename in filenames:
#print('parent is :' + parent)
#print('filename is :' + filename)
currentPath = os.path.join(parent, filename)
print('the fulll name of the file is :' + currentPath)
img = Image.open(currentPath)
# print (img.format, img.size, img.mode)
# img.show()
path = r'D:\\picture\\指针仪表拍图\\half_pointer\\Annotations\\'#Annotations
for xml_file in glob.glob(path + '/*.xml'):
# 返回解析树
tree = ET.parse(xml_file)
# 获取根节点
root = tree.getroot()
# print(root)
# 根据标签名查找root下的所有标签,并获取其值
# print(imgname)
# 对所有目标进行解析
for member in root.findall('object'):
xmlname = root.find('filename').text
savefilename = member.find('name').text
if savefilename == 'num':
xmin = int(member[4][0].text) # xmin
ymin = int(float(member[4][1].text)) # ymin
xmax = int(member[4][2].text) # xmax
ymax = int(member[4][3].text) # ymax
if xmlname == filename:
box1 = (xmin, ymin, xmax, ymax)
# print(box1)
image1 = img.crop(box1) # 图像裁剪
#salt = ''.join(random.sample(string.ascii_letters + string.digits, 8)) # 随机输出8位由英文字符和数字组成的字符串
salt = ''.join(random.sample(string.digits, 8)) # 随机输出8位由数字组成的字符串
image1.save(r"D:\\picture\\指针仪表拍图\\half_pointer\\num\\" + salt + '.jpg') # 存储裁剪得到的图像
end = time.time()
print("Execution Time:", end - start)
# 参考:https://www.cnblogs.com/White-xzx/p/9491192.html
# 思路:先在图片文件夹for循环,然后进入xml文件夹,解析xml文件,查找与图片相同名字的xml文件,解析该文件,提取截图坐标,截取图片
使用labelImg工具标注数据集生成XML文件后,通过XML文件的标注框截取原图像对应的目标子图像
最新推荐文章于 2022-10-14 16:43:25 发布