计算目标检测和语义分割的PR

需求描述

  1. 实际工作中,相比于mAP项目更加关心的是特定阈值下的precision和recall结果;
  2. 由于本次的GT中除了目标框之外还存在多边形标注,为此,计算IoU的方式从框与框之间变成了mask之间
    本文的代码适用于MMDetection下的预测结果和COCO格式之间来计算PR结果,具体的实现过程如下:
  • 获取预测结果并保存到json文件中;
  • 解析预测结果和GT;
  • 根据image_id获取每张图的预测结果和GT;
  • 基于mask计算预测结果和GT之间的iou矩阵;
  • 根据iou矩阵得到对应的tp、fp和num_gt;
  • 迭代所有的图像得到所有的tp、fp和num_gt累加,根据公式计算precision和recall;

具体实现

获取预测结果

在MMDetection框架下,通常使用如下的命令来评估模型的结果:

bash tools/dist_test.sh configs/aaaa/gaotie_cascade_rcnn_r50_fpn_1x.py work_dirs/gaotie_cascade_rcnn_r50_fpn_1x/epoch_20.pth 8 --eval bbox

此时能获取到类似下图的mAP结果。
mAP)
而我们需要在某个过程把预测结果保存下,用于后续得到PR结果,具体可以在mmdet/datasets/coco.py的438行位置添加如下代码:

 try:import shutilcocoDt = cocoGt.loadRes(result_files[metric])shutil.copyfile(result_files[metric], "results.bbox.json")

这样我们就可以得到results.bbox.json文件,里面包含的是模型的预测结果,如下图所示。
在这里插入图片描述)

获取GT结果

由于标注时有两个格式:矩形框和多边形,因此在构建GT的coco格式文件时,对于矩形框会将其四个顶点作为多边形传入到segmentations字段,对于多边形会计算出外接矩形传入到bbox字段。
在这里插入图片描述)
为此,获取GT信息的脚本实现如下:

def construct_gt_results(gt_json_path):results = dict()bbox_results = dict()cocoGt = COCO(annotation_file=gt_json_path)# cat_ids = cocoGt.getCatIds()img_ids = cocoGt.getImgIds()for id in img_ids:anno_ids = cocoGt.getAnnIds(imgIds=[id])annotations = cocoGt.loadAnns(ids=anno_ids)for info in annotations:img_id = info["image_id"]if img_id not in results:results[img_id] = list()bbox_results[img_id] = list()bbox = info["bbox"]x1, y1, x2, y2 = bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]# results[img_id].append([x1, y1, x2, y2])# mask = _poly2mask(info["segmentation"], img_h=1544, img_w=2064)results[img_id].append(info["segmentation"])bbox_results[img_id].append([x1, y1, x2, y2])return results, img_ids, cocoGt, bbox_results

输入GT的json文件路径,返回所有图像的分割结果,image_id,COCO对象和目标框结果(用于后续的可视化结果)。

获取预测结果

模型预测出来的结果都是目标框的形式,与上面一样,将目标框的四个顶点作为多边形的分割结果。具体解析脚本如下:

def construct_det_results(det_json_path):results = dict()bbox_results = dict()scores  = dict()with open(det_json_path) as f:json_data = json.load(f)for info in json_data:img_id = info["image_id"]if img_id not in results:results[img_id] = list()scores[img_id] = list()bbox_results[img_id] = list()bbox = info["bbox"]x1, y1, x2, y2 = bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]segm = [[x1, y1, x2, y1, x2, y2, x1, y2]]# mask = _poly2mask(segm, img_h=1544, img_w=2064)score = info["score"]# results[img_id].append([x1, y1, x2, y2, score])results[img_id].append(segm)bbox_results[img_id].append([x1, y1, x2, y2])scores[img_id].append(score)return results, scores, bbox_results

输入的是预测结果的json文件路径,输出是所有图像分割结果、得分和目标框结果。

根据image_id计算单个图像的TP、FP结果

