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)
删除后: