COCO评估输出指定某类AP或者输出每个类别AP结果

2023-05-16

一 输出单类AP(不需要修改pycocotools)

coco_eval.py源代码

"""
COCO-Style Evaluations

"""

import json
import os

import argparse
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval

def eval(coco_gt, image_ids, pred_json_path):
    # load results in COCO evaluation tool
    coco_pred = coco_gt.loadRes(pred_json_path)

    # run COCO evaluation
    print('BBox')
    coco_eval = COCOeval(coco_gt, coco_pred, 'bbox')
    coco_eval.params.imgIds = image_ids
    coco_eval.evaluate()
    coco_eval.accumulate()
    coco_eval.summarize()

if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('--gt-json', type=str, default='instances.json', help='coco val2017 annotations json files')
    ap.add_argument('--pred-json', type=str, default='coco_results.json', help='pred coco val2017 annotations json files')
    args = ap.parse_args()
    print(args)

    pred_json_path = args.pred_json

    MAX_IMAGES = 1000
    coco_gt = COCO(args.gt_json)
    image_ids = coco_gt.getImgIds()[:MAX_IMAGES]

    eval(coco_gt, image_ids, pred_json_path)

以上代码评估后的输出

 

修改后的代码,可以指定输出某类AP值,只修改eval函数:

def eval(coco_gt, image_ids, pred_json_path):
    # load results in COCO evaluation tool
    coco_pred = coco_gt.loadRes(pred_json_path)

    # run COCO evaluation
    print('BBox')
    coco_eval = COCOeval(coco_gt, coco_pred, 'bbox')
    coco_eval.params.imgIds = image_ids
    coco_eval.params.catIds = [2] # 你可以根据需要增减类别
    coco_eval.evaluate()
    coco_eval.accumulate()
    coco_eval.summarize()

修改后输出,比如只输出第2类

 

二 输出每个类别AP结果(需要修改pycocotools下的coco.py和cocoeval.py)

首先修改coco.py的类COCO的初始化为,在84行下添加代码

    def __init__(self, annotation_file=None):
        """
        Constructor of Microsoft COCO helper class for reading and visualizing annotations.
        :param annotation_file (str): location of annotation file
        :param image_folder (str): location to the folder that hosts images.
        :return:
        """
        # load dataset
        self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()
        self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)
        if not annotation_file == None:
            print('loading annotations into memory...')
            tic = time.time()
            with open(annotation_file, 'r') as f:
                dataset = json.load(f)
            assert type(dataset)==dict, 'annotation file format {} not supported'.format(type(dataset))
            print('Done (t={:0.2f}s)'.format(time.time()- tic))
            print(
                "category names: {}".format([e["name"] for e in sorted(dataset["categories"], key=lambda x: x["id"])]))
            self.dataset = dataset
            self.createIndex()

修改cocoeval.py,在第456行下添加代码,修改summarize函数

def summarize(self):
        '''
        Compute and display summary metrics for evaluation results.
        Note this functin can *only* be applied on the default parameter setting
        '''
        def _summarize( ap=1, iouThr=None, areaRng='all', maxDets=100 ):
            p = self.params
            iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}'
            titleStr = 'Average Precision' if ap == 1 else 'Average Recall'
            typeStr = '(AP)' if ap==1 else '(AR)'
            iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \
                if iouThr is None else '{:0.2f}'.format(iouThr)

            aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
            mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
            if ap == 1:
                # dimension of precision: [TxRxKxAxM]
                s = self.eval['precision']
                # IoU
                if iouThr is not None:
                    t = np.where(iouThr == p.iouThrs)[0]
                    s = s[t]
                s = s[:,:,:,aind,mind]
            else:
                # dimension of recall: [TxKxAxM]
                s = self.eval['recall']
                if iouThr is not None:
                    t = np.where(iouThr == p.iouThrs)[0]
                    s = s[t]
                s = s[:,:,aind,mind]
            if len(s[s>-1])==0:
                mean_s = -1
            else:
                mean_s = np.mean(s[s>-1])
            #print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))
            category_dimension = 1 + int(ap)
            if s.shape[category_dimension] > 1:

                iStr += ", per category = {}"
                mean_axis = (0,)
                if ap == 1:
                    mean_axis = (0, 1)
                per_category_mean_s = np.mean(s, axis=mean_axis).flatten()
                with np.printoptions(precision=3, suppress=True, sign=" ", floatmode="fixed"):
                    print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s, per_category_mean_s))
            else:
                print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s, ""))
            return mean_s

输出结果为(我的是6类模型):

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

COCO评估输出指定某类AP或者输出每个类别AP结果 的相关文章

随机推荐

  • 解决:硬盘安装Ubuntu16.04引导后加载失败

    按照网上硬盘安装Ubuntu的方法 xff0c 配置完毕后每次都在这个画面之后黑屏 xff0c 卡住不动 xff0c 加载失败 网上找了很多办法 xff0c 有的说是UEFI的问题 xff0c 有的说是N卡不兼容 xff0c 尝试了很多都没
  • Appuim+Pycharm+Pytest 自动化测试环境搭建 Mac版

    这一套流程有很多坑 xff0c 因为最近换主机原因被迫搭了2 xff0c 3次 xff0c 忍无可忍打算记录一下超详细的搭建过程 注意 xff1a 下载环境过程中 xff0c 下文有很多链接地址需要访问GitHub外网 xff0c 访问不了
  • [Mac 基础知识]:用Time Machine 恢复mac系统

    如果您使用 Time Machine 来备份 Mac xff0c 则在系统或启动磁盘损坏时可以恢复系统 Important 使用 Time Machine 备份将您的系统恢复到该备份的源 Mac 若 要将信息传输到新 Mac xff0c 请
  • jetson-tx2-4g ubuntu18系统设置中desktop sharing 无法打开的问题

    1 系统设置中desktop sharing无法打开需要进行以下几步 xff1a sudo apt get install vino dconf editor dconf write org gnome desktop remote acc
  • ubuntu18.04安装xrdp过程

    一 安装桌面环境 以具有 sudo 权限的用户身份键入以下命令 xff0c 以在服务器上安装 Xfce xff1a sudo apt update sudo apt install xfce4 xfce4 goodies xorg dbus
  • 瑞芯微RV1126/1109开发流程之模型转换

    1 环境搭建 xff08 PC端ubuntu16 04搭建rknn环境 xff09 xff08 1 xff09 安装anaconda环境 xff08 为了便于管理自己的环境建议安装 xff0c 安装步骤请自行搜索 xff0c 本人安装ana
  • 瑞芯微RV1126/1109开发流程之驱动升级

    1 1126硬件参数读取 xff08 1 xff09 CPU温度读取 46300和47100分别代表46 3 47 1 xff08 2 xff09 查看1126的NPU xff08 3 xff09 查询NPU驱动版本 dmesg grep
  • 如何在 ubuntu 安装并配置Go?

    如何在 ubuntu 安装并配置Go xff1f 虽然安装和配置go很简单 xff0c 但是很多初学者在第一次安装go环境时会遇到各种坑 这篇博客完整演示一次如何在ubuntu上安装和配置golang 第一步 xff0c 查看系统版本 xf
  • 瑞芯微RV1126/1109开发流程之yolov5部署(c++版本)

    1 ubuntu上安装rv1126交叉编译工具链 方式一 xff1a xff08 1 xff09 下载交叉编译工具 交叉编译器概念 xff1a 交叉编译器可以使我们在主机上编译出可以在嵌入式设备上运行的程序 下载地址 xff1a Downl
  • 瑞芯微RV1126/1109开发流程之资料收藏

    RKMedia Firefly Wiki https blog csdn net u013171226 category 11410227 html目前该博主已经建立专栏 RV1109 RV1126系列 3 RV1109 1126 RKNN
  • 瑞芯微RV1126/1109开发流程之opencv交叉编译

    1 下载opencv并解压 这里的opencv版本是我一直用者的opencv3 4 0 没有opencv的可以到这里 xff08 https opencv org releases page 5 xff09 下载 2 创建build和ins
  • yolov5目标检测算法研究之参考资料

    CSP网络架构 深度学习之CSPNet分析 tt丫的博客 CSDN博客 cspnet结构 深度学习入门小菜鸟 xff0c 希望像做笔记记录自己学的东西 xff0c 也希望能帮助到同样入门的人 xff0c 更希望大佬们帮忙纠错啦 侵权立删 目
  • pytorch统计模型参数量并输出

    有时候需要统计我们自己构建的模型参数 与baseline的网络比较 统计神经网络模型参数 方式一 def get parameter number net total num 61 sum p numel for p in net para
  • TCP传输过程中,客户端异常退出导致服务端send函数崩溃

    在linux下编写TCP socket程序时 xff0c 如果客户端突然退出 xff0c 导致连接中断 xff0c 这个时候服务端如果继续调用send函数发送数据的话 xff0c 会导致整个进程退出 xff0c 这是我们不愿看到的 xff0
  • linux socket编程 close函数详解

    int close int fd close 函数存在于函数库unistd h函数库中 xff1b close 函数用于释放系统分配给套接字的资源 xff0c 该函数即文件操作中常用的close函数 参数fd为需要关闭的套接字文件描述符 x
  • 瑞芯微RV1126/1109开发流程之json交叉编译

    1 下载json源码 下载json源码地址https github com open source parsers jsoncpp https github com open source parsers jsoncpp 本次安装下载jso
  • 瑞芯微RV1126/1109开发流程之redis交叉编译

    1 下载redis源码 下载json源码地址 Releases redis redis GitHub 本次安装下载json版本为redis 5 0 10 tar gz 2 解压 下载下来后解压 tar zxvf redis 5 0 10 t
  • 瑞芯微RV1126/1109开发流程之JDK安装

    因本人在基于rv1126上开发的项目需要用到java xff0c 于是需要在该平台上安装JDK xff0c 在安装过程中遇到些错误 xff1b 边缘视频计算模组均是基于ARM开发的 xff0c 但是ARM的硬件架构类似CPU架构也分32位和
  • kvm GPU直通(kvm GPU passthrough)

    感兴趣的可以站内私信我或直接打开链接显卡虚拟化方案之GPU透传 三 实战篇 为了方便对服务器进行自动管理 我们需要对硬件进行虚拟化 对于显卡而言 Nvidia有专门支持GPU虚拟化的显卡 比如GRID GPU系列 以NVIDIA GRID
  • COCO评估输出指定某类AP或者输出每个类别AP结果

    一 输出单类AP 不需要修改pycocotools coco eval py源代码 34 34 34 COCO Style Evaluations 34 34 34 import json import os import argparse