本步骤的具体内容如下:

  1. 根据置信度阈值对预测框进行筛选;
  2. 将所有的多边形转换为mask,用于后续计算IoU;
  3. 得到tp和fp;
  4. 可视化fp和fn结果;

将多边形转换为mask

    if img_id in det_results:# for dt in det_results[img_id]:for idx, score in enumerate(det_scores[img_id]):# score = dt[-1]if score > conf_thrs:mask = _poly2mask(det_results[img_id][idx], img_h=1544, img_w=2064)det_bboxes.append(mask)det_thrs_scores.append(score)plot_det_bboxes.append(det_tmp_bboxes[img_id][idx])if img_id in gt_results:     for segm in gt_results[img_id]:mask = _poly2mask(segm, img_h=1544, img_w=2064)   gt_bboxes.append(mask)plot_gt_bboxes = gt_tmp_bboxes[img_id]

通过_poly2mask函数可以将多边形转换为mask,_poly2mask函数的实现如下。

def _poly2mask(mask_ann, img_h, img_w):"""Private function to convert masks represented with polygon tobitmaps.Args:mask_ann (list | dict): Polygon mask annotation input.img_h (int): The height of output mask.img_w (int): The width of output mask.Returns:numpy.ndarray: The decode bitmap mask of shape (img_h, img_w)."""if isinstance(mask_ann, list):# polygon -- a single object might consist of multiple parts# we merge all parts into one mask rle coderles = maskUtils.frPyObjects(mask_ann, img_h, img_w)rle = maskUtils.merge(rles)elif isinstance(mask_ann['counts'], list):# uncompressed RLErle = maskUtils.frPyObjects(mask_ann, img_h, img_w)else:# rlerle = mask_annmask = maskUtils.decode(rle)return mask

计算单张图像的TP和FP

本文中使用tpfp_default函数实现该功能,具体实现如下:

def tpfp_default(det_bboxes,gt_bboxes,gt_bboxes_ignore=None,det_thrs_scores=None,iou_thr=0.5,area_ranges=None):"""Check if detected bboxes are true positive or false positive.Args:det_bbox (ndarray): Detected bboxes of this image, of shape (m, 5).gt_bboxes (ndarray): GT bboxes of this image, of shape (n, 4).gt_bboxes_ignore (ndarray): Ignored gt bboxes of this image,of shape (k, 4). Default: Noneiou_thr (float): IoU threshold to be considered as matched.Default: 0.5.area_ranges (list[tuple] | None): Range of bbox areas to be evaluated,in the format [(min1, max1), (min2, max2), ...]. Default: None.Returns:tuple[np.ndarray]: (tp, fp) whose elements are 0 and 1. The shape ofeach array is (num_scales, m)."""# an indicator of ignored gtsgt_ignore_inds = np.concatenate((np.zeros(gt_bboxes.shape[0], dtype=np.bool),np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool)))# stack gt_bboxes and gt_bboxes_ignore for convenience# gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore))num_dets = det_bboxes.shape[0]num_gts = gt_bboxes.shape[0]if area_ranges is None:area_ranges = [(None, None)]num_scales = len(area_ranges)# tp and fp are of shape (num_scales, num_gts), each row is tp or fp of# a certain scaletp = np.zeros((num_scales, num_dets), dtype=np.float32)fp = np.zeros((num_scales, num_dets), dtype=np.float32)# if there is no gt bboxes in this image, then all det bboxes# within area range are false positivesif gt_bboxes.shape[0] == 0:if area_ranges == [(None, None)]:fp[...] = 1else:det_areas = (det_bboxes[:, 2] - det_bboxes[:, 0] + 1) * (det_bboxes[:, 3] - det_bboxes[:, 1] + 1)for i, (min_area, max_area) in enumerate(area_ranges):fp[i, (det_areas >= min_area) & (det_areas < max_area)] = 1return tp, fp# ious = bbox_overlaps(det_bboxes, gt_bboxes)# ious = mask_overlaps(det_bboxes, gt_bboxes)ious = mask_wraper(det_bboxes, gt_bboxes)# for each det, the max iou with all gtsious_max = ious.max(axis=1)# for each det, which gt overlaps most with itious_argmax = ious.argmax(axis=1)# sort all dets in descending order by scores# sort_inds = np.argsort(-det_bboxes[:, -1])sort_inds = np.argsort(-det_thrs_scores)for k, (min_area, max_area) in enumerate(area_ranges):gt_covered = np.zeros(num_gts, dtype=bool)# if no area range is specified, gt_area_ignore is all Falseif min_area is None:gt_area_ignore = np.zeros_like(gt_ignore_inds, dtype=bool)else:gt_areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1) * (gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1)gt_area_ignore = (gt_areas < min_area) | (gt_areas >= max_area)for i in sort_inds:if ious_max[i] >= iou_thr:matched_gt = ious_argmax[i]     # 得到对应的GT索引if not (gt_ignore_inds[matched_gt]or gt_area_ignore[matched_gt]):if not gt_covered[matched_gt]:gt_covered[matched_gt] = True   # GT占位tp[k, i] = 1            else:fp[k, i] = 1# otherwise ignore this detected bbox, tp = 0, fp = 0elif min_area is None:fp[k, i] = 1else:bbox = det_bboxes[i, :4]area = (bbox[2] - bbox[0] + 1) * (bbox[3] - bbox[1] + 1)if area >= min_area and area < max_area:fp[k, i] = 1return tp, fp

