cam_label_encode.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import numpy as np
  2. import cv2
  3. from .ar_label_encode import ARLabelEncode
  4. def crop_safe(arr, rect, bbs=[], pad=0):
  5. rect = np.array(rect)
  6. rect[:2] -= pad
  7. rect[2:] += 2 * pad
  8. v0 = [max(0, rect[0]), max(0, rect[1])]
  9. v1 = [
  10. min(arr.shape[0], rect[0] + rect[2]),
  11. min(arr.shape[1], rect[1] + rect[3])
  12. ]
  13. arr = arr[v0[0]:v1[0], v0[1]:v1[1], ...]
  14. if len(bbs) > 0:
  15. for i in range(len(bbs)):
  16. bbs[i, 0] -= v0[0]
  17. bbs[i, 1] -= v0[1]
  18. return arr, bbs
  19. else:
  20. return arr
  21. try:
  22. # pygame==2.5.2
  23. import pygame
  24. from pygame import freetype
  25. except:
  26. pass
  27. class CAMLabelEncode(ARLabelEncode):
  28. """Convert between text-label and text-index."""
  29. def __init__(self,
  30. max_text_length,
  31. character_dict_path=None,
  32. use_space_char=False,
  33. font_path=None,
  34. font_size=30,
  35. font_strength=0.1,
  36. image_shape=[32, 128],
  37. **kwargs):
  38. super(CAMLabelEncode,
  39. self).__init__(max_text_length, character_dict_path,
  40. use_space_char)
  41. self.image_shape = image_shape
  42. if font_path is not None:
  43. freetype.init()
  44. # init font
  45. self.font = freetype.Font(font_path)
  46. self.font.antialiased = True
  47. self.font.origin = True
  48. # choose font style
  49. self.font.size = font_size
  50. self.font.underline = False
  51. self.font.strong = True
  52. self.font.strength = font_strength
  53. self.font.oblique = False
  54. def render_normal(self, font, text):
  55. # get the number of lines
  56. lines = text.split('\n')
  57. lengths = [len(l) for l in lines]
  58. # font parameters:
  59. line_spacing = font.get_sized_height() + 1
  60. # initialize the surface to proper size:
  61. line_bounds = font.get_rect(lines[np.argmax(lengths)])
  62. fsize = (round(2.0 * line_bounds.width),
  63. round(1.25 * line_spacing * len(lines)))
  64. surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)
  65. bbs = []
  66. space = font.get_rect('O')
  67. # space = font.get_rect(' ')
  68. x, y = 0, 0
  69. for l in lines:
  70. x = 2 # carriage-return
  71. y += line_spacing # line-feed
  72. for ch in l: # render each character
  73. if ch.isspace(): # just shift
  74. x += space.width
  75. else:
  76. # render the character
  77. ch_bounds = font.render_to(surf, (x, y), ch)
  78. # ch_bounds.x = x + ch_bounds.x
  79. # ch_bounds.y = y - ch_bounds.y
  80. x += ch_bounds.width + 5
  81. bbs.append(np.array(ch_bounds))
  82. # get the union of characters for cropping:
  83. r0 = pygame.Rect(bbs[0])
  84. rect_union = r0.unionall(bbs)
  85. # get the words:
  86. # words = ' '.join(text.split())
  87. # crop the surface to fit the text:
  88. bbs = np.array(bbs)
  89. surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf),
  90. rect_union,
  91. bbs,
  92. pad=5)
  93. surf_arr = surf_arr.swapaxes(0, 1)
  94. # self.visualize_bb(surf_arr,bbs)
  95. return surf_arr, bbs
  96. def __call__(self, data):
  97. data = super().__call__(data=data)
  98. if data is None:
  99. return None
  100. word = []
  101. for c in data['label'][1:data['length'] + 1]:
  102. word.append(self.character[c])
  103. word = ''.join(word)
  104. # binary mask
  105. binary_mask, bbs = self.render_normal(self.font, word)
  106. cate_aware_surf = np.zeros((binary_mask.shape[0], binary_mask.shape[1],
  107. len(self.character) - 3)).astype(np.uint8)
  108. for id, bb in zip(data['label'][1:data['length'] + 1], bbs):
  109. char_id = id - 1
  110. cate_aware_surf[:, :,
  111. char_id][bb[1]:bb[1] + bb[3], bb[0]:bb[0] +
  112. bb[2]] = binary_mask[bb[1]:bb[1] + bb[3],
  113. bb[0]:bb[0] + bb[2]]
  114. binary_mask = cate_aware_surf
  115. binary_mask = cv2.resize(
  116. binary_mask, (self.image_shape[0] // 2, self.image_shape[1] // 2))
  117. if np.max(binary_mask) > 0:
  118. binary_mask = binary_mask / np.max(binary_mask) # [0 ~ 1]
  119. binary_mask = binary_mask.astype(np.float32)
  120. data['binary_mask'] = binary_mask
  121. return data