通过nms删除json文件中重合度较高的bbox,并将删除后的保存

json格式如下:
目的:nms删除掉重合bbox,并将删除后的json文件同样保存到相同json文件中
在这里插入图片描述
代码如下:

import json
import numpy as np
import os

def py_cpu_nms(dets, thresh):
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4]

    areas = (x2 - x1 + 1) * (y2 - y1 + 1)  # 计算出所有图片的面积
    order = scores.argsort()[::-1]  # 图片评分按升序排序

    keep = []  # 用来存放最后保留的图片的相应评分
    while order.size > 0:
        i = order[0]  # i 是还未处理的图片中的最大评分
        keep.append(i)  
        tmp=x1[order[1:]]
        xxxx = x1[i]
        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])

        # 计算出各个相交矩形的面积
        w = np.maximum(0.0, xx2 - xx1 + 1)
        h = np.maximum(0.0, yy2 - yy1 + 1)
        inter = w * h
        # 计算重叠比例
        ovr = inter / (areas[i] + areas[order[1:]] - inter)

        # 只保留比例小于阙值的图片,然后继续处理
        inds = np.where(ovr <= thresh)[0]
        indsd= inds+1
        order = order[inds + 1]

    return keep

#nms_idx = []
json_path = '/home/zhaotongdong/桌面/aa/'
json_list = os.listdir(json_path)
for json_i in json_list:
    dets = []
    json_path_i = json_path + json_i
    with open(json_path_i) as f:
        ann = json.load(f)
        print(len(ann))
      
        for i in ann: 
            x1 = i['x']
            y1 = i['y']
            x2 = x1 + i['w']
            y2 = y1 + i['h']
            score = i['score']
            j = np.array([x1, y1, x2, y2, score])
            dets.append(j)
    
    detection = np.array(dets)
    
    if(len(detection) > 1):
        idx = py_cpu_nms(detection, 0.7)
        print(idx)
        if(len(idx) != len(detection)):
            j = 0
            for i in range(len(detection)):
                if i not in idx: 
                    print(j)
                    del ann[i-j] #这里之所以要减去j是因为,每当你删掉读取到的一个json元素,ann中的数目也会减少
                    j+=1
    with open(json_path_i, 'w') as file:
        json.dump(ann, file, indent = 2)

删除后:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值