过程是先获取预测框和GT框之间的IoU矩阵,然后按照置信度排序,将每个预测框分配给GT框得到tp和fp结果。

计算mask的IoU

IoU的定义都是一样的,计算公式如下:
在这里插入图片描述
基于mask计算IoU的实验也非常简单,代码如下:

def mask_overlaps(bboxes1, bboxes2, mode='iou'):assert mode in ['iou', 'iof']bboxes1 = bboxes1.astype(np.bool_)bboxes2 = bboxes2.astype(np.bool_)intersection = np.logical_and(bboxes1, bboxes2)union = np.logical_or(bboxes1, bboxes2)intersection_area = np.sum(intersection)union_area = np.sum(union)iou = intersection_area / union_areareturn iou

而计算预测框和GT之间的IoU矩阵实现如下:

def mask_wraper(bboxes1, bboxes2, mode='iou'):rows = bboxes1.shape[0]     # gtcols = bboxes2.shape[0]     # detious = np.zeros((rows, cols), dtype=np.float32)if rows * cols == 0:return iousfor i in range(rows):for j in range(cols):iou = mask_overlaps(bboxes1[i], bboxes2[j])ious[i, j] = ioureturn ious

至此,通过上述过程就能获取到单张图像的tp和fp结果。

可视化FP和FN结果

此外,我们需要分析模型的badcase,因此,可以将FP和FN的结果可视化出来,我这里是直接将存在问题的图像所有预测框和GT框都画出来了。

    if VIS and (fp > 0 or tp < gt):img_data, path = draw_bbox(img_id=img_id, cocoGt=cocoGt, det_bboxes=plot_det_bboxes, gt_bboxes=plot_gt_bboxes)if fp > 0:save_dir = os.path.join(VIS_ROOT, "tmp/FP/")os.makedirs(save_dir, exist_ok=True)cv2.imwrite(os.path.join(save_dir, os.path.basename(path)+".jpg"), img_data, [int(cv2.IMWRITE_JPEG_QUALITY), 30])if tp < gt:save_dir = os.path.join(VIS_ROOT, "tmp/FN/")os.makedirs(save_dir, exist_ok=True)cv2.imwrite(os.path.join(save_dir, os.path.basename(path)+".jpg"), img_data,[int(cv2.IMWRITE_JPEG_QUALITY), 30])

画框的实现如下:

