python xml obj_num


原文链接: python xml obj_num

之前写了一个matlab的,越用越觉得麻烦,如果不同数据集要改类别数目,而且运行速度慢。所以重新写了一个Python的,直接读取xml文件夹路径就可以,不用预先知道类别,直接能够检测出所有类别的目标名称及其对应的数量。

分享出来给大家。

代码如下:

# -*- coding:utf-8 -*-
import os
import xml.etree.ElementTree as ET
import numpy as np
np.set_printoptions(suppress=True, threshold=np.nan)
import matplotlib
from PIL import Image
 
def parse_obj(xml_path, filename):
  tree=ET.parse(xml_path+filename)
  objects=[]
  for obj in tree.findall('object'):
    obj_struct={}
    obj_struct['name']=obj.find('name').text
    objects.append(obj_struct)
  return objects
 
 
def read_image(image_path, filename):
  im=Image.open(image_path+filename)
  W=im.size[0]
  H=im.size[1]
  area=W*H
  im_info=[W,H,area]
  return im_info
 
 
if __name__ == '__main__':
  xml_path='C:/Users/nansbas/Desktop/hebin/03/'
  filenamess=os.listdir(xml_path)
  filenames=[]
  for name in filenamess:
    name=name.replace('.xml','')
    filenames.append(name)
  recs={}
  obs_shape={}
  classnames=[]
  num_objs={}
  obj_avg={}
  for i,name in enumerate(filenames):
    recs[name]=parse_obj(xml_path, name+ '.xml' )
  for name in filenames:
    for object in recs[name]:
      if object['name'] not in num_objs.keys():
         num_objs[object['name']]=1
      else:
         num_objs[object['name']]+=1
      if object['name'] not in classnames:
         classnames.append(object['name'])
  for name in classnames:
    print('{}:{}个'.format(name,num_objs[name]))
  print('信息统计算完毕。')
 

————————————————
版权声明:本文为CSDN博主「南石北岸生」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/gusui7202/article/details/86583444

`