crop_or_pad.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import numpy as np
  2. def crop_or_pad(image, x_min, y_min, x_max, y_max, border_value=0):
  3. """
  4. References:
  5. tf.image.resize_image_with_crop_or_pad
  6. """
  7. assert image.ndim in [2, 3]
  8. assert isinstance(x_min, int) and isinstance(y_min, int)
  9. assert isinstance(x_max, int) and isinstance(y_max, int)
  10. assert (x_min <= x_max) and (y_min <= y_max)
  11. src_height, src_width = image.shape[:2]
  12. dst_height, dst_width = y_max - y_min + 1, x_max - x_min + 1
  13. channels = 1 if image.ndim == 2 else image.shape[2]
  14. if image.ndim == 2:
  15. dst_image_shape = (dst_height, dst_width)
  16. else:
  17. dst_image_shape = (dst_height, dst_width, channels)
  18. if isinstance(border_value, (int, float)):
  19. dst_image = np.full(dst_image_shape, border_value, dtype=image.dtype)
  20. elif isinstance(border_value, tuple):
  21. assert len(border_value) == channels, \
  22. 'Expected the num of elements in tuple equals the channels' \
  23. 'of input image. Found {} vs {}'.format(
  24. len(border_value), channels)
  25. if channels == 1:
  26. dst_image = np.full(dst_image_shape, border_value[0], dtype=image.dtype)
  27. else:
  28. border_value = np.asarray(border_value, dtype=image.dtype)
  29. dst_image = np.empty(dst_image_shape, dtype=image.dtype)
  30. dst_image[:] = border_value
  31. else:
  32. raise ValueError(
  33. 'Invalid type {} for `border_value`.'.format(type(border_value)))
  34. src_x_begin = max(x_min, 0)
  35. src_x_end = min(x_max + 1, src_width)
  36. dst_x_begin = src_x_begin - x_min
  37. dst_x_end = src_x_end - x_min
  38. src_y_begin = max(y_min, 0, )
  39. src_y_end = min(y_max + 1, src_height)
  40. dst_y_begin = src_y_begin - y_min
  41. dst_y_end = src_y_end - y_min
  42. dst_image[dst_y_begin: dst_y_end, dst_x_begin: dst_x_end, ...] = \
  43. image[src_y_begin: src_y_end, src_x_begin: src_x_end, ...]
  44. return dst_image
  45. def crop_or_pad_coords(boxes, image_width, image_height):
  46. """
  47. References:
  48. `mmcv.impad`
  49. `pad` in https://github.com/kpzhang93/MTCNN_face_detection_alignment
  50. `MtcnnDetector.pad` in https://github.com/AITTSMD/MTCNN-Tensorflow
  51. """
  52. x_mins = boxes[:, 0]
  53. y_mins = boxes[:, 1]
  54. x_maxs = boxes[:, 2]
  55. y_maxs = boxes[:, 3]
  56. src_x_begin = np.maximum(x_mins, 0)
  57. src_y_begin = np.maximum(y_mins, 0)
  58. src_x_end = np.minimum(x_maxs + 1, image_width)
  59. src_y_end = np.minimum(y_maxs + 1, image_height)
  60. dst_x_begin = src_x_begin - x_mins
  61. dst_y_begin = src_y_begin - y_mins
  62. dst_x_end = src_x_end - x_mins
  63. dst_y_end = src_y_end - y_mins
  64. coords = np.stack([src_x_begin, src_y_begin, src_x_end, src_y_end,
  65. dst_x_begin, dst_y_begin, dst_x_end, dst_y_end], axis=1)
  66. return coords