def draw_bbox(img_id, cocoGt, det_bboxes, gt_bboxes):path = cocoGt.loadImgs(ids=[img_id])[0]["file_name"]img_path = os.path.join(IMG_ROOT, path)img_data = cv2.imread(img_path)for box in det_bboxes:# color_mask = (0, 0, 255)# color_mask = np.array([0, 0, 255], dtype=np.int8)# bbox_mask = box.astype(np.bool)cv2.rectangle(img_data, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 255), 3)# img_data[bbox_mask] = img_data[bbox_mask] * 0.5 + color_mask * 0.5for box in gt_bboxes:# color_mask = np.array([0, 255, 0], dtype=np.int8)# bbox_mask = box.astype(np.bool)# img_data[bbox_mask] = img_data[bbox_mask] * 0.5 + color_mask * 0.5cv2.rectangle(img_data, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 3)return img_data, path

至此,我们实现了单张图像的所有业务逻辑。

多线程计算所有图像结果

通过multiprocessing启动一个进程池来加速结果计算。

def eval_multiprocessing(img_ids):from multiprocessing import Poolpool = Pool(processes=16)results = pool.map(eval_pr, img_ids)# 关闭进程池,表示不再接受新的任务pool.close()# 等待所有任务完成pool.join()return np.sum(np.array(results), axis=0)

计算PR结果

返回所有图像的TP和FP结果之后,就可以计算precision和recall值了。

gt, tp, fp = eval_multiprocessing(img_ids)
eps = np.finfo(np.float32).eps
recalls = tp / np.maximum(gt, eps)
precisions = tp / np.maximum((tp + fp), eps)print("conf_thrs:{:.3f} iou_thrs:{:.3f}, gt:{:d}, TP={:d}, FP={:d}, P={:.3f}, R={:.3f}".format(conf_thrs, iou_thrs, gt, tp, fp, precisions, recalls))

最后,也附上整个实现代码,方便后续复现或者参考。

