box_overlaps.pyx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. cimport cython
  2. import numpy as np
  3. cimport numpy as np
  4. DTYPE = np.float
  5. ctypedef np.float_t DTYPE_t
  6. def bbox_overlaps(
  7. np.ndarray[DTYPE_t, ndim=2] boxes,
  8. np.ndarray[DTYPE_t, ndim=2] query_boxes):
  9. """
  10. Parameters
  11. ----------
  12. boxes: (N, 4) ndarray of float
  13. query_boxes: (K, 4) ndarray of float
  14. Returns
  15. -------
  16. overlaps: (N, K) ndarray of overlap between boxes and query_boxes
  17. """
  18. cdef unsigned int N = boxes.shape[0]
  19. cdef unsigned int K = query_boxes.shape[0]
  20. cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE)
  21. cdef DTYPE_t iw, ih, box_area
  22. cdef DTYPE_t ua
  23. cdef unsigned int k, n
  24. for k in range(K):
  25. box_area = (
  26. (query_boxes[k, 2] - query_boxes[k, 0] + 1) *
  27. (query_boxes[k, 3] - query_boxes[k, 1] + 1)
  28. )
  29. for n in range(N):
  30. iw = (
  31. min(boxes[n, 2], query_boxes[k, 2]) -
  32. max(boxes[n, 0], query_boxes[k, 0]) + 1
  33. )
  34. if iw > 0:
  35. ih = (
  36. min(boxes[n, 3], query_boxes[k, 3]) -
  37. max(boxes[n, 1], query_boxes[k, 1]) + 1
  38. )
  39. if ih > 0:
  40. ua = float(
  41. (boxes[n, 2] - boxes[n, 0] + 1) *
  42. (boxes[n, 3] - boxes[n, 1] + 1) +
  43. box_area - iw * ih
  44. )
  45. overlaps[n, k] = iw * ih / ua
  46. return overlaps