解析大量xml文件坐标位置,裁剪图片

喜欢程序的阿呆 2019-07-08 08:06:43
import os from PIL import Image try: import xml.etree.cElementTree as ET # 解析xml的c语言版的模块 except ImportError: import xml.etree.ElementTree as ET IMAGE_DIR = "/home/seeta/file/JPEGImages/" IMAGE_OUTPUT_DIR = "/home/seeta/file/ps/" XML_DIR = '/home/seeta/file/img_list/Annotations150/' def process(image_dir, xml_dir): image_list = os.listdir(image_dir) for image_filename in image_list: print(image_filename) image_id = image_filename.split('.')[0] xml_path = os.path.join(xml_dir, image_id + ".xml") bndboxes = GetAnnotBoxLoc(xml_path) if bndboxes: CropAndSave(image_filename, image_id, bndboxes) # CropByBoxLoc(image_filename, bndboxes) def GetAnnotBoxLoc(AnotPath): tree = ET.ElementTree(file=AnotPath) root = tree.getroot() ObjectSet = root.findall('object') ObjBndBoxSet = {} for Object in ObjectSet: ObjName = Object.find('name').text BndBox = Object.find('bndbox') x1 = int(BndBox.find('xmin').text) y1 = int(BndBox.find('ymin').text) x2 = int(BndBox.find('xmax').text) y2 = int(BndBox.find('ymax').text) BndBoxLoc = [x1, y1, x2, y2] if ObjBndBoxSet.get(ObjName): ObjBndBoxSet[ObjName].append(BndBoxLoc) # 如果字典结构中含有这个类别了,那么这个目标框要追加到其值的末尾 else: ObjBndBoxSet[ObjName] = [BndBoxLoc] return ObjBndBoxSet def CropAndSave(img_filename, img_id, bndboxes): save_dir = os.path.join(IMAGE_OUTPUT_DIR, img_id) if not os.path.exists(save_dir): os.mkdir(save_dir) img_path = os.path.join(IMAGE_DIR, img_filename) img = Image.open(img_path) for key in bndboxes.keys(): boxes = bndboxes.get(key) print(key, boxes) for i, box in enumerate(boxes): # 进行roi裁剪 roi_area = img.crop(box) # 裁剪后每个图像全路径 save_path = os.path.join(save_dir,key+"_{}.jpg".format(i)) # 保存处理图像 roi_area.save(save_path) process(IMAGE_DIR, XML_DIR)
...全文
306 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

2,760

社区成员

发帖
与我相关
我的任务
社区描述
搜索引擎的服务器通过网络搜索软件或网络登录等方式,将Internet上大量网站的页面信息收集到本地,经过加工处理建立信息数据库和索引数据库。
社区管理员
  • 搜索引擎技术社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