from multiprocessing import Pool
import os
import numpy as np
import json
from pycocotools.coco import COCO
import cv2
from pycocotools import mask as maskUtilsdef bbox_overlaps(bboxes1, bboxes2, mode='iou'):"""Calculate the ious between each bbox of bboxes1 and bboxes2.Args:bboxes1(ndarray): shape (n, 4)bboxes2(ndarray): shape (k, 4)mode(str): iou (intersection over union) or iof (intersectionover foreground)Returns:ious(ndarray): shape (n, k)"""assert mode in ['iou', 'iof']bboxes1 = bboxes1.astype(np.float32)bboxes2 = bboxes2.astype(np.float32)rows = bboxes1.shape[0]cols = bboxes2.shape[0]ious = np.zeros((rows, cols), dtype=np.float32)if rows * cols == 0:return iousexchange = Falseif bboxes1.shape[0] > bboxes2.shape[0]:bboxes1, bboxes2 = bboxes2, bboxes1ious = np.zeros((cols, rows), dtype=np.float32)exchange = Truearea1 = (bboxes1[:, 2] - bboxes1[:, 0] + 1) * (bboxes1[:, 3] - bboxes1[:, 1] + 1)area2 = (bboxes2[:, 2] - bboxes2[:, 0] + 1) * (bboxes2[:, 3] - bboxes2[:, 1] + 1)for i in range(bboxes1.shape[0]):x_start = np.maximum(bboxes1[i, 0], bboxes2[:, 0])y_start = np.maximum(bboxes1[i, 1], bboxes2[:, 1])x_end = np.minimum(bboxes1[i, 2], bboxes2[:, 2])y_end = np.minimum(bboxes1[i, 3], bboxes2[:, 3])overlap = np.maximum(x_end - x_start + 1, 0) * np.maximum(y_end - y_start + 1, 0)if mode == 'iou':union = area1[i] + area2 - overlapelse:union = area1[i] if not exchange else area2ious[i, :] = overlap / unionif exchange:ious = ious.Treturn iousdef mask_wraper(bboxes1, bboxes2, mode='iou'):rows = bboxes1.shape[0]     # gtcols = bboxes2.shape[0]     # detious = np.zeros((rows, cols), dtype=np.float32)if rows * cols == 0:return iousfor i in range(rows):for j in range(cols):iou = mask_overlaps(bboxes1[i], bboxes2[j])ious[i, j] = ioureturn iousdef mask_overlaps(bboxes1, bboxes2, mode='iou'):assert mode in ['iou', 'iof']bboxes1 = bboxes1.astype(np.bool_)bboxes2 = bboxes2.astype(np.bool_)intersection = np.logical_and(bboxes1, bboxes2)union = np.logical_or(bboxes1, bboxes2)intersection_area = np.sum(intersection)union_area = np.sum(union)iou = intersection_area / union_areareturn ioudef tpfp_default(det_bboxes,gt_bboxes,gt_bboxes_ignore=None,det_thrs_scores=None,iou_thr=0.5,area_ranges=None):"""Check if detected bboxes are true positive or false positive.Args:det_bbox (ndarray): Detected bboxes of this image, of shape (m, 5).gt_bboxes (ndarray): GT bboxes of this image, of shape (n, 4).gt_bboxes_ignore (ndarray): Ignored gt bboxes of this image,of shape (k, 4). Default: Noneiou_thr (float): IoU threshold to be considered as matched.Default: 0.5.area_ranges (list[tuple] | None): Range of bbox areas to be evaluated,in the format [(min1, max1), (min2, max2), ...]. Default: None.Returns:tuple[np.ndarray]: (tp, fp) whose elements are 0 and 1. The shape ofeach array is (num_scales, m)."""# an indicator of ignored gtsgt_ignore_inds = np.concatenate((np.zeros(gt_bboxes.shape[0], dtype=np.bool),np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool)))# stack gt_bboxes and gt_bboxes_ignore for convenience# gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore))num_dets = det_bboxes.shape[0]num_gts = gt_bboxes.shape[0]if area_ranges is None:area_ranges = [(None, None)]num_scales = len(area_ranges)# tp and fp are of shape (num_scales, num_gts), each row is tp or fp of# a certain scaletp = np.zeros((num_scales, num_dets), dtype=np.float32)fp = np.zeros((num_scales, num_dets), dtype=np.float32)# if there is no gt bboxes in this image, then all det bboxes# within area range are false positivesif gt_bboxes.shape[0] == 0:if area_ranges == [(None, None)]:fp[...] = 1else:det_areas = (det_bboxes[:, 2] - det_bboxes[:, 0] + 1) * (det_bboxes[:, 3] - det_bboxes[:, 1] + 1)for i, (min_area, max_area) in enumerate(area_ranges):fp[i, (det_areas >= min_area) & (det_areas < max_area)] = 1return tp, fp# ious = bbox_overlaps(det_bboxes, gt_bboxes)# ious = mask_overlaps(det_bboxes, gt_bboxes)ious = mask_wraper(det_bboxes, gt_bboxes)# for each det, the max iou with all gtsious_max = ious.max(axis=1)# for each det, which gt overlaps most with itious_argmax = ious.argmax(axis=1)# sort all dets in descending order by scores# sort_inds = np.argsort(-det_bboxes[:, -1])sort_inds = np.argsort(-det_thrs_scores)for k, (min_area, max_area) in enumerate(area_ranges):gt_covered = np.zeros(num_gts, dtype=bool)# if no area range is specified, gt_area_ignore is all Falseif min_area is None:gt_area_ignore = np.zeros_like(gt_ignore_inds, dtype=bool)else:gt_areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0] + 1) * (gt_bboxes[:, 3] - gt_bboxes[:, 1] + 1)gt_area_ignore = (gt_areas < min_area) | (gt_areas >= max_area)for i in sort_inds:if ious_max[i] >= iou_thr:matched_gt = ious_argmax[i]     # 得到对应的GT索引if not (gt_ignore_inds[matched_gt]or gt_area_ignore[matched_gt]):if not gt_covered[matched_gt]:gt_covered[matched_gt] = True   # GT占位tp[k, i] = 1            else:fp[k, i] = 1# otherwise ignore this detected bbox, tp = 0, fp = 0elif min_area is None:fp[k, i] = 1else:bbox = det_bboxes[i, :4]area = (bbox[2] - bbox[0] + 1) * (bbox[3] - bbox[1] + 1)if area >= min_area and area < max_area:fp[k, i] = 1return tp, fpdef _poly2mask(mask_ann, img_h, img_w):"""Private function to convert masks represented with polygon tobitmaps.Args:mask_ann (list | dict): Polygon mask annotation input.img_h (int): The height of output mask.img_w (int): The width of output mask.Returns:numpy.ndarray: The decode bitmap mask of shape (img_h, img_w)."""if isinstance(mask_ann, list):# polygon -- a single object might consist of multiple parts# we merge all parts into one mask rle coderles = maskUtils.frPyObjects(mask_ann, img_h, img_w)rle = maskUtils.merge(rles)elif isinstance(mask_ann['counts'], list):# uncompressed RLErle = maskUtils.frPyObjects(mask_ann, img_h, img_w)else:# rlerle = mask_annmask = maskUtils.decode(rle)return maskdef construct_det_results(det_json_path):results = dict()bbox_results = dict()scores  = dict()with open(det_json_path) as f:json_data = json.load(f)for info in json_data:img_id = info["image_id"]if img_id not in results:results[img_id] = list()scores[img_id] = list()bbox_results[img_id] = list()bbox = info["bbox"]x1, y1, x2, y2 = bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]segm = [[x1, y1, x2, y1, x2, y2, x1, y2]]# mask = _poly2mask(segm, img_h=1544, img_w=2064)score = info["score"]# results[img_id].append([x1, y1, x2, y2, score])results[img_id].append(segm)bbox_results[img_id].append([x1, y1, x2, y2])scores[img_id].append(score)return results, scores, bbox_resultsdef construct_gt_results(gt_json_path):results = dict()bbox_results = dict()cocoGt = COCO(annotation_file=gt_json_path)# cat_ids = cocoGt.getCatIds()img_ids = cocoGt.getImgIds()for id in img_ids:anno_ids = cocoGt.getAnnIds(imgIds=[id])annotations = cocoGt.loadAnns(ids=anno_ids)for info in annotations:img_id = info["image_id"]if img_id not in results:results[img_id] = list()bbox_results[img_id] = list()bbox = info["bbox"]x1, y1, x2, y2 = bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]# results[img_id].append([x1, y1, x2, y2])# mask = _poly2mask(info["segmentation"], img_h=1544, img_w=2064)results[img_id].append(info["segmentation"])bbox_results[img_id].append([x1, y1, x2, y2])return results, img_ids, cocoGt, bbox_resultsdef draw_bbox(img_id, cocoGt, det_bboxes, gt_bboxes):path = cocoGt.loadImgs(ids=[img_id])[0]["file_name"]img_path = os.path.join(IMG_ROOT, path)img_data = cv2.imread(img_path)for box in det_bboxes:# color_mask = (0, 0, 255)# color_mask = np.array([0, 0, 255], dtype=np.int8)# bbox_mask = box.astype(np.bool)cv2.rectangle(img_data, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 255), 3)# img_data[bbox_mask] = img_data[bbox_mask] * 0.5 + color_mask * 0.5for box in gt_bboxes:# color_mask = np.array([0, 255, 0], dtype=np.int8)# bbox_mask = box.astype(np.bool)# img_data[bbox_mask] = img_data[bbox_mask] * 0.5 + color_mask * 0.5cv2.rectangle(img_data, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 3)return img_data, pathdef eval_pr(img_id):tp, fp, gt = 0, 0, 0gt_bboxes, gt_ignore = [], []det_bboxes = list()gt_bboxes = list()det_thrs_scores = list()plot_det_bboxes = list()plot_gt_bboxes  = list()if img_id in det_results:# for dt in det_results[img_id]:for idx, score in enumerate(det_scores[img_id]):# score = dt[-1]if score > conf_thrs:mask = _poly2mask(det_results[img_id][idx], img_h=1544, img_w=2064)det_bboxes.append(mask)det_thrs_scores.append(score)plot_det_bboxes.append(det_tmp_bboxes[img_id][idx])if img_id in gt_results:     for segm in gt_results[img_id]:mask = _poly2mask(segm, img_h=1544, img_w=2064)   gt_bboxes.append(mask)plot_gt_bboxes = gt_tmp_bboxes[img_id]det_bboxes = np.array(det_bboxes)gt_bboxes = np.array(gt_bboxes)det_thrs_scores = np.array(det_thrs_scores)gt_ignore = np.array(gt_ignore).reshape(-1, 4)if len(gt_bboxes) > 0:if len(det_bboxes) == 0:tp, fp = 0, 0 else:tp, fp = tpfp_default(det_bboxes, gt_bboxes, gt_ignore, det_thrs_scores, iou_thrs)tp, fp = np.sum(tp == 1), np.sum(fp == 1)gt = len(gt_bboxes)else:fp = len(det_bboxes)if VIS and (fp > 0 or tp < gt):img_data, path = draw_bbox(img_id=img_id, cocoGt=cocoGt, det_bboxes=plot_det_bboxes, gt_bboxes=plot_gt_bboxes)if fp > 0:save_dir = os.path.join(VIS_ROOT, "tmp/FP/")os.makedirs(save_dir, exist_ok=True)cv2.imwrite(os.path.join(save_dir, os.path.basename(path)+".jpg"), img_data, [int(cv2.IMWRITE_JPEG_QUALITY), 30])if tp < gt:save_dir = os.path.join(VIS_ROOT, "tmp/FN/")os.makedirs(save_dir, exist_ok=True)cv2.imwrite(os.path.join(save_dir, os.path.basename(path)+".jpg"), img_data,[int(cv2.IMWRITE_JPEG_QUALITY), 30])return gt, tp, fpdef eval_multiprocessing(img_ids):from multiprocessing import Poolpool = Pool(processes=16)results = pool.map(eval_pr, img_ids)# 关闭进程池,表示不再接受新的任务pool.close()# 等待所有任务完成pool.join()return np.sum(np.array(results), axis=0)if __name__ == '__main__':VIS = 1IMG_ROOT = "gaotie_data"VIS_ROOT = 'badcase-vis-test-2/'conf_thrs = 0.5iou_thrs  = 0.001det_json_path = "results.bbox.json"gt_json_path  = "datasets/gaotie_test_data/annotations/test5_seg_removed.json"det_results, det_scores, det_tmp_bboxes = construct_det_results(det_json_path)gt_results, img_ids, cocoGt, gt_tmp_bboxes  = construct_gt_results(gt_json_path)gt, tp, fp = eval_multiprocessing(img_ids)eps = np.finfo(np.float32).epsrecalls = tp / np.maximum(gt, eps)precisions = tp / np.maximum((tp + fp), eps)print("conf_thrs:{:.3f} iou_thrs:{:.3f}, gt:{:d}, TP={:d}, FP={:d}, P={:.3f}, R={:.3f}".format(conf_thrs, iou_thrs, gt, tp, fp, precisions, recalls))

