operators.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. """
  2. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. from __future__ import unicode_literals
  20. import sys
  21. import six
  22. import cv2
  23. import numpy as np
  24. class DecodeImage(object):
  25. """ decode image """
  26. def __init__(self, img_mode='RGB', channel_first=False, **kwargs):
  27. self.img_mode = img_mode
  28. self.channel_first = channel_first
  29. def __call__(self, data):
  30. img = data['image']
  31. if six.PY2:
  32. assert type(img) is str and len(
  33. img) > 0, "invalid input 'img' in DecodeImage"
  34. else:
  35. assert type(img) is bytes and len(
  36. img) > 0, "invalid input 'img' in DecodeImage"
  37. img = np.frombuffer(img, dtype='uint8')
  38. img = cv2.imdecode(img, 1)
  39. if img is None:
  40. return None
  41. if self.img_mode == 'GRAY':
  42. img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  43. elif self.img_mode == 'RGB':
  44. assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape)
  45. img = img[:, :, ::-1]
  46. if self.channel_first:
  47. img = img.transpose((2, 0, 1))
  48. data['image'] = img
  49. return data
  50. class NormalizeImage(object):
  51. """ normalize image such as substract mean, divide std
  52. """
  53. def __init__(self, scale=None, mean=None, std=None, order='chw', **kwargs):
  54. if isinstance(scale, str):
  55. scale = eval(scale)
  56. self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
  57. mean = mean if mean is not None else [0.485, 0.456, 0.406]
  58. std = std if std is not None else [0.229, 0.224, 0.225]
  59. shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)
  60. self.mean = np.array(mean).reshape(shape).astype('float32')
  61. self.std = np.array(std).reshape(shape).astype('float32')
  62. def __call__(self, data):
  63. img = data['image']
  64. from PIL import Image
  65. if isinstance(img, Image.Image):
  66. img = np.array(img)
  67. assert isinstance(img,
  68. np.ndarray), "invalid input 'img' in NormalizeImage"
  69. data['image'] = (
  70. img.astype('float32') * self.scale - self.mean) / self.std
  71. return data
  72. class ToCHWImage(object):
  73. """ convert hwc image to chw image
  74. """
  75. def __init__(self, **kwargs):
  76. pass
  77. def __call__(self, data):
  78. img = data['image']
  79. from PIL import Image
  80. if isinstance(img, Image.Image):
  81. img = np.array(img)
  82. data['image'] = img.transpose((2, 0, 1))
  83. return data
  84. class KeepKeys(object):
  85. def __init__(self, keep_keys, **kwargs):
  86. self.keep_keys = keep_keys
  87. def __call__(self, data):
  88. data_list = []
  89. for key in self.keep_keys:
  90. data_list.append(data[key])
  91. return data_list
  92. class DetResizeForTest(object):
  93. def __init__(self, **kwargs):
  94. super(DetResizeForTest, self).__init__()
  95. self.resize_type = 0
  96. if 'image_shape' in kwargs:
  97. self.image_shape = kwargs['image_shape']
  98. self.resize_type = 1
  99. elif 'limit_side_len' in kwargs:
  100. self.limit_side_len = kwargs['limit_side_len']
  101. self.limit_type = kwargs.get('limit_type', 'min')
  102. elif 'resize_long' in kwargs:
  103. self.resize_type = 2
  104. self.resize_long = kwargs.get('resize_long', 960)
  105. else:
  106. self.limit_side_len = 736
  107. self.limit_type = 'min'
  108. def __call__(self, data):
  109. img = data['image']
  110. src_h, src_w, _ = img.shape
  111. if self.resize_type == 0:
  112. # img, shape = self.resize_image_type0(img)
  113. img, [ratio_h, ratio_w] = self.resize_image_type0(img)
  114. elif self.resize_type == 2:
  115. img, [ratio_h, ratio_w] = self.resize_image_type2(img)
  116. else:
  117. # img, shape = self.resize_image_type1(img)
  118. img, [ratio_h, ratio_w] = self.resize_image_type1(img)
  119. data['image'] = img
  120. data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w])
  121. return data
  122. def resize_image_type1(self, img):
  123. resize_h, resize_w = self.image_shape
  124. ori_h, ori_w = img.shape[:2] # (h, w, c)
  125. ratio_h = float(resize_h) / ori_h
  126. ratio_w = float(resize_w) / ori_w
  127. img = cv2.resize(img, (int(resize_w), int(resize_h)))
  128. # return img, np.array([ori_h, ori_w])
  129. return img, [ratio_h, ratio_w]
  130. def resize_image_type0(self, img):
  131. """
  132. resize image to a size multiple of 32 which is required by the network
  133. args:
  134. img(array): array with shape [h, w, c]
  135. return(tuple):
  136. img, (ratio_h, ratio_w)
  137. """
  138. limit_side_len = self.limit_side_len
  139. h, w, _ = img.shape
  140. # limit the max side
  141. if self.limit_type == 'max':
  142. if max(h, w) > limit_side_len:
  143. if h > w:
  144. ratio = float(limit_side_len) / h
  145. else:
  146. ratio = float(limit_side_len) / w
  147. else:
  148. ratio = 1.
  149. else:
  150. if min(h, w) < limit_side_len:
  151. if h < w:
  152. ratio = float(limit_side_len) / h
  153. else:
  154. ratio = float(limit_side_len) / w
  155. else:
  156. ratio = 1.
  157. resize_h = int(h * ratio)
  158. resize_w = int(w * ratio)
  159. resize_h = int(round(resize_h / 32) * 32)
  160. resize_w = int(round(resize_w / 32) * 32)
  161. try:
  162. if int(resize_w) <= 0 or int(resize_h) <= 0:
  163. return None, (None, None)
  164. img = cv2.resize(img, (int(resize_w), int(resize_h)))
  165. except:
  166. print(img.shape, resize_w, resize_h)
  167. sys.exit(0)
  168. ratio_h = resize_h / float(h)
  169. ratio_w = resize_w / float(w)
  170. # return img, np.array([h, w])
  171. return img, [ratio_h, ratio_w]
  172. def resize_image_type2(self, img):
  173. h, w, _ = img.shape
  174. resize_w = w
  175. resize_h = h
  176. # Fix the longer side
  177. if resize_h > resize_w:
  178. ratio = float(self.resize_long) / resize_h
  179. else:
  180. ratio = float(self.resize_long) / resize_w
  181. resize_h = int(resize_h * ratio)
  182. resize_w = int(resize_w * ratio)
  183. max_stride = 128
  184. resize_h = (resize_h + max_stride - 1) // max_stride * max_stride
  185. resize_w = (resize_w + max_stride - 1) // max_stride * max_stride
  186. img = cv2.resize(img, (int(resize_w), int(resize_h)))
  187. ratio_h = resize_h / float(h)
  188. ratio_w = resize_w / float(w)
  189. return img, [ratio_h, ratio_w]