当前位置:   article > 正文

YOLOv5 | NMS | 手动实现NMS

YOLOv5 | NMS | 手动实现NMS

这个NMS可以按照相同的类别进行nms,不同类别是不会进行nms的,可以加一个“开关”(参数)来控制是否使用进行同类别iou,但是懒得加了哈哈哈哈 ,就是一个if语句,offset这个简直绝了,学的源码的哈哈哈哈哈哈,不信你去看

YOLOv5 | NMS | 源码解析-CSDN博客

  1. import numpy as np
  2. import torch
  3. def nms(boxes, score, conf_thres, iou_thres, classes):
  4. tf = score[:] > conf_thres
  5. score = score[tf]
  6. keep = []
  7. idx = np.argsort(score)[::-1]
  8. pred = torch.hstack((boxes,classes))
  9. offset = pred[:,4:5] * 4096
  10. boxes = pred[:,0:4] + offset
  11. # print(boxes)
  12. while len(idx) > 0:
  13. keep.append(idx[0])
  14. overlap = np.zeros_like(idx[1:], dtype= np.float32)
  15. for i, j in enumerate(idx[1:]):
  16. bbox1 = boxes[idx[0]]
  17. bbox2 = boxes[j]
  18. out = iou(bbox1, bbox2)
  19. overlap[i] = out
  20. idx = idx[1:][overlap < iou_thres]
  21. return keep
  22. # box = []
  23. # for i in keep:
  24. # box.append(boxes[i])
  25. # return box
  26. def iou(bbox1,bbox2):
  27. x1, y1, w1, h1 = bbox1 # left up right bottom
  28. x2, y2, w2, h2 = bbox2
  29. if (x1 <= ((x2+ w2)/2) <= w1) or ((y1 <= ((y2+ h2)/2) <= h1)): # 必须加上等号
  30. left_top_x = max(x1, x2)
  31. left_top_y = max(y1, y2)
  32. right_bottom_x = min(w1, w2)
  33. right_bottom_y = min(h1, h2)
  34. I = (right_bottom_x - left_top_x) * (right_bottom_y - left_top_y)
  35. o = (w1 - x1) * (h1- y1) + (w2 - x2) * (h2 - y2) - I
  36. IoU = I / o
  37. return IoU
  38. else: # 不相交
  39. return 0
  40. if __name__ == '__main__':
  41. boxes = torch.Tensor([
  42. [100, 100, 200, 200],
  43. [120, 110, 220, 210],
  44. [300, 320, 400, 400],
  45. [180, 100, 300, 180]
  46. ])
  47. scores = np.array([0.9, 0.8, 0.7, 0.6])
  48. classes = torch.Tensor([[0],[1],[1],[2]])
  49. # np.concatenate 先转置 可以拼接
  50. out = nms(boxes, scores, 0.5, 0.25,classes)
  51. print(out)

写的比较简单,不会高级的写法

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/371503
推荐阅读
相关标签
  

闽ICP备14008679号