总结

本文针对目标检测任务中GT存在多边形情况下给出了如下计算数据集的PR结果,基于mask来计算IoU,与语义分割计算IoU的思路一致,最后也给出了所有的实现代码作为参考。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/276958.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于单片机智能家具无线遥控控制系统设计

**单片机设计介绍&#xff0c;基于单片机智能家具无线遥控控制系统设计 文章目录 一 概要二、功能设计设计思路 三、 软件设计原理图 五、 程序六、 文章目录 一 概要 基于单片机的智能家具无线遥控控制系统设计可以实现对家具&#xff08;如灯具、窗帘、空调等&#xff09;的…

yolov8实战第二天——yolov8训练结果分析(保姆式解读)

yolov8实战第一天——yolov8部署并训练自己的数据集&#xff08;保姆式教程&#xff09;-CSDN博客 我们在上一篇文章训练了一个老鼠的yolov8检测模型&#xff0c;训练结果如下图&#xff0c;接下来我们就详细解析下面几张图。 一、混淆矩阵 正确挑选&#xff08;正确&#…

STM32 寄存器配置笔记——USART DMA发送

一、DMA介绍 直接存储器存取(DMA)用来提供在外设和存储器之间或者存储器和存储器之间的高速数据传 输。无须CPU干预&#xff0c;数据可以通过DMA快速地移动&#xff0c;这就节省了CPU的资源来做其他操作。当产品对于时序要求较严格时&#xff0c;外设使用DMA的方式能够减轻CPU负…

