目标检测目标的统计

时间: 2023-07-09 admin 互联网

目标检测目标的统计

目标检测目标的统计

1 对目标数量,占比的统计

2 对目标尺寸(长,宽及面积的箱型图)

统计时你只需要修改对应目标的字典即可(下载STLITI.TTF字体格式,放到当前位置,替换fname中的位置)

# encoding:utf-8
""""
#20200331 统计目标检测中的数据,需要输入dota格式的标签x1,y1....x4,y4,category
"""
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib import font_manager
import random#目标数据统计字典
totalnum={ 'ship' : 0,"airplane"  : 0,"vehicle"    : 0,"overpass"  : 0,"basketballcourt"  : 0,"tenniscourt"  : 0,"airport"    : 0,'storagetank': 0,"Expressway-Service-area": 0,"harbor": 0,"baseballfield": 0,"bridge": 0,"chimney": 0,"groundtrackfield": 0,"trainstation":0,"stadium": 0,"windmill": 0,"golffield": 0,"Expressway-toll-station": 0,"dam":0}
#每类目标的长宽数据统计
totalnum_wh_area={"ship" : {'w':[],'h':[],'area':[]},"airplane"   : {'w':[],'h':[],'area':[]},"vehicle"     : {'w':[],'h':[],'area':[]},"overpass"   : {'w':[],'h':[],'area':[]},"basketballcourt"   : {'w':[],'h':[],'area':[]},"tenniscourt"   : {'w':[],'h':[],'area':[]},"airport"     : {'w':[],'h':[],'area':[]},"storagetank": {'w': [], 'h': [], 'area': []},"Expressway-Service-area": {'w': [], 'h': [], 'area': []},"harbor": {'w': [], 'h': [], 'area': []},"baseballfield": {'w': [], 'h': [], 'area': []},"bridge": {'w': [], 'h': [], 'area': []},"chimney": {'w': [], 'h': [], 'area': []},"groundtrackfield": {'w': [], 'h': [], 'area': []},"trainstation": {'w': [], 'h': [], 'area': []},"stadium": {'w': [], 'h': [], 'area': []},"windmill": {'w': [], 'h': [], 'area': []},"golffield": {'w': [], 'h': [], 'area': []},"Expressway-toll-station": {'w': [], 'h': [], 'area': []},"dam": {'w': [], 'h': [], 'area': []}}colors=['black','lightcoral','maroon','red','salmon','darksalmon','peru','orange',\'darkgoldenrod','olivedrab','chartreuse','palegreen','lime','seagreen',\'cyan','deepskyblue','skyblue','dodgerblue','lightslategray','crimson','b']
#标题名字
category_title="dota"
#画不同目标的总数量条形图及占比扇形图
def draw_totalnum(inputfiles,out_put):files=os.listdir(inputfiles)#统计不同目标的数据for fliename in files:txt_path=os.path.join(inputfiles,fliename)txt_size=os.path.getsize(txt_path)txt_f=open(txt_path,"r")if txt_size != 0:for line in txt_f.readlines():split_line=line.replace("\n","").split(" ")category=split_line[8]category_label = category#category_label=dict_category[category]if category_label in totalnum.keys():totalnum[category_label] += 1else:print("####category is not inputfiles:",inputfiles,category_label)else:print ("###txt_path_size is 0:",txt_path)#根据统计的数目画柱状图key_list = []val_list = []for key in totalnum.keys():key_list.append(key)val_list.append(totalnum[key])#添加图像属性plt.figure(1)plt.figure(figsize=(10, 10))my_font = font_manager.FontProperties(fname="/data/xx/PycharmProjects/object_detection_tool/image_label_data_convert/STLITI.TTF")plt.xlabel("类别",fontproperties=my_font,size=10)plt.ylabel("数量(个)",fontproperties=my_font,size=10)plt.title(category_title+"数据统计",fontproperties=my_font,size=15)#绘制Y轴信息y=val_listfirst_bar = plt.bar(range(len(y)), y, width=0.4, color='blue')#绘制x轴的数据index=range(0,len(y))name_list=key_listplt.xticks(index, name_list,fontproperties=my_font,rotation=-60)  # 绘制x轴的标签#添加数量for data in first_bar:y=data.get_height()x=data.get_x()plt.text(x,y,str(y),va="bottom")plt.savefig(os.path.join(out_put,"ship_columnar.jpg"))plt.close(1)#画扇形图plt.figure(2)plt.figure(figsize=(12, 12))labels= key_listsizes=val_listcolors_=random.sample(colors,len(key_list))explode=[]for index in range(len(key_list)):if val_list[index] < 300:explode.append(random.uniform(0.025,0.1))else:explode.append(0)explode=tuple(explode)patches, l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors,pctdistance=0.8,  # 设置百分比标签和圆心的距离labeldistance=1.02,  # 图例距圆心半径倍距离autopct='%3.2f%%',  # 数值保留固定小数位shadow=False,  # 无阴影设置startangle=90,  # 逆时针起始角度设置# center=(10, 10),  # 设置饼图的圆心(相当于X轴和Y轴的范围)# radius=10,  # 设置饼图的半径(相当于X轴和Y轴的范围)wedgeprops={'linewidth': 1, 'edgecolor': 'green'},  # 设置饼图内外边界的属性值textprops={'fontsize': 20, 'color': 'black', 'fontproperties': my_font})for t in l_text:t.set_fontproperties(my_font)plt.axis("equal")#第一个数值用于控制左右移动,值越大越向右边移动,第二个数值用于控制的上下移动,值越大越向上移动plt.legend(loc='lower right', bbox_to_anchor=(1.1,-0.1))plt.title(category_title+'类别数据占比', fontproperties=my_font,size=15)plt.savefig(os.path.join(out_put,"ship_sector.jpg"))print("####totalnum:",totalnum)#统计目标的长宽和面积,并画出箱型图
def draw_box_length_width_area(inputfiles, out_put):files = os.listdir(inputfiles)# 统计不同目标的数据for fliename in files:txt_path = os.path.join(inputfiles, fliename)txt_size = os.path.getsize(txt_path)txt_f = open(txt_path, "r")if txt_size != 0:for line in txt_f.readlines():split_line = line.replace("\n", "").split(" ")category = split_line[8]xmin = min(float(split_line[0]),float(split_line[2]),float(split_line[4]),float(split_line[6]))ymin = min(float(split_line[1]), float(split_line[3]), float(split_line[5]), float(split_line[7]))xmax = max(float(split_line[0]),float(split_line[2]),float(split_line[4]),float(split_line[6]))ymax = max(float(split_line[1]), float(split_line[3]), float(split_line[5]), float(split_line[7]))assert (xmax-xmin) >= 0, "w的值小于0"w=round((xmax-xmin),3)assert (ymax - ymin) >= 0, "h的值小于0"h=round((ymax - ymin),3)#category_label = dict_category[category]category_label =categoryarea=round(w*h,3)if category_label in totalnum.keys():totalnum_wh_area[category_label]['w'].append(w)totalnum_wh_area[category_label]['h'].append(h)totalnum_wh_area[category_label]['area'].append(area)else:print("####category is not inputfiles:", inputfiles, category_label)else:print ("###txt_path_size is 0:", txt_path)#print ("#####totalnum_wh_area:",totalnum_wh_area)#画w,h的箱型图#拿取出箱型图的数据key_list = []val_w_list = []val_h_list = []val_area_list = []for key in totalnum_wh_area.keys():key_list.append(key)for key_ in totalnum_wh_area[key].keys():if key_ =='w':val_w_list.append(totalnum_wh_area[key][key_])elif key_ == 'h':val_h_list.append(totalnum_wh_area[key][key_])elif key_ == 'area':val_area_list.append(totalnum_wh_area[key][key_])else:print ("key_ is not exit")#area画图plt.figure(1)fig, ax = plt.subplots(figsize=(8, 6))my_font = font_manager.FontProperties(fname="/data/xxx/PycharmProjects/object_detection_tool/image_label_data_convert/STLITI.TTF")plt.xlabel("类别", fontproperties=my_font, size=10)plt.ylabel("area像素点(个)", fontproperties=my_font, size=10)plt.title(category_title+"_area数据统计", fontproperties=my_font, size=15)data=val_area_listlabels=key_listax.boxplot(data)ax.set_xticklabels(labels,fontproperties=my_font, size=10,rotation=-60)fig.savefig(os.path.join(out_put, "ship_aera_box.jpg"))plt.close(1)#绘制w,hplt.figure(2)fig, ax = plt.subplots(figsize=(8,6))my_font = font_manager.FontProperties(fname="/data/xxx/PycharmProjects/object_detection_tool/image_label_data_convert/STLITI.TTF")plt.xlabel("类别", fontproperties=my_font, size=10)plt.ylabel("w像素点(个)", fontproperties=my_font, size=10)plt.title(category_title+"_w数据统计", fontproperties=my_font, size=15)data = val_w_listlabels = key_listax.boxplot(data)ax.set_xticklabels(labels, fontproperties=my_font, size=10,rotation=-60)fig.savefig(os.path.join(out_put, "ship_w_box.jpg"))plt.close(2)plt.figure(3)fig, ax = plt.subplots(figsize=(8, 6))my_font = font_manager.FontProperties(fname="/data/xxx/PycharmProjects/object_detection_tool/image_label_data_convert/STLITI.TTF")plt.xlabel("类别", fontproperties=my_font, size=10)plt.ylabel("h像素点", fontproperties=my_font, size=10)plt.title(category_title+"_h数据统计", fontproperties=my_font, size=15)data = val_h_listlabels = key_listax.boxplot(data)ax.set_xticklabels(labels, fontproperties=my_font, size=10,rotation=-60)fig.savefig(os.path.join(out_put, "ship_h_box.jpg"))plt.close(3)if __name__=="__main__":input_dota_txt="" #具体HBB数据格式的文件夹地址out_put=""        #生成图片的保存地址draw_totalnum(input_dota_txt,out_put)draw_box_length_width_area(input_dota_txt,out_put)print ("finished!!!!")