本文主要是介绍目标检测paddlex后使用nms代码优化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在主流的python nms解决方案基础上改了两个bug,还改了输入让它适应paddlex的输出(当然也可以不改)。
paddlex目标检测模型部署后推理,结果是个大列表,里面包字典,字典长这样,bbox里面是[x,y,w,h]
{'category_id': 1,'category': 'face','bbox': [118.9930648803711,33.9634895324707,300.4325942993164,272.63801193237305],'score': 0.956941545009613}
以脸部和眼部的目标检测为例,先写几行让它适应主流的nms解决方案,把结构改为[x1,y1.x2,y2](这边写错变量名了,应该是[x,y,w,h],懒得改了)
import numpy as np
face_list = []
eye_list = []
for d in result:x1 = d['bbox'][0]y1 = d['bbox'][1]x2 = d['bbox'][2] y2 = d['bbox'][3]score = d['score']if d['category_id'] == 1:face_list.append([x1, y1, x2, y2, score])# face_list.append(d)elif d['category_id'] == 0:eye_list.append([x1, y1, x2, y2, score])# eye_list.append(d)face_array = np.array(face_list)
eye_array = np.array(eye_list)
改了bug1:当score最大的锚框出现在左上是少统计的bug。bug2:while有时无限循环,加个counter限制最大循环。
加了最小准确率的参数,有时候有用。返回结果改成了直接返回bbox和score,避免了index的改动问题。
def nms(dets, thresh,base_score):scores = dets[:,4]dets = np.delete(dets,scores<base_score,axis=0)x1 = dets[:,0]y1 = dets[:,1]# x1 = dets[:,2]# y1 = dets[:,3]x2 = dets[:,2] + dets[:,0]y2 = dets[:,3] + dets[:,1]areas = (y2-y1+1) * (x2-x1+1)# print(areas)keep = []# index = scores.argsort()[::-1]index = dets[:,4].argsort()[::-1]# print(dets.shape)counter = 0# while len(index) != 0:while len(index) >= 1:counter += 1if counter>10:print('so many times')breaki = index[0] # every time the first is the biggst, and add it directlykeep.append(dets[i])# print(i)x11 = np.maximum(x1[i], x1[index[1:]]) # calculate the points of overlap y11 = np.maximum(y1[i], y1[index[1:]])x22 = np.minimum(x2[i], x2[index[1:]])y22 = np.minimum(y2[i], y2[index[1:]])w = abs(x22-x11+1)h = abs(y22-y11+1)overlaps = w*hious = overlaps / (areas[i]+areas[index[1:]] - overlaps)print(ious)idx = np.where(ious>=thresh)[0]idx = np.append(idx,0)index = np.delete(index,idx, axis=0) return keep
thresh = 0.7
keep = nms(eye_array,thresh=thresh,base_score=0.4)
keep
这篇关于目标检测paddlex后使用nms代码优化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!