使用Axure RP结合内网穿透工具制作本地静态web页面并实现公网访问

作者简介&#xff1a; 懒大王敲代码&#xff0c;正在学习嵌入式方向有关课程stm32&#xff0c;网络编程&#xff0c;数据结构C/C等 今天给大家讲解使用Axure RP结合内网穿透工具制作本地静态web页面并实现公网访问&#xff0c;希望大家能觉得实用&#xff01; 欢迎大家点赞 &am…

Linux--Docker容器

这里写目录标题 简介名词解释作用 指令在本地创建容器的过程&#xff1a;&#xff08;这里以tomcat为例&#xff09;访问容器端口映射目录挂载验证端口映射验证目录挂载 删除镜像多小组访问容器mysql容器 一级目录二级目录二级目录二级目录 一级目录二级目录二级目录二级目录 一…

民生银行三季度业绩双降:资产质量下行,屡吃“千万元”级别罚单

撰稿|行星 来源|贝多财经 中国银行研究院发布《2023年四季度经济金融展望报告》显示&#xff0c;今年以来全球经济呈现弱修复态势&#xff0c;虽然国内依旧面临较大外部环境压力&#xff0c;外需总体回落&#xff0c;但三季度经济持续恢复&#xff0c;经济企稳趋势初显。 在此…

