【实例分割|Detectron2】计算实例漏检数量

2023-05-16

文章目录

  • 问题背景
  • 代码实现
    • 计算 COCO 标签中实例数量
    • 结合 Detectron2 模型预测代码

问题背景

对于单张图像中实例超过 100 的情形(maskrcnn 预测超过 100 个实例),难免会出现漏检的情形,通过代码实现对漏检数量的计算,作为评估的指标。

代码实现

计算 COCO 标签中实例数量

"""
从标签文件中计算每张图像中实例的数量
"""

import os
import json
import string
import numpy as np

def count_instances(json_path: string) -> dict:
    with open(json_path,'rb') as f:

        # 打印 json 文件的相关信息
        data = json.load(f)
        print("Keys: ", data.keys())
        print("Images num: ", len(data["images"]))
        print("Annotations num: ", len(data["annotations"]))

        # 获取所有标签文件名称
        file_name_list = []
        for image in data["images"]:
            file_name_list.append(image["file_name"])
        # print("file_name list: ", file_name_list)

        # 获取每个标签文件中的实例数量
        count = np.zeros(len(data["images"]), dtype=int)
        for annotation in data["annotations"]:
            count[annotation["image_id"] - 1] = count[annotation["image_id"] - 1] + 1
        # print("count list: ", count.tolist())

    f.close()

    return dict(zip(file_name_list, count))

if __name__ == "__main__":
    path = "/home/zth/HardDisk/Datasets/nematode/origin_dataset/coco/annotations/instances_test.json"

    print(count_instances(path))

结合 Detectron2 模型预测代码

    if args.input:
        
        # 从标签文件中统计实例数量
        path = "/home/zth/HardDisk/Datasets/nematode/nematode_new/annotations/instances_test2017.json"
        instance_num =  count_instances(path)
        print(instance_num)

        if len(args.input) == 1:
            args.input = glob.glob(os.path.expanduser(args.input[0]))
            assert args.input, "The input path(s) was not found"
        for path in tqdm.tqdm(args.input, disable=not args.output):

            file_name = path.split("/")[-1]

            # use PIL, to be consistent with evaluation
            img = read_image(path, format="BGR")
            start_time = time.time()
            predictions, visualized_output, mask = demo.run_on_image(img)
            logger.info(
                "{}: {} in {:.2f}s".format(
                    path,
                    "detected {} instances".format(len(predictions["instances"]))
                    if "instances" in predictions
                    else "finished",
                    time.time() - start_time,
                )
            )

            print(" 图像分辨率:", img.shape, "实例数量:", len(predictions["instances"]), " 漏检数量:", instance_num[file_name] - len(predictions["instances"]), " 误检率:", (instance_num[file_name] - len(predictions["instances"]))/len(predictions["instances"]))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【实例分割|Detectron2】计算实例漏检数量 的相关文章

随机推荐