宝塔面板快速搭建本地网站结合内网穿透实现远程访问【无需公网IP】

文章目录 前言1. 环境安装2. 安装cpolar内网穿透3. 内网穿透4. 固定http地址5. 配置二级子域名6. 创建一个测试页面 前言 宝塔面板作为简单好用的服务器运维管理面板&#xff0c;它支持Linux/Windows系统&#xff0c;我们可用它来一键配置LAMP/LNMP环境、网站、数据库、FTP等&…

嵌入式C语言变量、数组、指针初始化的多种操作

在敲代码的时候&#xff0c;我们会给变量一个初始值&#xff0c;以防止因为编译器的原因造成变量初始值的不确定性。 对于数值类型的变量往往初始化为0&#xff0c;但对于其他类型的变量&#xff0c;如字符型、指针型等变量等该如何初始化呢&#xff1f; 数值类变量初始化 整…

vue2 echarts不同角色多个类型数据的柱状图

前端代码&#xff1a; 先按照echarts插件。在页面里引用 import * as echarts from "echarts";设置div <div style"width:100%;height:250px;margin-top: 4px;" id"addressChart"></div>方法: addressEcharts() {const option {g…

python 实现PC、app自动化全过程(包括CI\CD)

python main.py allure generate C:\devlopePath\new_nergeryApp_auto\reports -o C:\devlopePath\new_nergeryApp_auto\result --clean allure open C:\devlopePath\new_nergeryApp_auto\result

基于JAVA的校园电子商城系统论文

摘 要 网络技术和计算机技术发展至今&#xff0c;已经拥有了深厚的理论基础&#xff0c;并在现实中进行了充分运用&#xff0c;尤其是基于计算机运行的软件更是受到各界的关注。加上现在人们已经步入信息时代&#xff0c;所以对于信息的宣传和管理就很关键。因此校园购物信息的…

金蝶云星空协同开发环境应用内执行单据类型脚本

文章目录 金蝶云星空协同开发环境应用内执行单据类型脚本业务界面查询单据类型表数据导出数据执行数据库脚本单据类型xml检验是否执行成功检查数据库检查业务数据 金蝶云星空协同开发环境应用内执行单据类型脚本 业务界面 查询单据类型表数据 先使用类型中文在单据类型多语言…